jQuery(document).ready(function ($) {
	var $items = $('#slider > ul');

	var numItems = $items.children('li').length;
	var offsetDist = $items.children('li:first').next().position().left;
	var overflow = false;	

	//If there are more items than can be shown at once, show the left and right links.
	if (numItems * offsetDist > $items.width()) {
		overflow = true;
		$items.css('overflow', 'visible');

		//Enable the left link.
		$('#slider > .left > a').removeClass('hidden').addClass('clickable').click(function(e) {
			e.preventDefault();
			
			//If the link is clickable
			if ($(this).hasClass('clickable')) {
				moveRight();
			}
		});

		//Enable the right link.
		$('#slider > .right > a').removeClass('hidden').addClass('clickable').click(function(e) {
			e.preventDefault();

			//If the link is clickable
			if ($(this).hasClass('clickable')) {
				moveLeft();
			}
		});

		var intID = setInterval(moveLeft, 8000);
			$('#slider').hover(function() {
				clearInterval(intID);
			}, function() {
				intID = setInterval(moveLeft, 8000);
		});


	}


	//Set the items in their places using absolute positioning.
	$items.children('li').each(function(i) {
		if (i < numItems - 1 || !overflow) {
			$(this).css('position', 'absolute').css('left', (offsetDist * i) + 'px').css('top', '0px');
		}
		else {
			//If there is overflow, give the last item a negative position.
			$(this).css('position', 'absolute').css('left', -offsetDist + 'px').css('top', '0px');
		}
	});

	function moveLeft() {
		$('#slider > .arrow > a').removeClass('clickable');
				
		$items.children('li:last').css('left', (offsetDist * (numItems - 1)) + 'px');
		$items.children('li:first').appendTo($items);

		$items.children('li').each(function(i) {
			if (i < numItems - 1) {
				$(this).animate({left: (offsetDist * i) + 'px'}, 300, function() {
					if (i == 0) {
						$('#slider > .arrow > a').addClass('clickable');
					}
				});
			}
			else {
				$(this).animate({left:  -offsetDist + 'px'}, 300);
			}
		});
	}

	function moveRight() {
		$('#slider > .arrow > a').removeClass('clickable');

		$items.children('li:last').prependTo($items);

		$items.children('li').each(function(i) {
			$(this).animate({left: (offsetDist * i) + 'px'}, 300, function() {
				if (i == 0) {
					$('#slider > .arrow > a').addClass('clickable');
				}else if (i == numItems - 1) {
					$(this).css('left', -offsetDist + 'px');
				}
			});
		});
	}
	
});

