vanilla.namespace('ducaroygrange.carrousel');

ducaroygrange.carrousel =
{
    TIME		: 3000,
    TRANSITION_TIME	: 1000,
    FADING_TIME		: 600,
    SQUARE_X		: 12,
    SQUARE_Y		: 5,

    init : function(properties)
    {
	var self	= this;
	this.view	= $("#view-" + properties.viewId);
	this.items	= this.view.find("ul.visuels li.visuel").hide();
	this.interval	= null;

	this._initNavigation();
	this._initTransitions();

	this.selectByIndex(0);
    },

    _initTransitions : function()
    {
	// initialisation de la transition
	var w = this.items.width();
	var h = this.items.height();

	var sw = w / this.SQUARE_X;
	var sh = h / this.SQUARE_Y;

	var div = $("<div></div>").addClass("transition").css
	({
	    position	: "absolute", 
	    top		: 0,
	    left	: 0,
	    width	: w,
	    height	: h
	});

	for ( var x = 0 ; x < this.SQUARE_X ; x++ )
	{
	    for ( var y = 0 ; y < this.SQUARE_Y ; y++ )
	    {
		var square = $("<div></div>").addClass("square").
		css
		({
		    position		    : "absolute",
		    width		    : sw,
		    height		    : sh,
		    top			    : y*sh,
		    left		    : x*sw,
		    backgroundPosition	    : -x*sw + "px " + -y*sh + "px",
		    backgroundRepeat	    : "no-repeat",
		    backgroundAttachment    : "scroll"
		})
		.appendTo(div);
	    }
	};

	// on l'applique pour chaque item
	this.items.each
	(
	    function()
	    {
		var li = $(this);
		var img = li.find("img").hide();

		div.clone().insertBefore(li.find("div.description")).find("div.square").css("background-image", "url(" + img.attr("src") + ")");
	    }
	);
    },

    _initNavigation : function()
    {
	var self = this;
	
	this.navigation = $("<ul></ul>").addClass("navigation").appendTo(this.view);
	this.items.each
	(
	    function(i)
	    {
		var classNames	= this.className.split(/\s+/);
		var secteur	= classNames.length > 1 ? $.trim(classNames[1]) : "";

		$("<a></a>").addClass(secteur).attr("href", "#").click
		(
		    function(e)
		    {
			e.stopPropagation();
			e.preventDefault();

			self.selectByIndex(i, true);
		    }
		)
		.wrap("<li></li>").parent().appendTo(self.navigation);
	    }
	);

	var nw = this.navigation.width();
	var vw = this.view.width();

	this.navigation.css({left:(vw/2-nw/2) + "px"});

	this.previousButton = $('<a href="#" />').addClass("previous").click
	(
	    function(e)
	    {
		e.stopPropagation();
		e.preventDefault();
		self.previous(true);	
	    }
	)
	.hover
	(
	    function()
	    {
		$(this).stop(true).animate
		(
		    {
			width	    : 56, 
			left	    : -54
		    },
		    {
			duration    : "fast"	
		    }
		);
	    },
	    function()
	    {
		$(this).stop(true).animate
		(
		    {
			width	    : 36, 
			left	    : -34
		    },
		    {
			duration    : 500,
			easing	    : "easeOutBounce"
		    }
		);
	    }
	)
	.appendTo(this.view);

	this.nextButton = $('<a href="#" />').addClass("next").click
	(
	    function(e)
	    {
		e.stopPropagation();
		e.preventDefault();
		self.next(true);	
	    }
	)
	.hover
	(
	    function()
	    {
		$(this).stop(true).animate
		(
		    {
			width	    : 56, 
			right	    : -54
		    },
		    {
			duration    : "fast"	
		    }
		);
	    },
	    function()
	    {
		$(this).stop(true).animate
		(
		    {
			width	    : 36, 
			right	    : -34
		    },
		    {
			duration    : 500,
			easing	    : "easeOutBounce"
		    }
		);
	    }
	)
	.appendTo(this.view);
    },

    select : function(item, clearInterval)
    {
	item = $(item);

	if ( clearInterval && this.interval != null )
	{
	    window.clearInterval(this.interval);
	    this.interval = null;
	}

	var current = this.getCurrent();
	if ( current.get(0) == item.get(0) )
	{
	    return;
	}

	var self = this;
	if ( current.length <= 0 )
	{
	    // la première fois une affiche juste l'image
	    item.toggleClass("selected", true).css({opacity:1}).show();
	    self._updateNavigation(item);
	}
	else
	{
	    current.toggleClass("selected", false);
	    item.toggleClass("selected", true);

	    var c = this.view.find("div.carrouselContainer");

	    // TODO synchronise sur la navigation
	    // on enqueue la nouvelle méthode
	    c.clearQueue().queue
	    (
		function(next)
		{
		    current.css("z-index", 2).find("div.description").fadeOut();
		    item.css("z-index", 1).show().find("div.description").show().prev("div.transition").find("div.square").stop(true).css("opacity", 1);

		    var squares = current.find("div.square").stop(true);
		    var l = squares.length;
		    var t = self.TRANSITION_TIME - self.FADING_TIME;
		    var n = l;
		    squares.each
		    (
		        function(i)
		        {
			    var r = Math.round(Math.random()*t);
		            $(this).delay(r).animate
		            (
		        	{opacity:0}, self.FADING_TIME, "linear", 
		        	function()
		        	{
		        	    if ( --n == 0 )
		        	    {
		        		current.hide();
		        		next();
		        	    }
		        	}
		            );
		        }
		    );

		    self._updateNavigation(item);
		}
	    )
	}

	if ( this.interval == null && this.items.length > 1 )
	{
	    var self = this;
	    this.interval = window.setInterval
	    (
	        function()
	        {
	            self.next();
	        },
	        this.TIME
	    );
	}
    },

    _updateNavigation : function(item)
    {
	var index = this.items.index(item);
	this.navigation.find(".selected").toggleClass("selected", false);
	this.navigation.find("li").eq(index).toggleClass("selected", true);
    },

    selectByIndex : function(index, clearInterval)
    {
	var self = this;
	this.view.synchronize
	(
	    function()
	    {
		self.select(self.items[index], clearInterval);
	    }
	)
    },

    getCurrent : function()
    {
	return this.items.filter(".selected");
    },

    next : function(clearInterval)
    {
	if ( this.items.length <= 0 )
	{
	    return;
	}

	var self = this;
	this.view.synchronize
	(
	    function()
	    {
		var i = self.items.index(self.getCurrent()) + 1;
		i %= self.items.length;

		self.selectByIndex(i, clearInterval);
	    }
	);
    },

    previous : function(clearInterval)
    {
	if ( this.items.length <= 0 )
	{
	    return;
	}

	var self = this;
	this.view.synchronize
	(
	    function()
	    {
		var i = self.items.index(self.getCurrent()) - 1;
		if ( i < 0 )
		{
		    i = self.items.length - 1;
		}

		self.selectByIndex(i, clearInterval);
	    }
	);
    }
};

