/**
 * @author Stéphane Roucheray 
 * @extends jquery
 */
jQuery(function(){
	jQuery.fn.carousel = function(o) {
		return this.each(function() {
			new jQuery.carousel(this, o);
		});
	};
	
	jQuery.carousel = function(elem,options){

		var $this = jQuery(this);
		this.elem = elem;
		var $elem = jQuery(elem);
		this.sliderList = $elem.children()[0];
		var defaults = {
			previous:null,
			next:null,
			speed:500,
			auto:0
		};
		this.options = $.extend({}, defaults, options || {});



		if ($elem && this.sliderList) {
			this.increment = jQuery(this.sliderList).children().outerWidth("true"),
			this.elmnts = jQuery(this.sliderList).children(),
			this.numElmts = this.elmnts.length,
			this.sizeFirstElmnt = this.increment,
			this.shownInViewport = Math.round($elem.width() / this.sizeFirstElmnt),
			this.firstElementOnViewPort = 1,
			this.isAnimating = false;

			for (i = 0; i < this.shownInViewport; i++) {
				jQuery(this.sliderList).css('width',(this.numElmts+this.shownInViewport)*this.increment + "px");
				jQuery(this.sliderList).append(jQuery(this.elmnts[i]).clone());
			}
			var self = this;

			if(this.options.previous){
				jQuery(this.options.previous).click(function(event){
					self.prev();
				});
			}

			jQuery(this.options.next).click(function(event){
				self.next();
			});

			this.startAuto();
		}
	};
	
	$.carousel.fn = $.carousel.prototype = {
        carousel: '0.0.1'
    };
	$.carousel.fn.extend = $.carousel.extend = $.extend;

	$.carousel.fn.extend({
		next:function(){
			this.stopAuto();
			if (!this.isAnimating) {
				if (this.firstElementOnViewPort > this.numElmts) {
					this.firstElementOnViewPort = 2;
					jQuery(this.sliderList).css('left', "0px");
				}
				else {
					this.firstElementOnViewPort++;
				}
				this.animate('-='+this.increment);
			}
		},
		prev:function(){
			this.stopAuto();
			if (!this.isAnimating) {
				if (this.firstElementOnViewPort == 1) {
					jQuery(this.sliderList).css('left', "-" + this.numElmts * this.sizeFirstElmnt + "px");
					this.firstElementOnViewPort = numElmts;
				}
				else {
					this.firstElementOnViewPort--;
				}
				this.animate('+='+this.increment);
			}
		},
		animate:function(increment){
			this.isAnimating = true;
			var self = this;
			jQuery(this.sliderList).animate({
					left: increment
				},{
				duration: this.options.speed,
				complete: function(event){
					self.isAnimating = false;
					self.startAuto();
				},
				easing:"swing"
				}
		);
		},
		startAuto:function(){
			if(this.timer!=null){
				return;
			}
			if(this.options.auto == 0){
				this.stopAuto();
				return;
			}
			var self = this;
			this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);

		},
		stopAuto:function(){
			if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
		}
	});
});

