// JavaScript Document
(function($) {
	$.fn.slider = function(options) {
		var opts = $.extend({}, $.fn.slider.defaults, options);
		return this.each(function() {
			var $this 			= $(this);
			$this.opts 			= $.extend({}, opts);
			if($('.slider_help').length > 0){
				$this.opts.helper = $('.slider_help');
			}
			if($this.find('.active').length == 0){
				$this.find('ul li:eq(0)').addClass('active').show();
			}
			$this.find('ul li:not(.active)').css({'opacity':0}).hide();
			
			if($this.opts.helper){
				$this.opts.helper.find('li').hide();
				$this.opts.helper.find('li:eq('+$this.find('.active').index()+')').show();
			}
			
			$.fn.slider.startSlideshow($this);
			$this.hover(function(){ $.fn.slider.stopSlideshow($this); }, function(){ $.fn.slider.startSlideshow($this); });
			$this.find('.next').bind('click',function(e){e.preventDefault(); $.fn.slider.next($this); });
			$this.find('.prev').bind('click',function(e){e.preventDefault(); $.fn.slider.prev($this); });
		});
	};
	$.fn.slider.defaults = {
		timeout: 		4000,
		interval: 		null,
		slidedistance: 	20
	};
	
	$.fn.slider.startSlideshow = function($this){
		$.fn.slider.stopSlideshow($this);
		$this.opts.interval = setInterval(function(){ $.fn.slider.next($this); }, $this.opts.timeout);
	}
	
	$.fn.slider.stopSlideshow = function($this){
		clearInterval($this.opts.interval);
	}
	
	$.fn.slider.prev = function($this){
		$this.opts.nextActive = $this.find('.active').prev('li');
		if($this.opts.nextActive.length == 0){
			$this.opts.nextActive = $this.find('ul li:last');
		}
		$.fn.slider.slide($this, 'prev');
	}
	
	$.fn.slider.next = function($this){
		$this.opts.nextActive = $this.find('.active').next('li');
		if($this.opts.nextActive.length == 0){
			$this.opts.nextActive = $this.find('ul li:eq(0)');
		}
		$.fn.slider.slide($this, 'next');
	}
	
	$.fn.slider.slide = function($this, $from){
		$this.find('.active').removeClass('active').addClass('hide');
		$this.opts.nextActive.addClass('active');
		
		if($this.opts.helper){
			$this.opts.helper.find('li:eq('+$this.find('.active').index()+')').show().stop().css({'marginTop':'0px'}).fadeTo(50,1,function(){});
		}
		$this.find('.active').removeClass('hide').show().stop().css({}).fadeTo(300,1,function(){});
		if($from == 'next'){
			$this.find('.active img').stop().css({'marginLeft':'-'+$this.opts.slidedistance+'px'}).animate({'marginLeft':'0px'},500,function(){})
		}else{
			$this.find('.active img').stop().css({'marginLeft':$this.opts.slidedistance+'px'}).animate({'marginLeft':'0px'},500,function(){})
		}
		$this.find('.hide').stop().animate({'opacity':0},500,function(){ $(this).removeClass('hide').hide()})
		
		$this.find('.hide').each(function(){
			if($this.opts.helper){
				$this.opts.helper.find('li:eq('+$(this).index()+')').stop().animate({'opacity':0,'marginTop':'30px'},300,function(){ $(this).removeClass('hide').hide()});
			}
		});
	}
	
})(jQuery);
