var carousel = 
{
	dir: 0,
	interval: null,
	
	lastWidth: null,
	width: null,
	wrapperWidth: null,
	
	init: function()
	{
		if ($('#carousel').length == 0)
			return;
		$('#carousel .left').hover(function() { carousel.start(-1); }, function() { carousel.stop(); } );
		$('#carousel .right').hover(function() { carousel.start(1); }, function() { carousel.stop(); } );
		this.wrapperWidth = $('#carousel .wrapper').width();
		setInterval(function() { carousel.check(); }, 100);
		carousel.exec();
	},

	check: function()
	{
		this.width = this.findWidth();
		if (this.width != this.lastWidth)
		{
			this.lastWidth = this.width;
			if (this.width < this.wrapperWidth)
			{
				$('#carousel .left, #carousel .right').fadeOut();
				//$('#carousel .wrapper').css('margin-left', ((this.wrapperWidth - this.width) / 2) + 'px');
			}
			else
				$('#carousel .left, #carousel .right').fadeIn();
		}
	},
	
	findWidth: function()
	{
		var last = $('#carousel li:last-child');
		var width = last.position().left + last.width() + 100;
		return width;
	},
	
	start: function(dir) 
	{
		this.dir = dir;
		this.interval = setInterval( function() { carousel.exec(); }, 10 );
	},
	
	stop: function() 
	{
		clearInterval(this.interval);
	},
	
	exec: function()
	{
		var left = $('#carousel ul').position().left;
		left -= this.dir * 4;
		left = Math.min(0, Math.max(-this.width + 853 + 40, left));
		
		//console.log(left, -this.width + 853);
		$('#carousel ul').css('left', left + 'px');
		$('#carousel li').each(function() {
			var x = $(this).position().left + left;
			var width = $(this).width();
			var opacity = 1;
			if (x < 0)
				opacity = Math.max(0, 1 + x / 50);
			else if (x > 600 - width)
				opacity = Math.max(0, 1 - (x - 600 - width) / 50);
			$(this).css('opacity', opacity);
		});
	}	
};
