// JavaScript Document
(function($) {
	$.fn.ITSailSlider = function(option){
		var defaults = {autoable:1};
		option = $.extend(defaults, option);
		
		var oMain = $(this);
		var oUl = $(".slider ul", oMain);
		var oULi = $("li", oUl);
		var nums = oULi.length - 1;
		var this_num = 0;
		var last_num = 0;
		var width = oULi.width();
		
		var timerID = null;
		var timeout = 5000;
		var timestep = 1000;
		var slideWay = 1;

		var autoable = 1;
		var t_autoable = 1;
		if(typeof option.autoable != undefined) t_autoable = option.autoable;

		var html = '';
		for(var i=0;i<=nums;i++){
			html += '<li></li>';
		}
		$('.dot', oMain).html('<ol>' + html+ '</ol>');
		
		oULi.css({
			position: 'absolute',
			top: 0, 
			left: width,
			zIndex: 0,
			display: 'none'
		});
		
		oULi.eq(0).fadeIn();
			
		oUl.css({
			overflow: 'visible',
			position: 'relative',
			// size of control 3 x slide width
			width: (width * 3),
			// center control to slide
			left: -width
		});

		var position=0, direction=0, next = 0, prev = 0, number = 0, current = 0;
		
		var controls = $('ol li', oMain);
		controls.click(function(){onclick($(this).index());});
		controls.eq(0).addClass("current");
		
		$('.arrowL', oMain).click(function(){slideWay=1; onclick(current + 1);});
		$('.arrowR', oMain).click(function(){slideWay=-1; onclick(current - 1);});
		function slide() {
			autoable = 0;
			
			if(next > nums) next = 0;
			else if(next < 0) next = nums;
			
			if(next == current) return;
			
			prev = current;
			current = next;
			
			if (slideWay > 0) {
				position = width*2;
				direction = -width*2;
			} else {
				position = 0;
				direction = 0;
			}
			
			oULi.eq(next).css({
				left: position,
				display: 'block'
			});
			
			oUl.animate({left: direction}, timestep, '', function(){
				// after animation reset control position
				oUl.css({
					left: -width
				});
				// reset and show next
				oULi.eq(next).css({
					left: width,
					zIndex: 5
				});
				// reset previous slide
				oULi.eq(prev).css({
					left: width,
					display: 'none',
					zIndex: 0
				});
				// end of animation
				timer();
			});
			
			
			controls.eq(prev).removeClass("current");
			controls.eq(next).addClass("current");
		}
		
		function auto() {
			slideWay = 1;
			next = current + 1;
			slide();
		}
		
		function timer() {
			autoable = 1;
			if(t_autoable == 1) timerID = setTimeout(auto, timeout);
		}
		
		function onclick(id) {
			if(autoable == 1) {
				clearTimeout(timerID);
				next = id;
				slide();
			}
		}
		
		oUl.hover(function(){autoable=0;clearTimeout(timerID);}, function(){autoable=1;timer();});

		timer();
	};
})(jQuery);


