$(document).ready(
	function()
	{
		if(!jQuery.support.boxModel) return false;
		
		var $items = $('#projects-viewport ul li').removeClass('last').removeClass('hide');
		var itemWidth = $items[0].offsetWidth;
		var itemHeight = $items[0].offsetHeight;
		var itemIndex = 3;
		
		var isScrolling = false;
		
		var isAutoScroll = false;
		var autoScrollInterval;
		
		var $container = $('#projects-viewport ul').addClass('expanded');
		
		var $viewport = $('#projects-viewport');
		
		$($items[$items.length - 1]).addClass('last');
		
		$viewport
			.before('<img id="arrow-left" class="arrow" src="images/arrow-left.png" alt="View More Button" title="View More Work" />')
			.after('<img id="arrow-right" class="arrow" src="images/arrow-right.png" alt="View More Button" title="View More Work" />');
		
		$viewport.scrollLeft(itemIndex * (itemWidth + 10));
		
		var $arrowLeft = $('#arrow-left').click(
				function()
				{
					scrollLeft();
					if(isAutoScroll) stopAutoScroll();
					return false;
				}
			);
		var $arrowRight = $('#arrow-right').click(
				function()
				{
					scrollRight();
					if(isAutoScroll) stopAutoScroll();
					return false;
				}
			);
		
		function scrollLeft()
		{
			if(isScrolling) return false;
			isScrolling = true;
			
			// if we've gone off the left edge
			if(itemIndex-- <= 0)
			{
				// get the far right index, and move us there
				itemIndex = $items.length - 3;
				$viewport.scrollLeft(itemIndex * (itemWidth + 10));
				itemIndex--; // decrement again, so the animation responds to the click right away
			}
			$($viewport).animate({scrollLeft: itemIndex * (itemWidth + 10)}, 400, 'swing', function() {isScrolling = !isScrolling;});
			return false;
		}
		
		function scrollRight()
		{
			if(isScrolling) return false;
			isScrolling = true;
			
			// if we've gone off the right edge
			if(itemIndex++ >= $items.length - 3)
			{
				// move the viewport to 0
				$viewport.scrollLeft(0);
				itemIndex = 1; // so the animation responds to the click right away
			}
			$($viewport).animate({scrollLeft: itemIndex * (itemWidth + 10)}, 400, 'swing', function() {isScrolling = !isScrolling;});
			return false;
		}
		
//		function toggleScrolling()
//		{
//			isScrolling = !isScrolling;
//			return isScrolling;
//		}
		
		function startAutoScroll()
		{
			isAutoScroll = true;
			autoScrollInterval = setInterval(function() {scrollRight();}, 4000);
		}
		
		function stopAutoScroll()
		{
			isAutoScroll = false;
			clearInterval(autoScrollInterval);
		}
		
		startAutoScroll();
	}
);
