$(function () {

	var SLIDE_WIDTH = 680;

	$("#main-show .main-show").each(function () {

		var root = $(this),
			tabs = root.find("div.tabs-content > ul > li"),
			tabPosition = 0;

		if (!tabs.length) {
			return;
		}

		tabs.each(function () {
			$(this).css("left", tabPosition);
			tabPosition = tabPosition + SLIDE_WIDTH;
		});

		var ctrl = [];

		ctrl.push('<div class="tabs-control"><div class="tabs-control-wrap"><ul class="clearfix">');
		tabs.each(function (i) {
			var title = $(this).find("h3");
			ctrl.push('<li class="' + (i > 0 ? '' : 'active') + '">');
			ctrl.push('<span>' + title.html() + '</span>');
			ctrl.push('</li>');
			title.remove();
		});
		ctrl.push('</ul></div></div>');

		root.prepend(ctrl.join(''));

		root.find("div.tabs-control span").bind("click", function () {
			if ($(this).hasClass("active")) {
				return;
			}

			var tab = $(this).closest("li"),
				all = tab.parent().children(),
				index = all.index(tab),
				pos, container;

			if (index >= 0) {
				container = root.find("div.tabs-content > ul");
				container.stop();
				pos = parseInt(container.find("> li").eq(index).css("left"));
				container.animate( {"left": -pos} );
				all.removeClass("active");
				tab.addClass("active");
			}
		});

	});	

	$("#main-show dt").bind("click", function () {
		if ($(this).hasClass("active")) {
			return;
		}

		$(this).siblings(".active").removeClass("active first-active").end()
			.next().andSelf().addClass("active");
		if ($(this).hasClass("first")) {
			$(this).addClass("first-active");
		}
	});

	
	var SLIDE_TIMEOUT = 10000;
	var slide_timeoutId = 0;
	var film_count = $('#main-show dd:first .tabs-control ul li').length;
	var film_i = 0;
	
	slide_timeoutId = setTimeout( shiftSlideWindow, SLIDE_TIMEOUT );
	$('#main-show').click( function(){ clearTimeout( slide_timeoutId ); } );
	
	function shiftSlideWindow()
	{
		film_i = ( film_i + 1 ) % film_count;
		$('#main-show dd:first .tabs-control ul li:eq('+film_i+') span').click();
		
		slide_timeoutId = setTimeout( shiftSlideWindow, SLIDE_TIMEOUT );
	}
	
});
