$(
	function(){

		swfobject.embedSWF("/f/1/player.swf","player","315","24","9.0.0","", {audio:'/f/1/pesenka.mp3', css:'/f/1/audio.css', skin:'/f/1/default.swf'}, {allowFullscreen: "false",allowScriptAccess : "always"});
		
		function playVideo( filename, callback ){
			var path = filename.split('/');
			path.pop();
			path = path.join('/') + '/';
			swfobject.embedSWF("/f/1/video_player.swf","video_player","600","453","9.0.0","", {cover:filename.replace('.flv','.jpg'), video:filename, css: '/f/1/video_default.css', skin: '/f/1/video_default.swf'},{allowFullscreen: "true",allowScriptAccess:"always", wmode:"transparent"});
		}

		/*
		 * Класс анимации барби.
		 * @param {JDOMElement} container Элемент в котором будет барби
		 * @param {JDOMElement} barbi Картинка с барби
		 */
		function Barbi( container, barbi ){
			function runEvent(){
				if( eventBuffer.length < 1 ){
					isRunning = 0;
					return;
				}
				isRunning = 1;
				var event = eventBuffer.shift();
				if( event[0] != barbiSide ){
					$t(barbi).tween({
						left:(event[0] ? '+' : '-')+'=40',
						onComplete:function(){
							barbi.toggleClass('flip');	
							barbiSide = !barbiSide;
							
							$t(barbi).tween({
								left:event[1]+'px',
								onComplete:runEvent
							})
						},
						transition:'linear',
						time:0.1
					})
				}
				else
					$t(barbi).tween({
						left:event[1]+'px',
						onComplete:runEvent
					})
			}

			var years = container.find('.year > span'), eventBuffer = [], yearIndex = 0, barbiSide = 0, isRunning = 0;
			years.addClass('pseudo_link').click(
				function(){
					if( !$(this).hasClass('pseudo_link') )
						return false;

					years.addClass('pseudo_link').parent().addClass('closed');
					$(this).removeClass('pseudo_link').parent().removeClass('closed');

					var index = years.index(this);
					eventBuffer.push([yearIndex > index, index * 134]);
					yearIndex = index;
					if( !isRunning )
						runEvent();

					barbi.find('span').hide();

					return false;
				}
			).parent().addClass('closed');

			barbi.find('span').addClass('pseudo_link').click(
				function(){
					$(years[years.length - 1]).click();
				}
			);
		}

		/*
		 * Класс для инициализации производственных секретов
		 * @param {JDOMElement} element Элемент в котором содержатсяпроизводственные секреты
		 */
		function ProductSecrets( element ){
			var content = element.find('.content').css('height', 1),
			isLocked = 0, show = element.find('.show:first'), hide = element.find('.hide:first'), isMoving = 0, saveHeight, moveY, isOpened = 0;

			element.find('>i.sun').mousedown(
				function( event ){
					saveHeight = content[0].clientHeight;
					isMoving = 1;
					moveY = event.clientY;
				}
			).mousemove(
				function( event ){
					if( !isMoving )
						return;

					content.css('height', saveHeight + event.clientY - moveY > 1 ? saveHeight + event.clientY - moveY : 1);

					if( event.stopPropagation )
						event.stopPropagation();
				}
			).mouseup(
				function(){
					isMoving = 0;
					if( isOpened )
						hide.click();
					else
						show.click();
				}
			);

			show.addClass('pseudo_link').click(
				function(){
					if( isLocked )
						return false;
					isLocked = 1;

					show.parent().css('visibility', 'hidden');
					
					var currentHeight = content[0].clientHeight;

					content.css('height', 'auto');
					var height = content[0].clientHeight;
					content.css('height', currentHeight);
					$t(content).tween({
						height:height,
						time:2,
						onComplete:function(){
							isLocked = 0;
							isOpened = 1;
							content.css('height', 'auto');
						}
					});	
				}
			);

			hide.addClass('pseudo_link').click(
				function(){
					if( isLocked )
						return false;
					isLocked = 1;

					show.parent().css('visibility', 'visible');
                                        
					content.css('height', content[0].clientHeight);
					$t(content).tween({
						height:1,
						time:2,
						onComplete:function(){
							isLocked = 0;
							isOpened = 0;
						}
					})
				}
			);
		}

		/*
		 * Класс для инициализации раскрывающихся блоков
		 * @param {DOMElement} element Элемент который является раскрывающимя блоком
		 */
		function SlideBlock( element ){
			var content = $(element).find('> .content').css('height', '1');
			$(element).find('>.round-sides .pseudo_link').click(
				function(){
					if( isLocked )
						return false;
					isLocked = 1;

					var parents = $(this).parents('.content');

					var isOpened = false;

					var closedHeight = [];

					if( openedElements.length ){
						for(i = 0; i < openedElements.length; i++){
							if( parents.index(openedElements[i]) == -1 ){
								closedHeight[i] = openedElements[i].clientHeight;
								$(openedElements[i]).css('height', closedHeight[i]);
								$(openedElements[i]).css('overflow', 'hidden').trigger('changed');
							}
							else
								closedHeight[i] = 0;
							
							if( content.index(openedElements[i]) != -1 )
								isOpened = true;
						}
					}
					content.css('height', 'auto');
					var height = content[0].clientHeight;
					if( !isOpened )
						content.css('height', '1').css('overflow', 'hidden');

					jTweener.addPercent({
						everyFrame: function(iPercent){
							if( !isOpened )
								content.css('height', height * iPercent > 1 ? height * iPercent : 1);
								
							if( openedElements.length ){
								for(i = 0; i < openedElements.length; i++){
									if( closedHeight[i] ){
										var h = closedHeight[i] * (1-iPercent);
										$(openedElements[i]).css('height',  h < 1 ? 1 : h);
										
									}
								}
							}
						},
						onComplete: function(){
							isLocked = 0;								
							var newOpenedElements = [];
							for(i = 0; i < openedElements.length; i++){
								if( closedHeight[i] == 0 )
									newOpenedElements.push(openedElements[i]);
							}
							openedElements = newOpenedElements;

							if( !isOpened ){
								openedElements.push(content[0]);
								
								content.removeClass('closed').css('height', 'auto').css('overflow', 'visible').trigger('changed');
							}
						},
						transition:'linear',
						time: 0.2
					});
				}
			)
		}

		/*
		 * Функция навешивает обработчики на элементы внутри табов, 
		 * загружаемые через Ajax запросы
		 * @param {Bool} [isNoSlideBlocks] Не навешивать обработчики на раскрывающиеся блоки
		 */
		function refresh( isNoSlideBlocks ){
			//Инициализируем барби
			if( $('#barbi').length ){
				Barbi( $('#skating-rink'), $('#barbi') );
			}		

			//Инициализируем шарик
			$('#balloon').find('span').addClass('pseudo_link').click(
				function(){
					$(this).parent().hide();
					var balloon = $('#balloon');
					var offset = balloon.offset();
					offset.top += parseInt(balloon.css('top')) / 2;
					$('#layout').append(balloon);
					balloon.css({top:offset.top,left:offset.left});
					
					$t(balloon).tween({
						top:-10000,
						time:20,
						onComplete:function(){
							balloon.hide();
						},
						transition:'linear'
					})
					
				}
			);

			$('#links a').addClass('pseudo_link').each(
				function( index ){
					$(this).click(
						function(){
							var another = $(this).parents('.another:first');
							if( isLocked )
								return false;

							var isSelected = 0;
							$('#tabs > ul:first > li').each(
								function( i ){
									if( $(this).hasClass('selected') ){
										isSelected = 1;
										return;
									}	
									if( !isSelected && index == i || isSelected && index == i - 1 ){
										var tab = $('#tab');
										isLocked = 1;

                                                                                var loader = $('#loader').clone().removeClass('hidden');
										another.addClass('selected').append(loader);
										var that = $(this);
										var image = that.parents('ul:first').find('>li').filter('.selected').find('img');
										
										image.parents('li:first').removeClass('selected');
										image.remove();
										var href = that.find('a').attr('href');
										href = (href ? href : document.location.toString());
										$.get(
											href,
											'text', 
											function( data ){
												that.append(image).addClass('selected');
												tab.html(data.split("<!-- ajax -->")[1]);
							        				loader.addClass('hidden');
												isLocked = 0;
							                                        refresh();
							                                        setTimeout(
													function(){
														document.location = '#go-' + that.find('a').attr('anchor');
														document.location = '#' + that.find('a').attr('anchor');
													}, 200
												)
											}
										);
									}
								}
							);
							return false;
						}
					)
				}
			);

			var isOpened = 0;
			$('#hourglass_open').bind('changed',
				function(){
					setTimeout(
						function(){
							isOpened = !isOpened;
							if( isOpened )
								$('#hourglass').css('height', $('#hourglass_info')[0].clientHeight);
							else
								$('#hourglass').css('height', '');
						}
					,200)
				}
			);

			if( $('#morfing').length ){
				var morphing = new Morphing($('#morfing'), 29);
				$('#morfing_link>span').addClass('pseudo_link').mouseover(
					function(){
						morphing.morphIn();
					}
				).mouseout(
					function(){
						morphing.morphOut();
					}
				);
			}

			if( isNoSlideBlocks )
				return;

			$('#tab').find('.info').each(
				function(){
					SlideBlock(this);
				}
			);

			$('#tab span.pseudo_link').hover(function(){ if($(this).hasClass('pseudo_link'))$(this).addClass('hover') },function(){ $(this).removeClass('hover') });
		}

		var isLocked = 0, tabActive = (document.location.toString()).split('#');
		$('#tabs > ul:first > li').click(
			function(){
				var that = $(this);
				if( that.hasClass('selected') || isLocked )
					return false;

				var tab = $('#tab');
				isLocked = 1;
                                var loader = $('#loader').removeClass('hidden');
				that.append(loader);
				var image = that.parents('ul:first').find('>li').filter('.selected').find('img');
				image.parents('li:first').removeClass('selected');
				that.append(image).addClass('selected');
				var href = that.find('a').attr('href');
				href = (href ? href : document.location.toString());
				$.get(
					href,
					'text', 
					function( data ){
						document.location = '#' + that.find('a').attr('anchor');
							
						tab.html(data.split("<!-- ajax -->")[1]);
					        loader.addClass('hidden');
                                		isLocked = 0;
						refresh();
					}
				);

				return false;
			}
		).each(
			function(){
				var that = $(this);
				that.find('a').addClass('pseudo_link');
				that.find('b').addClass('pseudo_link');

				if( tabActive[1] && tabActive[1] == that.find('a').attr('anchor') ){
					that.click();
				}
			}
		);

		refresh( 1 );

		var isLocked = 0, openedElements = [], i;

		$('.info').each(
			function(){
				SlideBlock(this)
			}
		);
		$('#person_submit').click(
			function(){
                                if( /[^\s]/.test($('#person_name').val()) ){
					cookie('name', $('#person_name').val());
					$('.person_name').text($('#person_name').val());
					$('#volshebnica_first .with-name').removeClass('hidden');
					$('#volshebnica_first .without-name').addClass('hidden');
					if( !cookieName )
						$('#volshebnica_first .pseudo_link').click();
					cookieName = false;
				}
			}
		);


		var cookieName;
		if( cookieName = cookie('name') ){
			$('#person_name').val(cookieName);
			$('#person_submit').click();
		}

		$('#person_name').keypress(
			function( e ){
				if( e.which == 13 ){
					$('#person_submit').click();
				}
				return true;
			}
		).keyup(
			function(){
				if( /[^\s]/.test(this.value) )
					$('#person_submit')[0].disabled = false;
				else
					$('#person_submit')[0].disabled = true;
			}
		).keyup();
		
		var seasonIndex = 0;
		$('#season').addClass('pseudo_link').click(
			function(){
				seasonIndex++;
				seasonIndex %= 4;
				$($(this).find('span').addClass('hidden')[seasonIndex]).removeClass('hidden');
				$($('#holiday > span').addClass('hidden')[seasonIndex]).removeClass('hidden');
			}
		);

		$('#flowers > img').hide();
		$('#show_flower').addClass('pseudo_link').click(
			function(){
				if( !$(this).hasClass('pseudo_link') )
					return false;

				$(this).removeClass('pseudo_link');

				$('#flowers > img').each(
					function( index ){
						var flower = $(this).show();
						var width = Math.round(flower[0].clientWidth / 2);
						var height = Math.round(flower[0].clientHeight / 2);
						flower.css({width:1,height:1,marginTop:height+'px',marginLeft:width+'px'});
						
						$t(flower).tween({
							width:width * 2,
							height:height * 2,
							marginTop:0,
							marginLeft:0,
							time:0.2,
							delay:0.2*index,
							transition:"easeOutBack"
						})
					}
				)
			}
		);

		var videos = $('#cinema_list a');
		videos.click(
			function(){
				playVideo(this.href);
				videos.removeClass('selected');
			        $('#cinema h2').html($(this).addClass('selected').html());
				return false;
			}
		);
		$(videos[0]).click();

		videos.addClass('pseudo_link');

		ProductSecrets($('#product_secret'));

		var cloudIndex = 1;
		$('#clouds_change > span').addClass('pseudo_link').click(
			function(){
				var nextIndex = (cloudIndex + 1)%20;
				if( nextIndex < 1)
					nextIndex = 1;

				var clouds = $('#clouds')[0], href;
				if( clouds.savesrc ){
					clouds.src = clouds.savesrc.replace(cloudIndex + '.', nextIndex + '.');
					fixPNG(clouds);
				}
				else{
					clouds.src = clouds.src.replace(cloudIndex + '.', nextIndex + '.');
				}
				cloudIndex = nextIndex;
			}
		);

		$('#clouds').click(
			function(){
				$('#clouds_change > span').click();
			}
		);

		var videoIndex = 0, videoList = $('#cinema_list li');
		$('#video_change span').addClass('pseudo_link').click(
			function(){
				if( videoIndex + 5 < videoList.length - 1 ){
					videoIndex += 5;
				}
				else
					videoIndex = 0;
				videoList.addClass('hidden');
				$(videoList[0]).removeClass('hidden');
				for(var i = videoIndex; i < videoIndex + 5; i++ ){
					$(videoList[i + 1]).removeClass('hidden');
				}
			}
		);

		$(window).load(
			function(){
				$('span.pseudo_link').hover(function(){ if($(this).hasClass('pseudo_link'))$(this).addClass('hover') },function(){ $(this).removeClass('hover') });
			}
		);

		function cookie(name, value, options) {

			if ('undefined' != typeof value) {
				options = options || {};

				if (null === value) {
					value = '';
					options.expires = -1;
				}

				var expires = '';

				if (options.expires && ('number' == typeof options.expires || options.expires.toUTCString)) {
					var date;

					if ('number' == typeof options.expires) {
						date = new Date();
						date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
					} else {
						date = options.expires;
					}

					expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
				}

				// CAUTION: Needed to parenthesize options.path and options.domain
				// in the following expressions, otherwise they evaluate to undefined
				// in the packed version for some reason...
				var path = options.path ? '; path=' + options.path : '';
				var domain = options.domain ? '; domain=' + options.domain : '';
				var secure = options.secure ? '; secure' : '';
				document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');

				return this;
			}

			var cookieValue = null;

			if (document.cookie && '' != document.cookie) {
				var cookies = document.cookie.split(';');

				for (var i = 0; i < cookies.length; i++) {
					var cookie = jQuery.trim(cookies[i]);

					// Does this cookie string begin with the name we want?
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));

						break;
					}
				}
			}

			return cookieValue;
		};

	}
)