(function($) {
	jQuery.fn.snuko_slider = function(opt) {
		var el=$(this),
			width = el.width(),
			current = 1,
			previous = 1,
			count = el.find('li').length,
			titles = [],
			animation_speed = 2000,
			slide_show_interval = 7500,
			timer;
		
		function find_adjacent(from, direction){
			var adjacent = from;
			
			if(direction == 1){
				if(from==count) adjacent=1;
				else adjacent++;
			}				
			//Going left
			else{
				if(from == 1) adjacent = count;
				else adjacent = from - 1;
			}
			return adjacent;
		}
		
		/* no longer required?
		function find_ul_height(){
			var max = 0,
				current;
			
			el.find('li').each(function(){
				current = $(this).height();
				alert(current);
				if(current>max) max=current;
			});
			return max;
		}
		*/
		
		function bind_on_click_event(){
			$('#'+opt.left).click(function(){
				clearInterval(timer);
				slide_and_show('0px', 'auto');
			});

			$('#'+opt.right).click(function(){
				clearInterval(timer);
				slide_and_show('auto', '0px');
			});
		}
		
		function start_slide_show() {
			slide_and_show('auto', '0px');
		}
		
		function unbind(){
			$('#'+opt.left).add('#'+opt.right).unbind('click');
		}
		
		function slide_and_show(left, right){
			//Going right
			previous = current;
			
			if(left == 'auto'){
				current = find_adjacent(previous, 1);
			}				
			//Going left
			else{
				current = find_adjacent(previous, 0);
			}
			
			unbind();
						
			//prepare the previous (current) element to exit

			el.find("li:nth-child(" + previous + ")")
				.stop(true, true)
				.css({
						"left": left, 
						"right": right,
						"opacity": 1.0
					})
				.animate(
					{"width": 0},
					1000,
					function(){
						$(this).hide().css({
							"width": width + "px", 
							"opacity": 0
						});
						bind_on_click_event();
					}
				);
			
			//prepare the next element to enter:

			el.find("li:nth-child(" + current + ")")
				.stop(true, true)
				.css({"opacity": 0})
				.show()
				.animate(
					{"opacity": 1},
					animation_speed
				);			
			
			el.css('height', el.find('li:nth-child('+current+')').height());
			
			if(opt.link_text_as_heading !==undefined){
				$('#'+opt.left).find('.link_text').html(titles[find_adjacent(current, 0)-1]);
				$('#'+opt.right).find('.link_text').html(titles[find_adjacent(current, 1)-1]);
			}
		}
		
		el.find('li:gt(0)').css('opacity', '0.0');
		
		el.css('height', el.find('li:first').height() + 'px');
		
		bind_on_click_event();
		
		if (opt.auto) {
			timer = setInterval(start_slide_show, slide_show_interval);
		}
				
		if(opt.link_text_as_heading !== undefined){
			$.each(el.find('li h2'), function(index){
				titles[index]=$(this).html();
			});
		}
		return this;
	};
})(jQuery);

