var carouselSlideshow = {
	promoTimeout: 5,

	promoTriggered: false,

	promoInitialized: false,

	startPromoCycle: function(t) {
		if(carouselSlideshow.promoInitialized) {
			var buttons = $('#slideshow-buttons');
			var firstButton = $('a:first', buttons);

			this.promoCycle = setInterval(function() {
				carouselSlideshow.promoTriggered = true;
				$(
					$('a.slideshow-current + a', buttons)[0] || firstButton
				).trigger('click');
				carouselSlideshow.promoTriggered = false;
			}, t * 1000);
		}
	},

	stopPromoCycle: function() {
		clearInterval(this.promoCycle);
		clearTimeout(this.promoCycle);
		this.promoCycle = null;
	},

	restartPromoCycle: function() {
		this.stopPromoCycle();

		this.promoCycle = setTimeout(function() {
			with (carouselSlideshow) {
				startPromoCycle(promoTimeout);
			}
		}, 60000);
	},

	init: function() {
		carouselSlideshow.promoInitialized = true;
		carouselSlideshow.startPromoCycle(carouselSlideshow.promoTimeout);

		carousel.hasSlideshow = true;

		this.sizeOfBigCar = 3;

		var currentClass = 'current-flash-link';
		this.currentClass = currentClass;
		this.carsCount = $('#screens a.flash-link').length;
		//var currentNumber = Math.round(Math.random() * (carsCount - 1));
		var currentNumber = 2;
		carousel.currentIndex = currentNumber;
		carousel.current = $('#screens a.flash-link:eq(' + (currentNumber) + ')');
		this.smallCurrent = $('#thumbs a.small-flash-link:eq(' + (currentNumber) + ')');
		this.visible = Math.floor(carousel.visible / 2);

		$('a.flash-link').click(function() {
			if ($(this).hasClass(currentClass)) {
				return false;
			}

			if ($(this).hasClass('small-flash-link')) {
				var index = $('#thumbs a.small-flash-link').index(this);

			} else {
				var index = $('#screens a.flash-link').index(this);
			}

			carousel.trigger(index - carousel.moved - carousel.center + 1, false || $(this).hasClass('small-flash-link'));
			carouselSlideshow.changeCurrent(index);

			return false;
		});

		var flashBlock = $('#slideshow-flash-block');
		var banners = $('span.jsbanner');
		var flashBgs = $('#slideshow-flash-block div.flash-bg');
		var bgsWidth = flashBgs.width() * flashBgs.length;
		var flashBlockWidth = flashBlock.width();

		this.changeGame = function(href, wh, name) {
			if(!$('#submenu li:first a').length) {
				$('#submenu li:first img').wrap('<a href="/games/play.jsp"></a>'); // enable left submenu first item
			}

			this.stopPromoCycle();

			banners.hide(); //from IE6

			if (!wh) {
				var href = href.split('#', 2);
				if (!href[1]) href[1] = '600,385';
				var wh = href[1].split(',', 2);
				href = href[0];
			} else {
				var wh = wh.split(',', 2);
			}

			flashBlock.addClass('slide-loading');

			if (wh[0] > (flashBlockWidth - bgsWidth)) { // if flash width > free space
				flashBgs.css({'width': (flashBlockWidth - wh[0]) / 2 + 'px'});
				flashBlock.css({'float': 'left', 'margin-right': '-' + flashBlockWidth + 'px'});

				flashBlock.animate(
					{'width': wh[0] * 1 + bgsWidth}, 'fast'
				).animate(
					{'height': wh[1]}, 'slow'
				);
			} else {
				flashBlock.animate(
					{'width': wh[0] * 1 + bgsWidth}, 'fast'
				).animate(
					{'height': wh[1]}, 'slow'
				).queue(function(){
					flashBgs.css('width', bgsWidth / 2 + 'px');
					flashBlock.css({'float': 'none', 'margin-right': 'auto'});
					$(this).dequeue();
				});
			}

			flashBlock.queue(function() {
				carouselSlideshow.embedGame(href, 'slideshow-flash', wh[0], wh[1]);

				$(this).removeClass('slide-loading').addClass('slide-loaded');
				banners.show();

				$(this).dequeue();
			});

			trackGame(href, name);
			return false;
		}

		$('#screens a.playnow-link').click(function() {
			carouselSlideshow.changeGame(this.href, null, $(this).attr('disney:game-name'));
			document.getElementById('slideshow-flash-block').scrollIntoView(true);
			window.location.hash = $(this).attr('disney:game-name');
			return false;
		});

		$('#slideshow-link').click(function() {
			var name = this.href.split('#', 2)[1];

			$('#screens a.playnow-link').filter(function() {return $(this).attr('disney:game-name') == name; }).trigger('click');

			$('body').append('<iframe class="statiframe" src="' + this.href + '"></iframe>');

			return false;
		});

		if ('undefined' == typeof dvdSoon || !dvdSoon) {
			$(carousel.current, this.smallCurrent).trigger('click');
		}

		// test games, that not in Pluto yet
		if (window.location.search) {
			this.changeGame(window.location.search.substr(1) + window.location.hash, null, 'testGame');

		} else if (window.location.hash) {
			this.selectThumb(window.location.hash);
			this.loadCurrent();
		}
	},

	changeCurrent: function(index) {
		this.restartPromoCycle();

		with (carousel) {
			current.parent().hide('fast').removeClass('current').show('fast');
			current.removeClass(carouselSlideshow.currentClass);
			current = $('#screens a.flash-link:eq(' + index + ')');
			currentIndex = index;
			current.addClass(carouselSlideshow.currentClass);
			current.parent().addClass('current');
		}

		/* change current5 */
		var smallCurrentClass = 'small-current';
		$('li.current5').removeClass('current5').removeClass('current5first').removeClass('current5last');

		this.smallCurrent.removeClass(smallCurrentClass);
		this.smallCurrent = $('#thumbs a.small-flash-link:eq(' + (index) + ')');
		this.smallCurrent.addClass(smallCurrentClass);

		var limitLt = index + carouselSlideshow.visible;
		var limitGt = index - carouselSlideshow.visible;
		var eqzero = '';

		if (index < carouselSlideshow.visible) {
			limitLt += carouselSlideshow.visible - index - 1;
			limitGt = 0;
			eqzero = ', #thumbs a.small-flash-link:first';

		} else if (index > (carouselSlideshow.carsCount - carouselSlideshow.visible)) {
			limitLt = carouselSlideshow.carsCount;
			limitGt = limitLt - carouselSlideshow.visible * 2;
		}

		$(
			'#thumbs a.small-flash-link:lt(' + (limitLt) + '):gt(' + (limitGt) + ')' + eqzero
		).parent().addClass('current5');

		$('li.current5:first').addClass('current5first');
		$('li.current5:last').addClass('current5last');
	},

	embedGame: function(href, id, w, h) {
		var placeholder = document.getElementById(id);

		if (placeholder) {
			if (href.match(/\.dcr/)) {
				var clsid = '166B1BCA-3F9C-11CF-8075-444553540000';
				var type = 'application/x-director';
				var additionalParams = "<param name=\"swRemote\" value=\"swSaveEnabled='true' swVolume='true' swRestart='true' swPausePlay='true' swFastForward='true' swContextMenu='true'\" /><param name=\"swStretchStyle\" value=\"none\" />";
				var alterText = '<p>Для игры требуется Shockwave-плагин. Чтобы загрузить плагин, нажмите <a href="http://get.adobe.com/shockwave/">сюда</a>.</p>';
				var content = 'src';

			} else if (href.match(/\.swf/)) {
				var clsid = 'D27CDB6E-AE6D-11CF-96B8-444553540000';
				var type = 'application/x-shockwave-flash';
				var additionalParams = '<param name="wmode" value="opaque" />';
				var alterText = '<p>Для игры требуется Flash-плагин. Чтобы загрузить плагин, нажмите <a href="http://get.adobe.com/flashplayer/">сюда</a>.</p>';
				var content = 'movie';

			} else {
				placeholder.innerHTML = '<iframe src="' + href +'" frameborder="0" width="'+ w +'" height="'+ h +'" scrolling="no"></iframe>';

				return;
			}

			var swfObj = [
				'<object classid="clsid:', clsid,
				'" width="', w,
				'" height="', h,
				'"><param name="', content,
				'" value="', href,
				'" />',
				additionalParams,
				'<!--[if !IE]>--><object type="', type,
				'" data="', href,
				'" width="', w,
				'" height="', h,
				'"><!--<![endif]-->',
				alterText,
				'<!--[if !IE]>--></object><!--<![endif]--></object>'
			]

			placeholder.innerHTML = swfObj.join('');
		}
	},

	selectThumb: function(name) {
		$('#thumb-' + name.split('#', 2)[1]).trigger('click');
	},

	loadCurrent: function() {
		$('#screens div.current a.playnow-link').trigger('click');

		return false;
	}
}

