$(function(){
	var slides = $('#slides');
	var index = -1;
	var slide_timout = 5000;
	var children = $('#slides > div').length
	var current_slide = 0;
	var links_container;
	var margin_right = parseFloat($('#slides > div').css('margin-right'))
	
	// Add container
	slides.wrap('<div></div>');
	
	// Enable absolute relative positioning
	slides.parent().css({
		'overflow' : 'hidden',
		'position' : 'relative',
		'width' : parseInt(slides.css('width')),
		'height': parseInt(slides.css('height')) // jquery includes padding with $.fn.height()
	}).mouseover(function(){
		clearInterval(interval);
	}).mouseout(function(){
		interval = setInterval(function(){
			slide((children + ++current_slide) % children)
		}, slide_timout );		
	})
	
	slides.css({		
		'position' : 'absolute'	,		
		'left' : 0,
		'width' : (slides.width() * children) + (margin_right * children)
	});	
	
	$('<div></div>').attr('id', 'links_container').css({
		'position':'absolute',
		'bottom' : 7,
		'right' :7
	}).appendTo(slides.parent())

	// Add styling to every div, and assign it an unique index
	$('#slides > div').each(function(i){
		$(this).css(
			{
			 'width' : slides.parent().width(),
			 'height': slides.parent().height()
			}).attr('index', i);
				
		addLink(i)
	});	
		
	function addLink(index){
		$('<button></button>').text(index+1).attr({
			'class': 'slide_button',
			'id': 'slider_button_id_' + index
		}).click(function(){
			slide(index);
		}).appendTo($('#links_container'));		
	}
	
	function slide(target){
		$('#links_container :button').removeClass('slide_button_selected');	
		$('#links_container #slider_button_id_' + target).addClass('slide_button_selected');

		slides.animate({
			// Also include padding
			'left': -(target * slides.parent().width() + target * margin_right)
		},1000);
	}
	
	slide((children + current_slide) % children)	
	var interval = setInterval(function(){
		slide((children + ++current_slide) % children)
	}, slide_timout );	
})
