/*
auther  : Karas
version : 1.0
update  : 2011-04-12

[2011-04-12] 解决由全局变量带来的无法同时在一个页面内使用多次的问题
*/

(function($){

    var win = window;
    
    var main = function(options) {
    
        var config = {
            auto : true ,
            dir : 'right' ,
            child : 'li' ,
            duration : 500 ,
            delay : 5000 ,
            pause : true ,
            margin : 0 ,
            width : 0 ,
            buttonLeft : null ,
            buttonRight : null
        };
        
        var $box = this;
        var timer = null;
        
        $.extend(config, options);
        
        
        function slide(dir)
        {
            var indent = parseInt($box.css('left')) + (dir == 'left' ? config.width : 0 - config.width);
            $box.filter(':not(:animated)').animate({'left' : indent}, config.duration, function(){
                if(dir == 'left'){
                    $box.find(config.child).first().before($box.find(config.child).last());
                }else{
                    $box.find(config.child).last().after($box.find(config.child).first());
                }
                $box.css('left' , '-' + config.width + 'px');
            });
        }
        
        function start(){
            timer = setInterval(function(){slide(config.dir)}, config.delay);
        }
        
        function pause(){
            win.clearInterval(timer);
        }
        
        function bindHover($t){
            $t.hover(function(){
                pause();
            }, function(){
                if(config.auto){ start(); }
            });
        }

        
        config.width = $box.find(config.child).outerWidth() + config.margin;
        config.delay += config.duration;
        
        var $btnLeft = $(config.buttonLeft);
        var $btnRight = $(config.buttonRight);
        
        $btnLeft.click(function(){ slide('left') });
        $btnRight.click(function(){ slide('right') });
        
        if(config.pause){ bindHover($box); bindHover($btnLeft); bindHover($btnRight); }
        if(config.dir != 'left'){ $box.find(config.child).first().before($box.find(config.child).last()); }
        $box.css('left' , '-' + config.width + 'px');
        if(config.auto){ start(); }
    }
    
    $.fn.switchable = main;
    
})(jQuery);