$(document).ready(function() {
	if (document.getElementById('slideshow-flash-block')) {
		if ('undefined' != typeof cto) {
			(function() {
				trackGame = function(game, name) {
					cto.ajaxStart();
					cto.pageName = name;
					cto.contentType = 'game_content';
					cto.ugcAction = 'game:play';
					cto.ajaxEnd();
				}
			})();

			$(window).unload(trackGame);
		} else {
			trackGame = function() {
				return null;
			}
		}

		function startSlideshowTimer() {
			try {
				carousel.hasSlideshow = false;
			} catch(e) {}

			try {
				carouselSlideshow.init();
			} catch(e) {}

			return false;
		}

		if(typeof dvdSoon != 'undefined') {
			var flash_block = $('#slideshow-flash-block');
			var html = Array();

			var preloadings_loaded = 0;
			var preloadings_total = 0;

			for(i in dvdSoon) {
				if(typeof dvdSoon[i] == 'object' && dvdSoon[i].image) {
					html.push('<img alt="" />');
					preloadings_total++;
				}
			}
			flash_block.append('<div id="image-preloadings">' + html.join('') + '</div>');

			$('#image-preloadings img').load(function(){
				preloadings_loaded++;

				if(preloadings_loaded == preloadings_total) {
					startSlideshowTimer();
				}
			});

			var preloading_current = 0;
			for(i in dvdSoon) {
				if(typeof dvdSoon[i] == 'object' && dvdSoon[i].image) {
					$('#image-preloadings img').eq(preloading_current).attr('src', dvdSoon[i].image);
					preloading_current++;
				}
			}
		}
	}
});
