/**
 * Copyright (c) 2009 Sylvain Gougouzian (sylvain@gougouzian.fr)
 * MIT (http://www.opensource.org/licenses/mit-license.php) licensed.
 * GNU GPL (http://www.gnu.org/licenses/gpl.html) licensed.
 *
 * jQuery carrousel by Sylvain Gougouzian http://sylvain.gougouzian.fr
 *
 * inspirated of jCarousel http://sorgalla.com/
 *
 * Version: 1.1.7
 *
 * Requires: jQuery 1.3.2+ 	// http://www.jquery.com
 *
 * Compatible : Internet Explorer 6+, Firefox 1.5+, Safari 3+, Opera 9+, Chrome 0.9+
 */
jQuery(function($){
    $.fn.carrousel = function(options){
        var el = this.eq(0).data("carrousel");
        var opts = $.extend({}, $.fn.carrousel.defaults, options);
        var ctrls = $.extend({}, $.fn.carrousel.controls);
        var effects = $.extend({}, $.fn.carrousel.effects);
        this.each(function(){
            el = new $carrousel(this, opts, ctrls, effects);
        });
        return opts.api ? el : null;
    };
    $.carrousel = function(e, opts, ctrls, effects){
        this.e = $(e);
        $(e).css('position', 'relative').wrap('<div><div></div></div>');
		if (opts.continuous)
			$(e).html($(e).html() + $(e).html());
        var self = this;
        var tA = new Date();
        this.id = ($(e).attr('id') != "" ? 'carrousel_' + tA.getTime() : $(e).attr('id'));
        this.container = $(e).parent();
        this.container.parent().css('overflow', 'hidden').append("<a href='#' id='" + this.id + "_prev' class='carrousel_button carrousel_prev'>" + opts.htmlPrevButton + "</a><a href='#' id='" + this.id + "_next' class='carrousel_button carrousel_next'>" + opts.htmlNextButton + "</a><div id='" + this.id + "_legend' class='carrousel_legend'></div>");
        $('a#' + this.id + '_prev').hide().click(function(){
            self._animate('prev');
            return false;
        });
        $('a#' + this.id + '_next').hide().click(function(){
            self._animate('next');
            return false;
        });
        this.aItems = null;
        this.nbItems = 0;
        this.current = 0;
        this.locked = false;
        this.block = {
            width: 0,
            height: 0
        };
        this.margin = {
            width: 0,
            height: 0
        };
        this.dep = 0;
        this.timerMoving = null;
        this.opts = opts;
        this.controls = ctrls;
        this.effects = effects;
        this.direction = ((opts.direction == 'left') || (opts.direction == 'top') ? 'next' : 'prev');
        this.pos = ((opts.direction == 'left') || (opts.direction == 'right') ? 'left' : 'top');
		this.dir = ((opts.direction == 'right') || (opts.direction == 'top') ? -1 : 1);
		this.vertical = (this.pos == 'left' ? false : true);
        this._init();
    };
    var $carrousel = $.carrousel;
    $carrousel.fn = $carrousel.prototype = {
        carrousel: '1.1.7'
    };
    $carrousel.fn.extend = $carrousel.extend = $.extend;
    $carrousel.fn.extend({
        _init: function(){
            var self = this;
            this.aItems = $('> li', this.e);
            this.nbItems = this.aItems.length;
			if (!this.opts.continuous) this.nbItems = this.nbItems * 2;
            var item = this.aItems.eq(0);
            //// outerWidth(true) & outerHeight(true) are bugged with Webkit,
            //// because DOM margin values are wrong
            ////this.block.width = item.outerWidth(true);
            ////this.block.height = item.outerHeight(true);
            ////this.margin.width = this.block.width - item.outerWidth();
            ////this.margin.height = this.block.height - item.outerHeight();
            this.block.width = this.opts.itemWidth;
            this.block.height = this.opts.itemHeight;
            this.margin.width = 0;
            this.margin.height = 0;
            this.container.parent().addClass('carrousel').attr('id', this.id + '_div');
            var width = (this.vertical ? 1 : parseInt(this.opts.dispNumber)) * this.block.width;
            this.container.addClass('carrousel_carrousel').attr('id', this.id + '_carrousel').css({
                'overflow': 'hidden',
                'position': 'relative'
            }).width(width + 'px').height((this.vertical ? parseInt(this.opts.dispNumber) : 1) * this.block.height + 'px').parent().width(width + 'px');
            $('ul > li > ' + this.opts.mode, this.container).each(function(i){
                $(this).wrap('<div class="carrousel_item" rel="' + i + '"></div>');
            });
            this.e.css(this.pos, '0px').width(this.block.width * (this.vertical ? 1 : this.nbItems));
            if (this.opts.stopOver) {
                this.container.bind("mouseenter", function(evt){
                    self.locked = true;
                });
                this.container.bind("mouseleave", function(evt){
                    self.locked = false;
                    if (self.opts.auto) {
                        this.timerMoving = setTimeout(function(){
                            self._animate('next');
                        }, self.opts.dispTimeout);
                    }
                });
            }
            if (this.legend == "mouseover") {
                $('.carrousel_item', this.container).css('cursor', 'pointer');
                for (var i = 0; i < this.nbItems; i++) {
                    $eq = this.aItems.eq(i);
                    $(this.opts.mode, $eq).bind("mouseenter", function(evt){
                        $('div#' + self.id + '_legend').html($(this).attr('title'));
                    });
                    $(this.opts.mode, $eq).bind("mouseleave", function(evt){
                        $('div#' + self.id + '_legend').html("");
                    });
                }
            }
            if (this.legend == "always") {
                $('div#' + self.id + '_legend').html($(self.opts.mode, this.container).eq(this.realpos(this.current)).attr('title'));
            }
            var control = this.opts.controls.split(' ');
            for (var i = 0; i < control.length; i++) {
                if ($.isFunction(this.controls[control[i]]))
                    this.controls[control[i]](this);
            }
            if (this.opts.mode == 'img') {
                $('.carrousel_item img', this.container).load(function(){
                    $this = $(this);
                    $this.parent().width($this.width()).height($this.height());
                });
            }
            var effect = this.opts.effects.split(' ');
            for (var i = 0; i < effect.length; i++) {
                if ($.isFunction(this.effects.init[effect[i]]))
                    this.effects.init[effect[i]](this);
            }
            if (self.opts.auto) {
                setTimeout(function(){
                    self._animate('next');
                }, self.opts.dispTimeout);
            }
        },
        _animate: function(dir){
            dir = (dir == undefined ? this.direction : dir);
            if (!this.locked) {
                clearTimeout(this.timerMoving);
                this.locked = true;
                this.dep = this.dep == 0 ? this.opts.scroll : this.dep;
                if (this.dir == -1) {
					if (dir == "next") {
						dir = "prev";
					}
					else if (dir == "prev") {
						dir = "next";
					}
				}
				if (dir != 'next') {
                    this.dep *= -1;
                }
				var cont = true;
				if (!this.opts.continuous) {
					if (dir == 'next') {
	                    if (this.current == ((this.nbItems / 2) - this.opts.dispNumber)) {
	                        cont = false;
							this.locked = false;
	                    }
	                }
	                else {
	                    if (this.current == 0) {
	                        cont = false;
							this.locked = false;
	                    }
	                }
	            }
				if (cont)
                	this._beforeMoving();
            }
        },
        _beforeMoving: function(){
            var effect = this.opts.effects.split(' ');
            for (var i = 0; i < effect.length; i++) {
                if ($.isFunction(this.effects.before[effect[i]]))
                    this.effects.before[effect[i]](this, (this.dep < 0 ? -1 : 1));
            }
            this._move();
        },
        _move: function(){
            var self = this;
            if ($.isFunction(this.opts.move)) {
                this.opts.move(this, function(){
                    self._afterMoving();
                });
            }
            else {
                var self = this;
                var size = this.vertical ? this.block.height : this.block.width;
                if (this.dep > 0) {
                    while (parseInt(this.e.css(this.pos)) < 0) {
                        var item = $('> li:first', this.e);
                        $('> li:first', this.e).remove();
                        this.e.append(item);
                        this.e.css(this.pos, parseInt(this.e.css(this.pos)) + size);
                    }
                }
                else {
                    for (var i = 0; i < Math.abs(this.dep); i++) {
                        var item = $('> li:last', this.e);
                        $('> li:last', this.e).remove();
                        this.e.prepend(item);
                    }
                    this.e.css(this.pos, parseInt(this.e.css(this.pos)) + this.dep * size + 'px');
                }
                var b = parseInt(this.e.css(this.pos));
                if (this.vertical) {
                    this.e.stop(true, true).animate({
                        top: b - this.dep * this.block.height + 'px'
                    }, this.opts.speed, this.opts.easing, function(){
                        self._afterMoving();
                    });
                }
                else {
                    this.e.stop(true, true).animate({
                        left: b - this.dep * this.block.width + 'px'
                    }, this.opts.speed, this.opts.easing, function(){
                        self._afterMoving();
                    });
                }
            }
        },
        _afterMoving: function(){
            var self = this;
            this.current = this.current + this.dep;
            if (this.current == -1) {
                this.current = this.nbItems - 1;
            }
            else {
                if (this.current == this.nbItems) {
                    this.current = 0;
                }
                else {
                    this.current = this._realpos(this.current);
                }
            }
            if (this.legend == "always") {
                $('div#' + this.id + "_legend").html($(this.opts.mode, this.container).eq(this.realpos(this.current)).attr('title'));
            }
            this.dep = 0;
            this.locked = false;
            var effect = this.opts.effects.split(' ');
            for (var i = 0; i < effect.length; i++) {
                if ($.isFunction(this.effects.after[effect[i]]))
                    this.effects.after[effect[i]](this);
            }
            for (var i = 0; i < this.opts.callbacks.length; i++) {
                this.opts.callbacks[i](this);
            }
            var control = this.opts.controls.split(' ');
            for (var i = 0; i < control.length; i++) {
                if ($.isFunction(this.controls.callback[control[i]]))
                    this.controls.callback[control[i]](this);
            }
            if (this.opts.auto) {
                this.timerMoving = setTimeout(function(){
                    self._animate('next');
                }, this.opts.dispTimeout);
            }
        },
        _realpos: function(i){
            return (i < (this.nbItems / 2) ? i : (i - (this.nbItems / 2)));
        },
        start: function(){
            if (!this.opts.auto) {
                this.locked = false;
                this.opts.auto = true;
                this._animate('next');
            }
            return false;
        },
        stop: function(){
            clearTimeout(this.timerMoving);
            this.opts.auto = false;
            return false;
        },
        next: function(){
            this._animate('next');
            return false;
        },
        prev: function(){
            this._animate('prev');
            return false;
        },
        getCurrent: function(){
            return this._realpos(this.current);
        },
        moveTo: function(i){
            if (i > (this.nbItems / 2)) {
                i = (this.nbItems / 2) - 1;
            }
            this.dep = parseInt(i) - parseInt(this.current);
            if (this.dep != 0) {
                this._animate('next');
            }
            return false;
        }
    });
    $.fn.carrousel.defaults = {
        auto: true,
        infinite: true,
        controls: 'button',
        effects: '',
        easing: '',
        continuous: true,
        speed: 2000,
        direction: 'right',
        scroll: 1,
        dispTimeout: 1000,
        stopOver: true,
        dispNumber: 3,
        legend: '',
        mode: 'img',
        htmlPrevButton: "prev",
        htmlNextButton: "next",
        callbacks: [],
        api: false,
        /////
        itemWidth: 0,
        itemHeight: 0
    };
    $.fn.carrousel.controls = {
        button: function(carrousel){
            $("a#" + carrousel.id + '_prev').show();
            $("a#" + carrousel.id + "_next").show();
        },
        callback: {}
    };
    $.fn.carrousel.effects = {
        init: {},
        before: {},
        after: {}
    };
});
