$(function() {

	$('.carousel').each(function() {
		
		var $carousel = $(this);
		var $left = $carousel.find('.left');
		var $right = $carousel.find('.right');
		var $table = $carousel.find('table');
		
		if ($table.find('td').length) {
			var cellWidth = $table.find('td:first').outerWidth();
	
			$right.click(function() {
				if ($carousel.find(':animated').length) {
					return false;
				}
				var $first = $table.find('td:first');
				var $last = $table.find('td:last');
				var size = $first.outerWidth();
				$table.animate({'margin-left': -size}, function() {
					$first.insertAfter($last);
					$table.css({'margin-left': 0});
				});
			});
			
			$left.click(function() {
				if ($carousel.find(':animated').length) {
					return false;
				}
				var $first = $table.find('td:first');
				var $last = $table.find('td:last');
				var size = $last.outerWidth();
				$table.css({'margin-left': -size});
				$last.insertBefore($first);
				$table.animate({'margin-left': 0}, function() {
					
				});
			});
			
			function onresize() {
				$carousel.css('width', 'auto');
				$table.hide();
				if (!cellWidth) {
					cellWidth = $table.find('td:first').outerWidth();
				}
				var newWidth = Math.floor(($carousel.parent().width() - 60) / cellWidth) * cellWidth;
				if (newWidth < cellWidth) {
					newWidth = cellWidth;
				}
				if (!$.support.boxModel) {
					newWidth += 60;
				}
				
				$carousel.width(newWidth);
				$table.show();
				
				if ($carousel.width() < $table.width()) {
					$left.show();
					$right.show();
				} else {
					$left.hide();
					$right.hide();
				}
				
				$right.height($carousel.height());
				$left.height($carousel.height());
			}
			onresize();
			
			$(window).resize(function() {
				onresize();
			});
			
			setTimeout(onresize, 1);
		}
		
	});

});
