(function($) {
	$.fn.b2Slider = function(attr) {
		var reset = {
			autoPlay: false,
			speed: 1000
		};
		
		var attr = $.extend(reset, attr);
		
		this.each(function() {
			var obj = $(this); 
			var length = $('li', $(this)).length;
			var width = $('li', $(this)).width();
			var height = $('li', $(this)).height();
			var clickable = true;
			
			$(this).width(width);
			$(this).height(height);
			$(this).css("overflow", "hidden");
			var ts = length-1;
			var t = 0;
			
            $('ul', $(this)).css("width", width*length);
			$("ul", $(this)).prepend($("ul li:last-child", $(this)).clone().css("margin-left","-"+ width +"px"));
			$("ul", $(this)).append($("ul li:nth-child(2)", $(this)).clone());
			$("ul", $(this)).css('width',(length+1)*width);			
			$("li", $(this)).css('float','left');

			var html = '';			
			html += '<ul id="switcher"></ul>';
			$($(this)).after(html);	
            									
			for(var i=0; i<length; i++) {
				$(document.createElement("li"))
					.attr('id', 'switcher' + (i+1))
					.html('<a rel=\"'+i+'\" href=\"javascript:void(0);\"></a>')
					.appendTo($("#switcher"))
					.click(function() {
						animate($("a", $(this)).attr('rel'), true);
					});
			};

			function setCurrent(i){
				i = parseInt(i)+1;
				$("li", "#switcher").removeClass("current");
				$("li#switcher"+ i).addClass("current");
				$("li", "#switcher").css("color", "black");
				$("li#switcher"+ i).css("color", "yellow");
				
			};
			
			function adjust(){
				if(t>ts) t=0;		
				if(t<0) t=ts;	
				
					$("ul",$(this)).css("margin-left",(t*height*-1));
				
				clickable = true;
				setCurrent(t);
			};
			
			function animate(dir,clicked){
				if (clickable){
					clickable = false;
					var ot = t;				
					switch(dir){
						case "next":
							t = (ot>=ts) ? (1==1 ? t+1 : ts) : t+1;			
							break; 
						case "prev":
							t = (t<=0) ? (1==1 ? t-1 : 0) : t-1;
							break; 
						case "first":
							t = 0;
							break; 
						case "last":
							t = ts;
							break; 
						default:
							t = dir;
							break; 
					};	
					var diff = Math.abs(ot-t);
					var speed = diff*attr.speed;						
					
						p = (t*width*-1);
						$("ul",obj).animate(
							{ marginLeft: p }, 
							{ queue:false, duration:speed, complete:adjust }
						);							
					if(clicked) clearTimeout(timeout);
					if(attr.autoPlay && dir=="next" && !clicked){
						timeout = setTimeout(function(){
							animate("next",false);
						},diff*attr.speed+6000);
					};
			
				};
				
			};
			
			//initialize
			var timeout;
				timeout = setTimeout(function(){
					animate("next",false);
				},4000);
			
			setCurrent(0);
		});
	};
})(jQuery);
