$(function()
{
	$('nav[role=navigation]>ul>li').hover(function() { $(this).addClass('hover'); }, function() { $(this).removeClass('hover'); });

	$('#pieces a[href=#prev]').mouseover(function() { dir = -1; startMoving( ); }).bind('mouseout mouseleave', function() { stopMoving(); }).click(function() { return false; });
	$('#pieces a[href=#next]').mouseover(function() { dir = 1; startMoving(); }).bind('mouseout mouseleave', function() { stopMoving(); }).click(function() { return false; });

	var moving = null;               // a timer used to start and stop transition progress
	var pos = 0;                     // the current offset of the carousel
	var $el = $('#pieces ul');       // the elements which is offset
	var maxWidth = 0;                // the maximum offset width
	var dir;                         // direction

	$(window).load(function() {
		/* The maximum offset width is computed from the 
	   	   coumpounded width of each element in the list
	 	 */
		$('#pieces li').each( function(i) { maxWidth -= this.offsetWidth + 40; });

		/* ... minus the viewport width
	 	 */
		$('#pieces div').eq(0).each(function() { maxWidth += this.offsetWidth; });
	});

	function startMoving( dir )
	{
		moving = window.setTimeout( move, 20, dir );
	}

	function stopMoving()
	{
		window.clearInterval( moving );
	}

	var prout = 0;
	function move()
	{
		pos += dir * 6;
		if( pos > 0 ) pos = 0;
		else if( pos < maxWidth ) pos = maxWidth;
		$el.css({ left: pos + 'px' });
		
		moving = window.setTimeout( move, 20, dir );
	}


	$('#promos nav a').click(function() {
		if( $(this).hasClass('current') ) return false;

		var $a = $(this);
		var $el = $($(this).attr('hash'));

		$el.addClass('next');

		$('#promos li.current').fadeOut(300, function() {
			$el.fadeIn(400, function() {
				$('#promos .current').removeClass('current');
				$(this).removeClass('next').addClass('current');
				$a.addClass('current');
				$a = null;
				$el = null;
			});
		});

		return false;
	});

	$('.qty a[href="#stepup"]').bind('click keyup', function()
	{
		if( Modernizr.inputtypes.number )
			this.nextSibling.nextSibling.stepUp(1);
		else
			$(this).next('input[type=number]').val(parseInt($(this).next('input[type=number]').val()) + 1);

		return false;
	})

	$('.qty a[href="#stepdown"]').bind('click keyup', function()
	{
		if( Modernizr.inputtypes.number )
			this.previousSibling.previousSibling.stepDown(1);
		else if( parseInt($(this).prev('input[type=number]').val()) > 0 )
			$(this).prev('input[type=number]').val(parseInt($(this).prev('input[type=number]').val()) - 1);

		return false;
	})
})
