var Player = function(_container, _playlist, _options) {
    ///////////////////////////////////////
    // Déclaration des attributs
    ///////////////////////////////////////
    var instance = this;

    this.playlist = {
        image : new Array(),
        video : new Object(),
        imageCount : 0
    };

    this.options = {
        autoStart : true,
        mode: "image",
        showTime : 700,
        fadeSpeed : 400,
        afterFadeInEvent : null,
        flowplayer : {
            config : {
                src : "player/flowplayer.swf",
                wmode: 'opaque',
                debug : true
            },
            options : {
                clip : {
                    autoPlay : false,
                    onFinish : function () {
                        instance.closeVideoMode();
                    }
                },
                plugins : {
                    controls : {
                        url : "player/flowplayer.controls.swf"
                    }
                },
                playlist : []
            }
        },
        lightbox : {}
    };


    this.indexCurrentImage = null;
    this.mode = null;
    this.flowplayer = null;
    this.stopped = false;
    this.ligthbox = false;

    // Gestion du timer
    this.timer = null;

    // Tableau contenant les div[index_image]
    this.divs = new Array();









    // Creer une image non visible dans un lien et du panel info
    this.createImage = function (index) {
        var image = this.playlist.image[index];
        var div = $("<div/>").addClass("image").attr("index_image", index);

        var a = $("<a/>")
        .attr("href", image.srcNormal)
        .attr("rel", "slideshow")
        .attr("title", image.legende);


        if (this.playlist.image.length > 1) {
            a.hover(function () {instance.hoverEvent("in", index);}, function() {instance.hoverEvent("out", index);});
        }
        
        var img = $("<img/>").attr("src", image.srcThumbnail).attr("alt", image.legende).attr("title", image.legende);
        a.append(img);
        a.colorbox(instance.options.lightbox);
        div.append(a);
        return div;
    }

    this.createMenu = function () {
        this.player_menu.append(
            $('<div id="player_menu_image"></div>').append(
                $('<div class="background"></div>')
            ).append(
                $('<div class="controls"></div>').append(
                    // Déclanchement du click sur l'image pour l'ouverture de la lightbox
                    $('<div class="fullscreen"></div>').append(
                        $('<a href="#"></a>').click(function () {
                            $("div[index_image=" + instance.indexCurrentImage + "] a", this.player_content_image).click();
                        })
                    )
                ).append(
                    this.createMenuImageNavigation()
                ).append(
                    $('<div class="copyright"></div>')
                )
            )
        ).append(
            $('<div id="player_menu_tab"></div>').append(
                $('<div class="button video inactive"></div>').append(
                    $('<div class="picto"></div>')
                ).append(
                    $('<a href="#">VIDEO</a>').click(function () {instance.openVideoMode();})
                )
            ).append(
                $('<div class="button image active">').append(
                    $('<div class="picto"></div>')
                ).append(
                    $('<a href="#">PHOTOS</a>').click(function () {instance.closeVideoMode();})
                )
            )
        );
    }

    this.createMenuImageNavigation = function () {
        var ul = $("<ul>");

        if (this.playlist.image.length > 1) {
            var li = $('<li class="arrow_left"></li>').append(
                $('<a href="#"></a>').click(function () {instance.previousImage();})
            );
            ul.append(li);
        }

       for(var index in this.playlist.image) {
            li = $('<li class="circle"></li>').append(
                $('<a href="#"></a>').click(
                    (function (index) {
                        return function () {
                            instance.transition(index);
                        }
                    })(index)
                )
            );
            ul.append(li);
       }

       if (this.playlist.image.length > 1) {
           li = $('<li class="arrow_right"></li>').append(
                $('<a href="#"></a>').click(function () {instance.nextImage();})
            );
       }

        ul.append(li);
        return ul;
    }


    // Ajouter un lecteur flash au HTML
    this.loadPlayer = function (_config, _options) {
        var config = this.options.flowplayer.config;
        var options = this.options.flowplayer.options;
        
        if (_config != null) config = $.extend(true, config, _config);
        if (_options != null) options = $.extend(true, options, _options);

        //this.player_content_video.attr("href", this.playlist.video.url);
        if (typeof(this.playlist.video.splash) == 'string' && this.playlist.video.splash.length > 0) {
            options.playlist.push({
                url : this.playlist.video.splash,
                autoPlay : true,
                onFinish : function () { return false; }
            });
        }
        options.playlist.push({url : this.playlist.video.url});
        
        if (this.player.hasClass("singlemode")) {
            options.plugins.controls.bottom = 0;
            options.plugins.controls.timeColor = '#000000';
            options.plugins.controls.durationColor = '#000000';
            options.plugins.controls.bufferColor = '#FFFFFF';
            options.plugins.controls.sliderColor = '#000000';
            options.plugins.controls.backgroundColor = '#858585';
            options.plugins.controls.volumeSliderColor = '#FFFFFF';
        }
        this.flowplayer = $f(this.player_content_video.attr('id'), config, options);
    }

    this.unloadPlayer = function () {
        if (this.flowplayer != null) {
            if (this.flowplayer.isPlaying()) this.flowplayer.stop();
            this.flowplayer.unload();
            this.flowplayer = null;
            this.player_content_video.empty();
        }
    }

    // Ajuste le viewer pour le mode video
    this.openVideoMode = function () {
        if (this.mode != "video") {
            this.stop();
            this.mode = "video";
            this.player.removeClass("mode_image").addClass("mode_video");
            this.loadPlayer();
        }
    }


    // Ajuste le viewer pour le mode image
    this.closeVideoMode = function () {
        if (this.mode != "image") {
            this.unloadPlayer();
            this.mode = "image";
            this.player.removeClass("mode_video").addClass("mode_image");
            this.resume();
        }
    }

    // Ajoute une image non visible au container html
    this.loadImage = function (index) {
        if (this.playlist.image[index].loaded == false) {
            this.player_content_image.append(this.createImage(index));
            this.playlist.image[index].loaded = true;
        }
    }

    this.loadAllImages = function () {
        for(var i = 0; i < this.playlist.image.length; i++) this.loadImage(i);
    }

    this.createTimer = function (callback, time, force) {
        if (this.stopped == false || force == true) {
            this.timer = setTimeout(callback, time);
            return true;
        } else return false;
    }

    // Charge la premiere image dans le html et lance le fadeIn
    this.start = function (index) {
        if (index == null) index = 0;
        if (this.playlist.image.length > 0) {
            this.loadImage(index);
            this.stopped = false;
            if (this.options.mode == "image") this.closeVideoMode();
            else this.openVideoMode();
        } else this.openVideoMode();
    }

    this.resume = function () {
        this.stopped = false;
        this.transition();
    }

    // Annule le timer programmé
    this.stop = function () {
        instance.stopped = true;
        clearTimeout(instance.timer);
        instance.timer = null;
    }

    // Retourne l'indice precedent l'indice de l'image courante ou de l'indice donné en parametre
    this.getIndicePreviousImage = function (index) {
        if (index == null) {
            if (this.indexCurrentImage == null) return 0;
            else index = this.indexCurrentImage;
        }

        if (index - 1 >= 0) index -= 1;
        else index = this.playlist.imageCount - 1;

        return index;
    }

    // Retourne l'indice suivant l'indice de l'image courante ou de l'indice donné en parametre
    this.getIndiceNextImage = function (index) {
        if (index == null) {
            if (this.indexCurrentImage == null) return 0;
            else index = this.indexCurrentImage;
        }

        if (this.playlist.imageCount > index + 1) index += 1;
        else index = 0;

        return index;
    }

    // Fait l'effet de transition entre les 2 images
    this.transition = function (index) {
        clearTimeout(this.timer);
        this.timer = null;
        if (this.mode == "video") {
            this.closeVideoMode(
                function () {
                    instance.transition(index);
                });
        } else {
            if (this.indexCurrentImage == null || this.playlist.image.length > 1) {
                this.fadeOut();
                this.fadeIn(index);
            }
        }
    }

    this.previousImage = function () {
        this.transition(this.getIndicePreviousImage());
    }

    this.nextImage = function () {
        this.transition(this.getIndiceNextImage());
    }




    // Fait apparait une image en augmentant l'opacité
    // A la fin de l'effet on relance une transition avec un timer
    this.fadeIn = function (index) {
        if (index == null) index = this.getIndiceNextImage();
        else {
            index = parseInt(index);
            this.loadImage(index);
        }

        if (this.divs[index] == null) this.divs[index] = $("div[index_image='" + index + "']", this.player_content_image).first();

        this.divs[index].fadeIn(this.options.fadeSpeed, function() {
            instance.indexCurrentImage = index;
            instance.afterFadeInEvent();
        });
    }

    this.afterFadeInEvent = function () {
        var index = instance.indexCurrentImage;

        instance.player_menu_image_copyright.text(instance.playlist.image[index].copyright);
        $(".controls .circle.active", instance.player_menu_image).removeClass("active");
        $(".controls .circle:eq(" + index + ")", instance.player_menu_image).addClass("active");

        if (instance.playlist.image.length > 1) {
            instance.loadImage(instance.getIndiceNextImage());

            // Timer pour relancer une transition
            instance.createTimer(function() {instance.transition();}, instance.options.showTime);

            // Préchargement de l'image affiché dans la prochaine transition
            if (typeof(instance.options.afterFadeInEvent) == "function") instance.options.afterFadeInEvent(instance.indexCurrentImage);
        }
    }

    // Fait disparaitre une image en diminuant l'opacité
    this.fadeOut = function () {
        if (this.divs[this.indexCurrentImage] == null) this.divs[this.indexCurrentImage] = $("div[index_image='" + this.indexCurrentImage + "']", this.player_content_image).first();
        this.divs[this.indexCurrentImage].fadeOut(this.options.fadeSpeed);
    }

    this.hoverEvent = function (InOrOut) {
        if (this.mode == "image") {
            if (InOrOut == "in") this.stop();
            else {
                if (this.ligthbox == false) {
                    // On relance la transition seulement aprés une seconde lorsque le curseur
                    // qui la zone de l'image cela evite que des passage trop rapide sur l'image
                    // face défiler trop rapidement les images
                    this.createTimer(function () {instance.resume();}, 1000, true);
                }
            }
        }
    }



    //////////////////////////////////
    // Initialisation
    //////////////////////////////////
    if (typeof(_playlist.video.url) == "string" || _playlist.image.length > 0) {
        this.options = $.extend(true, this.options, _options);

        this.playlist.video = _playlist.video;
        // Aucune image n'est chargé
        for(var i = 0; i < _playlist.image.length; i++) {
            this.playlist.image[i] = {
                srcNormal : _playlist.image[i].srcNormal,
                srcThumbnail : _playlist.image[i].srcThumbnail,
                copyright : _playlist.image[i].copyright,
                legende : (_playlist.image[i].legende != null) ? _playlist.image[i].legende : '',
                loaded : false
            };
            this.playlist.imageCount++;
        }

        this.player = _container;
        if (!this.player.hasClass('player')) this.player.addClass('player');

        this.player.append('<div id="player_content"><div id="player_content_image"></div><div id="player_content_video"></div><div id="player_content_hover"></div><div class="cross"><a href="#"></a></div></div><div id="player_menu">');

        this.player_content = $("#player_content", this.player);
        $(".cross a", this.player_content).click(function () {instance.closeFullscreen();});

        this.player_menu = $("#player_menu", this.player);
        this.player_content_video = $("#player_content_video", this.player_content);
        this.player_content_image = $("#player_content_image", this.player_content);
        this.player_conent_hover = $("#player_content_hover", this.player_content);

        this.createMenu();
        this.player_menu_image = $("#player_menu_image", this.player_menu);
        this.player_menu_image_copyright = $(".copyright", this.player_menu_image);
        this.player_menu_tab = $("#player_menu_tab", this.player_menu);
        this.player_menu_tab_image = $("#player_menu_tab_image", this.player_menu_tab);
        this.player_menu_tab_video = $("#player_menu_tab_video", this.player_menu_tab);

        if (this.playlist.image.length > 0 && typeof(this.playlist.video.url) == 'string') this.player.addClass("dualmode");
        else this.player.addClass("singlemode");

        this.loadAllImages();

        this.options.lightbox.onLoad = function () {instance.stop();};
        this.options.lightbox.onClosed = function () {instance.resume();};

        this.start();
    }
};
