/** 
 * 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.0.1
 *
 * 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>');
        $(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.dep = -1;
        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.vertical = (this.pos == 'left' ? false : true);
        this._init();
    };
    var $carrousel = $.carrousel;
    $carrousel.fn = $carrousel.prototype = {
        carrousel: '1.0.1'
    };
    $carrousel.fn.extend = $carrousel.extend = $.extend;
    $carrousel.fn.extend({
        _init: function(){
            var self = this;
            this.aItems = $('> li', this.e);
            this.nbItems = this.aItems.length;
			var item = this.aItems.eq(0);
            this.block.width = parseInt(item.width()) + parseInt(item.css('margin-left')) + parseInt(item.css('margin-right'));
            this.block.height = parseInt(item.height()) + parseInt(item.css('margin-top')) + parseInt(item.css('margin-bottom'));
            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);
                    self._alignItem($this.parent());
                    $this.parent().width($this.width()).height($this.height());
                });
            }
            else {
                this._alignItem($('.carrousel_item', this.aItems.eq(i)));
            }
            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);
            }
        },
        _alignItem: function(item){
            item.css({
                'top': this._getAlignHeight(parseInt($(this.opts.mode, item).height())),
                'left': this._getAlignWidth(parseInt($(this.opts.mode, item).width())),
                'position': 'relative'
            });
        },
        _getAlignHeight: function(size){
            var top = this.block.height - size;
            if (this.opts.align.indexOf('top') != -1) {
                return '0px';
            }
            if (this.opts.align.indexOf('bottom') != -1) {
                return top + 'px';
            }
            if (this.opts.align.indexOf('center') != -1) {
                return parseInt(top / 2) + 'px';
            }
            return '0px';
        },
        _getAlignWidth: function(size){
            var left = this.block.width - size;
            if (this.opts.align.indexOf('left') != -1) {
                return '0px';
            }
            if (this.opts.align.indexOf('right') != -1) {
                return left + 'px';
            }
            if (this.opts.align.indexOf('center') != -1) {
                return parseInt(left / 2) + 'px';
            }
            return '0px';
        },
        _animate: function(dir){
            dir = (dir == undefined ? this.direction : dir);
            if (!this.opts.continuous) {
                if (dir == 'next') {
                    if (this.current == ((this.nbItems / 2) - 1)) {
                        this.locked = true;
                    }
                }
                else {
                    if (this.current == 0) {
                        this.locked = true;
                    }
                }
            }
            if (!this.locked) {
                this.locked = true;
                this._beforeMoving(dir);
            }
        },
        _beforeMoving: function(direction){
            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, (direction == 'prev' ? -1 : 1));
            }
            this._move(direction);
        },
        _move: function(direction){
            var self = this;
            var move = this.dep == -1 ? this.opts.scroll : this.dep;
            var size = this.vertical ? this.block.height : this.block.width;
            if (direction == 'next') {
                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 < move; 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)) - move * size + 'px');
            }
            var nb = (direction == 'prev' ? -1 : 1) * move;
            var b = parseInt(this.e.css(this.pos));
            if (this.vertical) {
                this.e.stop().animate({
                    top: b - nb * this.block.height + 'px'
                }, this.opts.speed, this.opts.easing, function(){
                    self._afterMoving(direction);
                });
            }
            else {
                this.e.stop().animate({
                    left: b - nb * this.block.width + 'px'
                }, this.opts.speed, this.opts.easing, function(){
                    self._afterMoving(direction);
                });
            }
        },
        _afterMoving: function(direction){
            var self = this;
            this.current = this.current + (direction == 'prev' ? -1 : 1) * (this.dep == -1 ? this.opts.scroll : 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 = -1;
            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);
            }
            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(){
            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.dep = (this.nbItems / 2) + parseInt(this.dep);
            }
            if (this.dep != 0) {
                this._animate('next');
            }
            return false;
        }
    });
    $.fn.carrousel.defaults = {
        auto: true,
        controls: 'button',
        effects: '',
		easing: '',
        continuous: true,
        speed: 2000,
        direction: 'right',
        scroll: 1,
        dispTimeout: 1000,
        stopOver: true,
        dispNumber: 3,
        legend: '',
        align: 'left',
        mode: 'img',
        htmlPrevButton: "prev",
        htmlNextButton: "next",
        callbacks: [],
        api: false
    };
    $.fn.carrousel.controls = {
        button: function(carrousel){
            $("a#" + carrousel.id + '_prev').show();
            $("a#" + carrousel.id + "_next").show();
        }
    };
    $.fn.carrousel.effects = {
        init: {},
        before: {},
        after: {}
    };
});


