/*
 *
 *  Class CarrousselSlider
 *
 */
(function($){
  
    CarrousselSlider = function(sliderArea, sliderElements, sliderInfoArea, sliderInfoElementsClass, speed){
        this.sliderArea = $(sliderArea);
        this.sliderElementsClass = sliderElements;
        this.timeoutId = null;
        this.speed = speed;

        this.canSlide = false;
        this.loadingArea = $('#slider');
        this.imgLoaded = 0;

        this.currentElt = 0;
        this.maxElts = $(".slider_carroussel").length;
        this.isPeriodicalAnimation = true;

        this.sliderInfoArea = $(sliderInfoArea);
        this.sliderInfoElementsClass = sliderInfoElementsClass;
    };
  
  
    /**
   *
   */
    CarrousselSlider.prototype = {
    
        SPEED : 6000, // délait entre les slides
        TRANSITION_FAST : 400, // vitesse de défilement d'un slide lors d'une changement manuel'
        FADEIN_SPEED:750,
        divLoader : null,


        /**************************
   *                        *
   *  chargement du slider  *
   *                        *
   **************************/

        /**
   *
   */
        load: function(){
            this.addLoader();
    
            var images = $('.slider_carroussel img').toArray();
            var imagesElt = $('.slider_carroussel img');
    
            //  this.loadImages2(imagesElt, imagesElt.length);
            this.loadImages(images, 0);
    
        },
  
  
        endLoad : function(){
            this.removeLoader();
            this.init();
        },
  
        addLoader : function(){
            this.divLoader = $('<div class="loader">');
            this.loadingArea.append(this.divLoader);
        },
  
        removeLoader : function(){
            this.divLoader.remove();
            var obj = this;
            this.sliderArea.fadeIn(this.FADEIN_SPEED, function(){
                obj.sliderArea.removeClass('homepage_slider_loading');
                $('#info_slide').removeClass('homepage_slider_loading');
      
            });
        },
  
  
        loadImages : function(images, position){
            if(position < images.length){
                var img = new Image();
                var noCacheTimer = new Date().getTime();
                img.src = $(images[position]).attr("src")+'?no_cache='+noCacheTimer;
                //      img.src = $(images[position]).attr("src");
                //      if(img.complete){
                //        position++;
                //        this.loadImages(images, position);
                //      }  
      
                var obj = this;
                img.onload = function(){
                    position++;
                    obj.loadImages.call(obj, images, position);
                };
            }else{
                this.endLoad();
            }
        },
  
  
  
        loadImages2: function(imagesElt, totalImages){
            var self = this;
    
            imagesElt.each(function(index, elt){
                var img = new Image();
                img.src = $(this).attr('src');
                if(img.complete){
                    self.imgLoaded++;
                    return;
                }else{
                    $(this).load(function(){
                        self.ImageLoaded.call(self, totalImages);
                    });
                }
            });
            if(this.imgLoaded == totalImages){
                this.endLoad();
            }
        },


        ImageLoaded: function(totalImages){
            this.imgLoaded++;
            if(this.imgLoaded == totalImages){
                this.endLoad();
            }
        },



        /********************************
 *                              *
 *  fonctions d'initialisation  *
 *                              *
 *******************************/

        /**
   *  initialisation des éléments après chargement des images
   */
        init: function(){
            var obj = this;
            this.barreResume = new ResumeToolbar(300, function(index){
                obj.changeSlideCallback(obj, index);
            });
            this.initEtapeListener();
            this.initListeners();

            this.initResume();
            this.canSlide = true;
            this.start();
        },


        /**
 *  initialisation des écouteurs
 *   pour la forme, mais pas utilisé pour le moment
 */
        initListeners : function(){
    
        },
  
  
    
        /**
   *  lance / cache le résumé du caroussel
   */
        initResume : function(){
            var obj = this;
            $("#sliderContainer").mouseenter(function(evt){
                this.resumeTimeoutId = setTimeout(function(){
                    obj.displayResume.call(obj);
                }, 1000);
            });
    
    
            $("#sliderContainer").mouseleave(function(evt){
                clearTimeout(this.resumeTimeoutId );
                obj.hideResume.call(obj);
            });
    
        },// end initLegende
    
    
        /**
   *  preapration des tableaux block et visuel
   */
        initEtapeListener : function(){
            this.etape = {
                visuel:[], 
                block:[]
            };
    
            var eltsLength = $(this.sliderElementsClass).length;
            for(var i = 0; i < eltsLength; i++){
                this.etape.visuel[i] = true;
                this.etape.block[i] = true;
            }
    
            var obj = this;
            $(document).bind("etapeReady", function(evt, obj){ 
                if(obj.etapeVisuelIsReady.call(obj) && obj.etapeBlockIsReady.call(obj)){
                    obj.addNewSlide.call(obj);
                }
            });
        },
  
  
    
  
        /**
   * relance la timer pour le diaporama
   */
        reInitPeriodicalSliding : function(){
            this.canSlide = true;
            this.isPeriodicalAnimation = true;
            this.start();
        },
  
  
  
        /****************************
   *                          *
   *  gestion des événements  *
   *                          *
   ***************************/
  
        /**
   *  changement d'un slide
   */
        changeSlide : function(index){ 
            var duration = this.TRANSITION_FAST;
            var obj = this;
     
            this.periodicalSliding(duration);
            $(document).bind("new_slider_ready", function(evt, obj){ 
                $(document).unbind("new_slider_ready");
                if(index != obj.currentElt){
                    obj.changeSlide.call(obj, index);
                }else{
                    obj.reInitPeriodicalSliding.call(obj);
                }
            });
        },
  
  
        /**
   *
   */
        changeSlideCallback : function(obj, index){
            // si une transition est déjà en cours, on ne fair rien
            if(!obj.etapeVisuelIsReady() || !obj.etapeBlockIsReady() || !obj.canSlide){
                obj.isPeriodicalAnimation = true;
                return 1;
            }
    
            // on est déjà sur le sldie demandé
            if(index == obj.currentElt){
                obj.isPeriodicalAnimation = true;
                return 1;
            }

            obj.stop();
            obj.isPeriodicalAnimation = false;
            obj.changeSlide(index);
        },
  
  
  
  
  
        /**************
   *            *
   *  affichage *
   *            *
   **************/
  
        /**
   *
   */
        displayResume : function(){
            this.barreResume.open();
        },
  
        /**
   *
   */
        hideResume : function(){
            this.barreResume.close();
        },
  
  
        /********************
 *                  *
 *  les traitements *
 *                  *
 ********************/
  
    
        /**
   *  contrôle le lancement de la boucle d'animation
   */
        start : function(){ 
            if(arguments.length == 1){
                arguments[0].run.call(arguments[0]);
            }else{
                this.run();
            }
        },
  
  
        /**
   *  lancement d'une animation
   */
        run : function(){
            if(this.canSlide){
                var obj = this;
                this.timeoutId = setTimeout(function(){
                    obj.periodicalSliding.call(obj);
                }, obj.speed);
            }
        },
  
  
        /**
   *  fin de l'animation
   */
        stop : function(){
            clearTimeout(this.timeoutId);
            this.timeoutId = 0;
        },
  
  
  
  
        /**
   * execution de l'animation
   */
        periodicalSliding : function(){
            this.canSlide = false;
            this.setEtapeBlockInProgress();
            this.setEtapeVisuelInProgress();      

            var duration = Application.FADE_SPEED_LOW;
            if(arguments.length == 2){
                duration = arguments[1];
            }

            this.moveSlide(duration);
            this.moveSlideElement(duration);
        },
  
  
  
        /**
   *  décalle les images du slider (visuels) lors du changement de slide
   */
        moveSlide : function(duration){
            var elt = $(this.sliderElementsClass).first();
            var obj = this;
            
            $("#timer").hide();
            
            elt.animate({
                "margin-right":"-1050px"
            }, {
                duration:duration, 
                easing:"easeOutCirc",
                complete:function(){
                    $(obj.sliderElementsClass).each(function(index, elt){
                        obj.setEtapeVisuelReady.call(obj, index);
                    });
                    $("#timer").show();
                }
            });
    
        
    
        },
  
  
        /**
           *  décalle les éléments du slider (block infos) lors du changement de slide
           */
        moveSlideElement : function( duration){
            var infoElts = $(this.sliderInfoElementsClass);
            var obj = this;

            infoElts.each(function(index, elt){
                var left = parseInt($(this).css("left"), 10);
                left -= 427;
                $(this).animate({
                    "left":left.toString()+"px"
                },{
                    duration:duration, 
                    easing:"easeOutCirc",
                    complete:function(){
                        obj.setEtapeBlockReady.call(obj, index);
                    }
                });
      
                if($("#timer",this).length > 0){
                    $("#timer",this).animate({
                        "left":left.toString()+"px"
                    }); 
                }
      
            });
        },
  

  
  
        /**
   *  ajout du nouvel élément
   *  on place le 1ere élément en queue de liste
   *  pour les diapos
   */
        addNewSlide : function(){
            var elt = $(this.sliderElementsClass).first();
            var newElt = elt.clone();
            elt.remove();
            newElt.css({
                "margin-right":0
            });
            this.sliderArea.append(newElt);

            //pour les textes
            //   var sliderEltLenght = $(obj.sliderInfoElementsClass).length;
            var blkElt = $(this.sliderInfoElementsClass).first().clone(); 
            var left = 427 * ($(this.sliderInfoElementsClass).length -1);
            $(this.sliderInfoElementsClass).first().remove();
            blkElt.css({
                "left":left.toString()+"px"
                });
            $(this.sliderInfoArea).append(blkElt);

            this.currentElt++;
            if(this.currentElt >= this.maxElts){
                this.currentElt = 0;
            }

            if(this.isPeriodicalAnimation){
                this.reInitPeriodicalSliding();
            }else{
                $(document).trigger("new_slider_ready", this);
            }
        },
  
  
  
  
  
        /************************************************
   *                                              *
   *  détection de l'état des éléments du slider  *
   *                                              *
   *************************************************/
  
  
        /**
   * initialise le tableau des visuels à faux
   * durant la transition, chaque case passera à true lorsqu'elle aura finit sa transition
   * une fois toutes les case à true, l'événement 'etapeReady' est déclenché (voir fonction setEtapeVisuelReady())
   */
        setEtapeVisuelInProgress : function(){
            var visuelLength = this.etape.visuel.length;
    
            for(var i = 0; i < visuelLength; i++){
                this.etape.visuel[i] = false;
            }
        },
  
  
        /**
   * même principe que setEtapeVisuelInProgress
   */
        setEtapeBlockInProgress : function(){
            var blockLength = this.etape.block.length;
    
            for(var i = 0; i < blockLength; i++){
                this.etape.block[i] = false;
            }
        },
  
  
        /**
   *  trigger lancé lorsque le visuel est prêt
   */
        setEtapeVisuelReady : function(index){
            this.etape.visuel[index] = true;

            if(this.etapeVisuelIsReady()){
                $(document).trigger("etapeReady", this);
            } 
        },
  
    
        /**
   *  trigger lancé lorsque le bloc est prêt
   */
        setEtapeBlockReady : function(index){
            this.etape.block[index] = true;
    
            if(this.etapeBlockIsReady()){
                $(document).trigger("etapeReady", this);
            } 
        },
  
  
        /**
   *  retourne true si toutes les cases sont à true => slider (visuel) opérationnel
   */
        etapeVisuelIsReady : function(){
            var visuelLength = this.etape.visuel.length;
            var isReady = true;
    
            for(var i = 0; i < visuelLength; i++){
                if(!this.etape.visuel[i]){
                    return false;
                }
            }
    
            return isReady;
        },
  
  
        /**
   * return true si toutes les cases sont à true => slider (block) opérationnel
   */
        etapeBlockIsReady : function(){
            var blockLength = this.etape.block.length;
            var isReady = true;
    
            for(var i = 0; i < blockLength; i++){
                if(!this.etape.block[i]){
                    return false;
                }
            }
    
            return isReady;
        }
  
  
    };
  
})(jQuery);
// end class CarrousselSlider




