(function($){
	$(document).ready(function(){
		var slidewrap = $('#home_sub .slides')[0]
			, slides = $('#home_sub .slide')
			, links = []
			, tallest = 0
			, width = $(slidewrap).width()
			, nav = $('<div class="slide-nav"/>').insertAfter(slidewrap)
			, current = 0
			, time = 10000
			, restarttime = 30000
			, slide = function(i)
			{
				$(slides[current]).animate({left:(0-width)});
				$(slides[i]).css({left:width}).animate({left:0});
			}
			, rotate = function()
			{
				var i = current + 1;
				if(i==slides.length) i = 0;
				$(links[current]).removeClass('current');
				$(links[i]).addClass('current');
				slide(i);
				current = i;
				clearTimeout(timer);
				timer = setTimeout(rotate,time);
			}
			, timer = setTimeout(rotate,time);
			;
		
		$(slides).each(function(i,el){
			var h = parseInt($(el).outerHeight(true));
			if(h>tallest) tallest = h;
			$(el).css({
				position: 'absolute'
				, top: 0
				, left: (i==0 ? 0 : width)
				, width: width
			});
			
			var link = $('<a href="#">'+(i+1)+'</a>').click(function(e){
				e.preventDefault();
				// Cancel rotate but restart if user hasn't 
				// interacted after restarttime length 
				clearTimeout(timer);
				timer = setTimeout(rotate,restarttime);
				if(i==current) return;
				slide(i);
				$(links[current]).removeClass('current');
				$(this).addClass('current');
				current = i;
			});
			if(i==0) {
				currentlink = link;
				$(link).addClass('current');
			}
			$(nav).append(link);
			links.push(link);
		});
		
		$(slidewrap).css({
			position: 'relative'
			, width: width
			, height: tallest
			, overflow: 'hidden'
		});
		
	});
})(jQuery);
