﻿/*global Math, Number, RegExp, clearTimeout, document, go, height, iterations, jQuery, parseInt, setTimeout, width, pausedCarousel */
(function($){
    /**
     * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
     * @requires jQuery v1.2 or above
     *
     * @author Ganeshji Marwaha
     * @author Karl Swedberg (modifications/enhancements)
     *
     *
     * http://gmarwaha.com/jquery/jcarousellite/
     *
     * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
     * Dual licensed under the MIT and GPL licenses:
     * http://www.opensource.org/licenses/mit-license.php
     * http://www.gnu.org/licenses/gpl.html
     *
     * Version: 1.1
     * Note: Requires jquery 1.2 or above from version 1.0.1
     */
    $.jCarouselLite = {
        version: '1.1',
        defaults: {
            btnPrev: null, // Selecteur/objet jQuery du bouton précédent
            btnNext: null, // Selecteur/objet jQuery du bouton suivant
            btnGo: null, // Selecteurs/objets jQuery des controleurs externes
			btnPause: null, // Selecteur/objet jQuery  du bouton pause
            mouseWheel: false, // Mouse Wheel (true ou false)
            speed: 200, // Vitesse de défilement
            easing: null,  // Effets
            auto: false, // Auto scrolling true ou false
            autoStop: false, // nombre de d'iteration de l'autoscrolling
            timeout: 4000, // Temps entre chaque defilement en millisecondes
            pause: false, // pause au rollover sur le carrousel (true ou false)
            vertical: false, // defilement vertical (true ou false)
            circular: true, // defilement circulaire (true ou false)
            visible: 3, // nombre d'éléments visibles
            start: 0, // index de l'élément à afficher en premier à l'initialisation
            scroll: 1, // nombre d'élément déplacé à chaque défilement
            beforeStart: null, // fonction lancé avant chaque défilement
            afterEnd: null,	// fonction lancé après chaque défilement
			pauseCallback: null // fonction lancé à chaque pause
        }
    };
    
    $.fn.jCarouselLite = function(options){
        var o = $.extend({}, $.jCarouselLite.defaults, options);
        
        return this.each(function(){
        
            var running = false, animCss = o.vertical ? "top" : "left", sizeCss = o.vertical ? "height" : "width";
            
            var div = $(this), ul = div.find('>ul'), tLi = ul.find('>li'), tl = tLi.length, v = o.visible;
            tLi.each(function(){
                $(this).addClass("index-" + tLi.index($(this)).toString());
            });
            
			var li = ul.find('>li'), itemLength = li.length, curr = o.start;
            if (o.start > itemLength - v) {
                curr = itemLength - v;
            }
			
            // Désactivation des boutons précédent/suivant quand le carrousel atteind le premier/dernier élément
            if (!o.circular) {
				$(o.btnPrev).add(o.btnNext).removeClass("disabled");
                $((curr === 0 && o.btnPrev) ||
                (curr + v >= itemLength && o.btnNext) ||
                []).addClass("disabled");
            }
			
            div.css("visibility", "visible");
            
            li.css({
                overflow: o.vertical ? "hidden" : 'visible',
                'float': o.vertical ? "none" : "left"
            });
            ul.css({
                margin: "0",
                padding: "0",
                position: "relative",
                "list-style-type": "none",
                "z-index": "1"
            });
            div.css({
                overflow: "hidden",
                position: "relative",
                "z-index": "2",
                left: "0px"
            });
            
            var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation
            var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items)
            if (o.circular) {
				ulSize = liSize * (itemLength+o.scroll);
			}
            var divSize = liSize * v; // size of entire div(total length for just the visible items)					
            li.css({width: li.width(), height: li.height()});
            ul.css(sizeCss, ulSize + "px").css(animCss, -(curr * liSize));
            o.vertical ? ul.css("width", width(li)) : ul.css("height", height(li));
            //div.css(sizeCss, divSize + "px"); // Width of the DIV. length of visible images
            o.vertical ? div.css("width", width(li)) : div.css("height", height(li));
            if (o.btnPrev) {
                $(o.btnPrev).click(function(e){
					e.preventDefault();
					if (curr === 0 && !o.circular) {
						return;
					}
					else {
						return go(curr - o.scroll);
					}
                });
            }
            if (o.btnNext) {
                $(o.btnNext).click(function(e){
					e.preventDefault();
					if (curr + v >= itemLength && !o.circular) {
						return;
					}
					else {
						return go(curr + o.scroll);
					}
                });
            }
            if (o.btnGo) {
                $.each(o.btnGo, function(i, val){
                    $(val).click(function(e){
						e.preventDefault();
                        var itemGo = $(val).attr("class").split(" ");
                        itemGo = $.grep(itemGo, function(txt){
                            return (new RegExp(/^scroll-/).test(txt));
                        });
                        itemGo = itemGo[0].split("scroll-")[1];
						itemGo = parseInt(itemGo-1,10);
						if (o.circular) {
							itemGo = $(ul).find(">li").index($(ul).find("li[class*=index-"+itemGo+"]"));
						}
						if (itemGo != curr) {
							return go(itemGo);
						}
                    });
                });
            }
            if (o.mouseWheel && div.mousewheel) {
                div.mousewheel(function(e, d){
                    return d > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
                });
            }
            
            if (o.auto) {
                // CHANGED: Added pause on hover (Karl Swedberg)
                var setAutoAdvance, advanceCounter = 0, autoStop = iterations(tl, o);
                
                var advancer = function(){
                    setAutoAdvance = setTimeout(function(){
                        if (!autoStop || autoStop > advanceCounter) {							
                            go(curr + o.scroll);
                            advanceCounter = advanceCounter + 1;
                            //advancer();
                        }
                    }, o.timeout + o.speed);
                };
                
				advancer();
				
				$(document).bind('pauseCarousel', function(event){
                    clearTimeout(setAutoAdvance);
                    $(event.target).data('paused', true);
                }).bind('resumeCarousel', function(event){
                    advancer();
                    $(event.target).data('paused', false);
                });
				
				var pausedCarouselClick = false;
				var pausedCarousel = false;
				
				if (o.btnPause) {
					 $(o.btnPause).click(function(e){
						e.preventDefault();
						
						if(!$(this).hasClass("paused")){
							ul.clearQueue();
							div.trigger('pauseCarousel');
							$(this).addClass("paused");
							pausedCarousel = true;
							pausedCarouselClick = true;
							if (o.pauseCallback) {
		                        o.pauseCallback.call(this, $(o.btnPause));
		                    }	
						}
						else{
							div.trigger('resumeCarousel');
							$(this).removeClass("paused");
							pausedCarousel = false;
							pausedCarouselClick = false;
							if (o.pauseCallback) {
								o.pauseCallback.call(this, $(o.btnPause));
							}	
						}
					});
				}
				
                if (o.pause) {
                    ul.mouseenter(function(){
						if (!pausedCarouselClick) {
							div.trigger('pauseCarousel');
							pausedCarousel = true;
							if (o.btnPause) {
								$(o.btnPause).addClass("paused");
								if (o.pauseCallback) {
									o.pauseCallback.call(this, $(o.btnPause));
								}
		                    }
						}						
                    }).mouseleave(function(){
						if (!pausedCarouselClick) {
							div.trigger('resumeCarousel');
							pausedCarousel = false;
							if (o.btnPause) {
								$(o.btnPause).removeClass("paused");
								if (o.pauseCallback) {
									o.pauseCallback.call(this, $(o.btnPause));
								}
							}
	                    }
                    });
                }
            }
            
            function vis(){
                return ul.find(">li").slice(curr).slice(0, v);
            }			 
            
            function go(to){
                if (!running) {
					
                    if (o.beforeStart) {
                        o.beforeStart.call(this, vis());
                    }
					if (o.auto === true && pausedCarousel === false) {
						div.trigger('pauseCarousel');						
					}
					
					var move = curr*liSize;
					
                    if (o.circular) { // If circular we are in first or last, then goto the other end
						if (to < curr) {
							
							if (to < 0) {
								ul.prepend(ul.find(">li").slice(ul.find(">li").length - o.scroll).clone(true));
								ul.css(animCss, -(curr + o.scroll) * liSize);
								curr = to + o.scroll;
							}
							else {
								curr = to;
							}
							move = curr*liSize;
						}
						else {
							
							if (to > itemLength - v) {
								ul.append(ul.find(">li").slice(0, o.scroll).clone(true));
								curr = to - o.scroll;
							}
							else {
								curr = to;
							}
							move = to*liSize;
						}
						
                    }
                    else { // If non-circular and to points beyond first or last, we change to first or last.
                        if (to < 0) {
                            curr = 0;
                        }
                        else {
                            if (to > itemLength - v) {
                                curr = itemLength - v;
                            }
                            else {
                                curr = to;
                            }
                        }
                        
						move = curr*liSize;
                    }
					
					running = true;					
							
                    ul.animate(animCss === "left" ? {
                        left: -move
                    } : {
                        top: -move
                    }, o.speed, o.easing, function(){
						
						if (o.circular) {
							if (to > itemLength - v && to >= curr) {
								ul.find(">li").slice(0, o.scroll).remove();
								ul.css(animCss, -(curr) * liSize);
							}
							if (to < 0 && to < curr) {
								ul.find(">li").slice(ul.find(">li").length - o.scroll).remove();
							}
						}
                        if (o.afterEnd) {									
                            o.afterEnd.call(this, vis());
                        }
						if (o.auto === true && pausedCarousel === false) {
							div.trigger('resumeCarousel');
						}
						running = false;
                    });
					if (!o.circular) {
						// Disable buttons when the carousel reaches the last/first, and enable when not
                        $(o.btnPrev).add(o.btnNext).removeClass("disabled");
                        $((curr === 0 && o.btnPrev) ||
                        (curr + v >= itemLength && o.btnNext) ||
                        []).addClass("disabled");
					}
                    
                }
                return false;
            } // end if !running
        });
    };
    
    function css(el, prop){
        return parseInt($.css(el[0], prop), 10) || 0;
    }
    function width(el){
        var elt = el[0];
        el.each(function(){
            if ($(this).width() > $(elt).width()) {
                elt = this;
            }
        });
        return elt.offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');
    }
    function height(el){
        var elt = el[0];
        el.each(function(){
            if ($(this).height() > $(elt).height()) {
                elt = this;
            }
        });
        return elt.offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom');
    }
    function iterations(itemLength, options){
        return options.autoStop && (options.circular ? options.autoStop : Math.min(itemLength, options.autoStop));
    }
}(jQuery));


