$(function()
{

	var ul = $('#homepage-slideshow>ul').addClass('slideshow-active'),
		lis = ul.find('li'),
		numItems = lis.length - 1;
		currentItem = 0,
		maxHeight = 0,
		showNextTimeout = false
		;

	if (numItems < 0) {
		return;
	}

	lis.each(
		function()
		{
			var h = $(this).outerHeight();
			if (h > maxHeight) {
				maxHeight = h;
			}
		}
	).hide().first().show();

	function changeImage(dir, wrap)
	{
		if (showNextTimeout) {
			clearTimeout(showNextTimeout);
			showNextTimeout = false;
		}
		var lastItem = currentItem;
		currentItem += dir;
		if (currentItem < 0) {
			currentItem = 0;
		} else if (currentItem > numItems) {
			if (wrap) {
				currentItem = 0;
			} else {
				currentItem = numItems;
			}
		}
		if (lastItem != currentItem) {
			lis.eq(lastItem).stop().fadeTo(500, 0);
			lis.eq(currentItem).stop().fadeTo(500, 1);
		}
		positionLabel.text((currentItem + 1) + ' / ' + (numItems + 1));
		backLink[currentItem == 0 ? 'addClass' : 'removeClass']('disabled');
		nextLink[currentItem == numItems ? 'addClass' : 'removeClass']('disabled');
		initTimeout();
	}
	function initTimeout()
	{
		if (showNextTimeout) {
			clearTimeout(showNextTimeout);
		}
		showNextTimeout = setTimeout(
			function()
			{
				changeImage(1, true);
			},
			4000
		);
	}

	var backLink = $('<a href="#" class="disabled">Previous</a>').bind(
					'click',
					function()
					{
						if (!backLink.is('.disabled')) {
							changeImage(-1);
						}
						this.blur();
						return false;
					}
				);
	var nextLink = $('<a href="#">Next</a>').bind(
					'click',
					function()
					{
						if (!nextLink.is('.disabled')) {
							changeImage(1);
						}
						this.blur();
						return false;
					}
				);
	var positionLabel = $('<div>1 / ' + (numItems + 1) + '</div>');

	ul.css(
		{
			'height' : maxHeight + 'px'
		}
	);
	ul.before(
		$('<ul id="homepage-image-nav">').append(
			$('<li />').append(
				backLink
			),
			$('<li />').append(
				positionLabel
			),
			$('<li />').append(
				nextLink
			)
		)
	);

	initTimeout();
});
