/**
 * @author Stéphane Roucheray 
 * @extends jquery
 */


jQuery.fn.carousel = function(previous, next, options){
	var sliderList = jQuery(this).children()[0];
	
	if (sliderList) {
		var increment = jQuery(sliderList).children().outerWidth("true"),
		elmnts = jQuery(sliderList).children(),
		numElmts = elmnts.length,
		sizeFirstElmnt = increment,
		shownInViewport = Math.round(jQuery(this).width() / sizeFirstElmnt),
		firstElementOnViewPort = 1,
		isAnimating = false;
		
		
		//here we also deal with the case we have less then 6 colors available, so we have to repeat them to fill the empty color spaces in the interfaces
		var ok = false;
		var total = numElmts;
		var toClone = (shownInViewport<numElmts) ? shownInViewport : numElmts  ;
		while(!ok){			
	 		for (i = 0; i < toClone; i++) {
				jQuery(sliderList).css('width',(total)*increment + increment + "px");
				jQuery(sliderList).append(jQuery(elmnts[i]).clone(true));
				total++;
			}
	 		if (total >= 12) ok = true;
	 		else {
	 			var leftToClone = 12 - total;
	 			if (leftToClone > numElmts) toClone = numElmts;
	 			else toClone = leftToClone;
	 		}
		}
 		
		jQuery(previous).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort == 1) {
					jQuery(sliderList).css('left', "-" + numElmts * sizeFirstElmnt + "px");
					firstElementOnViewPort = numElmts;
				}
				else {
					firstElementOnViewPort--;
				}
				
				jQuery(sliderList).animate({
					left: "+=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
			
		});
		
		jQuery(next).click(function(event){
			if (!isAnimating) {
				if (firstElementOnViewPort > numElmts) {
					firstElementOnViewPort = 2;
					jQuery(sliderList).css('left', "0px");
				}
				else {
					firstElementOnViewPort++;
				}
				
				jQuery(sliderList).animate({
					left: "-=" + increment,
					y: 0,
					queue: true
				}, "swing", function(){isAnimating = false;});
				isAnimating = true;
			}
		});
	}
};
