/* Rotator
 * Version 1.0.0
 * Author Michael Neil
 * URI: http://www.fluxar.com/
 */
(function($){ //jQuery.noConflict()compliant	
    $.fn.rotator = function(o, callback){
    	
    	o = $.extend({ //defaults, can be overidden
    		arrows: {left:".leftarrow",right:".rightarrow"},
	    	tranSpeed: 800,//ms transition speed
	    	delay: 4000,//ms delay before next transition
	    	auto: false,//sets auto scrolling through rotator
	    	loop: false,//infinite scroll on or off, default false rotates back to beginning
	    	backwards: false
        }, o ||
        {});

        if(!$(this)){alert("Must specify an object to target.");return false;}
       
        var reverse = false;
        if(o.backwards)reverse = true;
        if(o.backwards && !o.loop)
        	o.backwards = false;
        
        $(this).each(function(i){
        	var that = $(this);
        	beforeN = $(this).children("li").length;

        	var beforeN = 0;
			var inner = "";
			if(o.loop){
				beforeN = $(this).children("li").length;
				inner = $(this).html();
				$(this).children("li:first").before(inner);
				$(this).children("li:last").after(inner);
	        }
	       	
			var w = $(this).children("li").width();
			var n = $(this).children("li").length;
			var cur = beforeN;
			var animate = false;
			
			$(this).css({"margin-left":-cur*w});
			$(this).css({width:w*n});	
			
			
			$(o.arrows.right).click(function(){
				if(cur == n-1)return;
				if(o.auto){clearInterval(interval);interval = setInterval(goNext,o.delay);o.backwards = false;}
				if(animate)return;cur++;animate = true;
				that.animate({marginLeft:-cur*w},o.tranSpeed,reset);
			});
			$(o.arrows.left).click(function(){
				if(cur==0)return;
				if(o.auto){clearInterval(interval);interval = setInterval(goNext,o.delay);o.backwards = true;}
				if(animate)return;cur--;animate = true;
				that.animate({marginLeft:-cur*w},o.tranSpeed,reset);
			});
			if(o.auto){
				var interval = setInterval(goNext,o.delay);
			}
			function goNext(){
				if(cur == n-1){if(reverse){o.backwards = true}else{return}};//else{};
				if(cur == 0 && reverse)o.backwards = false;
				if(animate)return;if(!o.backwards){cur++}else{cur--};animate = true;
				that.animate({marginLeft:-cur*w},o.tranSpeed,reset);
			}
			function reset(){
				animate = false;
				if(cur==0 || cur==n-beforeN){
					cur = beforeN;
					$(this).css({"margin-left":-cur*w});
				}
			}
    	});
        
        
	}
})(jQuery);