/*
 *
 *  Class ResumeToolbar
 *
 */
(function(){
    ResumeToolbar = function(duration, selectItemCallback){
        this.elt = $("#slider_resume");
        this.initToolBarItems(selectItemCallback);
    
        this.realTop = 292;
        this.realHeight = 48;
        this.isOpen = false;
        this.duration = duration;
    
        this.initListeners.call(this);
    };
  
    ResumeToolbar.prototype.initListeners = function(){
    
    };
  
  
    ResumeToolbar.prototype.initToolBarItems = function(selectItemCallback){
        this.items = [];
        var obj = this;
        this.elt.children().each(function(index, elt){
            var tbItem = new ResumeToolBarItem($(this), index, selectItemCallback);
            obj.items.push(tbItem);
        });
    };
  
  
    ResumeToolbar.prototype.open = function(){
        var obj = this;
    
        this.elt.animate({
            "top":this.realTop,
            "height":this.realHeight
        },{
            duration:obj.duration,
            complete:function(){
                obj.isOpen = true;
                obj.elt.removeClass("closed");
            }
        });
    };


    ResumeToolbar.prototype.close = function(){
        var obj = this;
        var top = this.realTop+this.realHeight;
        var height = 0;
    
        this.elt.animate({
            "top":top,
            "height":height
        },{
            duration:obj.duration,
            complete:function(){
                obj.isOpen = true;
                obj.elt.addClass("closed");
            }
        });
    };
  
})();
// end class ResumeToolbar




/*
 *
 * Class ResumeToolBarItem 
 * 
 */
(function(){
    ResumeToolBarItem = function(elt, index, selectItemCallback){
  
        this.elt = elt;
        this.index = index;
        this.onSelect = selectItemCallback;
        this.initListeners();
    };


    ResumeToolBarItem.prototype.initListeners = function(){ 
        var obj = this;
        this.elt.click(function(evt){
            evt.preventDefault();
            obj.onSelect(obj.index);
        });
    };
  
})();
// end class ResumeToolBarItem
