var carouselSlideshow = {
	promoTimeout: 5,

	promoTriggered: false,

	promoInitialized: false,

	cycling: false,

	startPromoCycle: function(t) {
		if (this.promoInitialized && !this.cycling) {
			this.cycling = true;
			this.changePromo();
		}
	},

	changePromo: function() {
		this.promoCycle = setTimeout(function() {
			var $buttons = $('#slideshow-buttons a');
			var $current = $('#slideshow-buttons a.slideshow-current');
			var index = $buttons.index($current) + 1;
			if (index >= $buttons.size()) {
				index = 0;
			}
			$($buttons.get(index)).click();
			carouselSlideshow.changePromo();
		}, this.promoTimeout * 1000);
	},

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

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

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

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

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

			return false;
		}
		
		if (window.dvdSoon) {
			var preloadings_loaded = 0;
			var preloadings_total = [];
			//in case images load more than 3 minutes
			var justInCase = setTimeout(startSlideshowTimer, 180000);
			for (var i in dvdSoon) {
				if (typeof dvdSoon[i] == 'object' && dvdSoon[i].image) {
					var img = new Image();
					img.onload = function() {
						preloadings_loaded++;
						if (preloadings_loaded == preloadings_total.length) {
							clearTimeout(justInCase);
							startSlideshowTimer();
						}
					};
					preloadings_total.push({
						imgObj: img,
						url: dvdSoon[i].image
					});
				}
			};

			for (i = 0; i < preloadings_total.length; i++) {
				preloadings_total[i].imgObj.src = preloadings_total[i].url;
			};
		}
	},

	init: function() {
		if (!this.promoInitialized) {
			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');
				
				var play_banner = document.getElementById('play_banner');
				play_banner.src = play_banner.src; 
				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) {
				var testUrl = window.location.search.substr(1).replace(/^\w+:\/\/[^/]+/, '');
				this.changeGame(testUrl + 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/" target="_blank">сюда</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/" target="_blank">сюда</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;
			}
		}
	}
});

