$(function() {
	$("body.root").each(function() {
		var query = window.location.search;

		if (query.length) {
			if (query.match(/unsubscribe/)) {
				$(this).addClass("unsubscribe");
			}

			if (query.match(/activate/)) {
				var result = "";

				var params = query.split('&');
				var type = "";
				
				for(i=0; i< params.length; i++) {
					var tmp = params[i].split("=");
					
					if (tmp.length > 1) {
						if (tmp[0] == "type") {
							switch(tmp[1]) {
								case 'news':
									type = "ежемесячные новости";
									break;
								case 'press':
									type = "пресс-релизы";
									break;
								case 'all':
									type = "пресс-релизы и ежемесячные новости";
									break;
							}

						} else if (tmp[0] == "error") {
							switch(tmp[1]) {
								case 'already':
									result = "Подписка уже активна";
									break;
								case 'id':
									result = "Не корректный id";
									break;
		
								default:
									result = "Ошибка активации, попробуйте позже";
							}
						
						}
					}
				}
				
				if (result == "") {
					result = "Вы успешно подписались на " + type + " компании Disney.";
				}

				$("form#subscribtion input, form#subscribtion h4, form#subscribtion label, form#subscribtion p").hide();
				$("p.result").html(result);
				$("p.result").show();
			}

			var topscroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
			$("div.subscribtion").css("top", topscroll + 340);
			$("div.subscribtion").show();
			$("body").addClass("veiled");
		}
	})
})
$(function() {
	$("body.root #flash").each(function() {
		swfobject.embedSWF(
			'/images/corp.swf', 'flash', '735', '170', '9.0.0"', 'false',{xmlpath:'/topmenuXML.jsp'},{wmode:"opaque"}
		);
	})
	$("#flash2").each(function() {
		swfobject.embedSWF(
			'/images/corpinner.swf', 'flash2', '735', '170', '9.0.0"', 'false',{xmlpath:'/topmenuXML.jsp'},{wmode:"opaque"}
		);
	})
})
$(function() {
	$('dl.media dt:first, dl.media dd:first').addClass("selected");
	$('dl.media dt').click(function(){
		$(this).siblings().removeClass('selected').end().next('dd').andSelf().addClass('selected');
	})
})
$(function() {
	//scrollpane parts
	$('.scroll-pane').each(function() {
		var scrollPane = $(this);
		var scrollContent = scrollPane.children('.scroll-content');

		//build slider
		var scrollbar = scrollPane.find(".scroll-bar").slider({
			slide:function(e, ui){
				if( scrollContent.width() > scrollPane.width() ){ scrollContent.css('margin-left', Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + 'px'); }
				else { scrollContent.css('margin-left', 0); }
			}
		});

		//append icon to handle
		var handleHelper = scrollbar.find('.ui-slider-handle')
		.mousedown(function(){
			scrollbar.width( handleHelper.width() );
		})
		.mouseup(function(){
			scrollbar.width( '100%' );
		})
		.append('<span class="ui-icon ui-icon-grip-dotted-vertical"></span><span class="cr"></span>')
		.wrap('<div class="ui-handle-helper-parent"></div>').parent();

		//change overflow to hidden now that slider handles the scrolling
		scrollPane.css('overflow','hidden');

		//size scrollbar and handle proportionally to scroll distance
		function sizeScrollbar(){
			var remainder = scrollContent.width() - scrollPane.width();
			var proportion = remainder / scrollContent.width();
			var handleSize = scrollPane.width() - (proportion * scrollPane.width());
			scrollbar.find('.ui-slider-handle').css({
				width: handleSize,
				'margin-left': -handleSize/2
			});
			handleHelper.width('').width( scrollbar.width() - handleSize);
		}

		//reset slider value based on scroll content position
		function resetValue(){
			var remainder = scrollPane.width() - scrollContent.width();
			var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
			var percentage = Math.round(leftVal / remainder * 100);
			scrollbar.slider("value", percentage);
		}
		//if the slider is 100% and window gets larger, reveal content
		function reflowContent(){
				var showing = scrollContent.width() + parseInt( scrollContent.css('margin-left') );
				var gap = scrollPane.width() - showing;
				if(gap > 0){
					scrollContent.css('margin-left', parseInt( scrollContent.css('margin-left') ) + gap);
				}
		}

		//change handle position on window resize
		$(window)
		.resize(function(){
				resetValue();
				sizeScrollbar();
				reflowContent();
		});
		//init scrollbar size
		setTimeout(sizeScrollbar,10);//safari wants a timeout
	})
});
$(function() {
	$('form#subscribtion input[name=email], form#subscribtion input[name=repeat_email], form#anketa input.text'
	).each(function() {
		this.defVal = this.value;
	}).focus(function() {
		if (this.value == this.defVal) this.value = '';
		$(this).parents().eq(0).addClass('search-keyword-active');
	}).blur(function() {
		if (this.value == '') this.value = this.defVal;
		$(this).parents().eq(0).removeClass('search-keyword-active');
	});
});
$(function() {
	$('form#subscribtion').submit(function(){
		var email          = $('input[name=email]', this).val();
		var newslettersUrl = $('input[name=url]', this).val() + "?callback=?";
		var data = $(this).serialize();

		$.ajax({
			url: newslettersUrl,
			data: data,

			success: function(data, textStatus, XMLHttpRequest) {
				$("form#subscribtion input").show();
				$("p.result").removeClass("error");

				var result = "";
				if (data.status == "error") {

					if (data.error == "noEmail") {
						result = "Введите правильный e-mail";
						$("p.result").addClass("error").show();

					} if (data.error == "noRepeat") {
						result = "e-mail и подтверждение не совпадают";
						$("p.result").addClass("error").show();

					} if (data.error == "noSubscribe") {
						result = "Выберите тип подписки";
						$("p.result").addClass("error").show();

					} if (data.error == "dbError") {
						result = data.errorMessage;
						$("p.result").addClass("error").show();
					}

				} else {
					var ok_text    = "<p>Вы подписались на type компании Disney. На ваш электронный адрес выслано письмо активации. Подтвердите свою подписку, нажав на ссылку в письме.</p>";
					var error_text = "<p>Email " + email + " уже подписан на type компании Disney.</p>";

					if (data.status_news == "ok" && data.status_press == "ok") {
						result = ok_text.replace("type", "пресс-релизы и ежемесячные новости");
						
					} else if (data.status_news == "error" && data.status_press == "error") {
						result = error_text.replace("type", "пресс-релизы и ежемесячные новости");
						
					} else {
						
						if (data.status_news == "error") {
							result += error_text.replace("type", "ежемесячные новости");
						}
						if (data.status_press == "error") {
							result += error_text.replace("type", "пресс-релизы");
						}
						if (data.status_news == "ok") {
							result += ok_text.replace("type", "ежемесячные новости");
						}
						if (data.status_press == "ok") {
							result += ok_text.replace("type", "пресс-релизы");
						}
					}

					$("form#subscribtion input, form#subscribtion h4, form#subscribtion label, form#subscribtion p").hide();
					$("p.result").show();
				}

				$("div.subscribtion p.result").html(result);
			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$("form#subscribtion input").show();

				var result = "Какая то ошибка на сервере";
				$("p.result").addClass("error").show();

				$("div.release p.result").html(result);
			},

			dataType: 'json',
			type: 'GET'
		});

		return false;
	});

	$('form#unsubscribtion').submit(function(){
		var email          = $('input[name=email]', this).val();
		var newslettersUrl = $('input[name=url]', this).val() + "?callback=?";
		var type           = $('input[name=type]', this).val();

		$.ajax({
			url: newslettersUrl,
			data: {email: email, type: type},

			success: function(data, textStatus, XMLHttpRequest) {
				$("form#unsubscribtion input").show();
				$("p.result").removeClass("error");

				var result = "";
				if (data.status == "error") {

					if (data.error == "noEmail") {
						result = "Введите корректный e-mail";
						$("p.result").addClass("error").show();

					} if (data.error == "notExists") {
						result = "E-mail " + email + " не  был подписан ранее";
						$("p.result").addClass("error").show();

					} if (data.error == "noType") {
						result = "Тип подписки не определен";
						$("p.result").addClass("error").show();

					} if (data.error == "dbError") {
						result = data.errorMessage;
						$("p.result").addClass("error").show();
					}

				} else {
					var text = "ежемесячных новостей";
					if (type == "press") {
						text = "пресс-релизов";
					}
					result = "Ваш e-mail успешно отписан от " + text + " компании Disney.";

					$("form#unsubscribtion input, form#unsubscribtion p").hide();
					$("p.result").show();
				}

				$("div.subscribtion p.result").html(result);
			},

			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$("form#unsubscribtion input").show();

				var result = "Какая то ошибка на сервере";
				$("p.result").addClass("error").show();

				$("div.release p.result").html(result);
			},

			dataType: 'json',
			type: 'GET'
		});

		return false;
	});
	
	$('form#anketa').submit(function(){
		var name  = $.trim(this.contact_name.value);
		var email = $.trim(this.email.value);
		var phone = $.trim(this.phone.value);
		
		var epattern = new RegExp("^([a-z0-9_-]+)(\\.[a-z0-9_-]+)*@((([a-z0-9-]+\\.)+(com|net|org|mil|edu|gov|arpa|info|biz|inc|name|mobi|[a-z]{2}))|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))$", "i");

		if (name == "" || name == "Контактное лицо" || email == "" || phone == "" || phone == "Телефон") {
			$("p.result").addClass("error");
			$("div.anketa p.result").html("Заполните контактную информацию");
				
		} else if (!email.match(epattern)) {
			$("p.result").addClass("error");
			$("div.anketa p.result").html("Введите правильный e-mail");
		} else {
			if (this.city.value == "Город") {
				this.city.value = "";
			}
		
			if (this.other_product_category.value == "Другое") {
				this.other_product_category.value = "";
			}
			
			if (this.other_brand.value == "Другое") {
				this.other_brand.value = "";
			}

			var saveUrl = this.url.value + "?callback=?";
			var data = $(this).serialize();

			$.ajax({
				url: saveUrl,
				data: data,
	
				success: function(data, textStatus, XMLHttpRequest) {
					$("form#anketa input").show();
					$("p.result").removeClass("error");
					
					var result = "";
					if (data.status == "ok") {
						result = "Ваша заявка успешно отправлена";
						$("form#anketa input, form#anketa h2, form#anketa h3, form#anketa label, form#anketa select, form#anketa textarea, form#anketa a, form#anketa ul, form#anketa p:not(.result)").hide();
					} else {
						result = "Ошибка отправки, попробуйте позже";
						$("p.result").addClass("error");
					}
					var topscroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
					$("div.anketa").css("top", topscroll + 100);
					$("div.anketa p.result").html(result).addClass("success");
				},
	
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					$("form#anketa input").show();
	
					$("p.result").addClass("error").show();
					$("div.anketa p.result").html("Какая то ошибка на сервере");
				},
	
				dataType: 'json',
				type: 'GET'
			});
		}
		$("p.result").show();

		return false;
	});
	
	$("form#anketa select[name=country]").change(function() {
		if ($(this).val() == "") {
			$("div.anketa input#other_country").show(); 
		} else {
			$("div.anketa input#other_country").attr("value", "");
			$("div.anketa input#other_country").hide(); 
		}
	});
});
$(function() {
	$("#rootnews").each(function(){
		var $list = $(".news-shifting", this);
		var $items = $list.find(".news-item");
		var listHeight = $list.height();
		var listTop = parseInt($list.css("top")) || 0;
		var listScrollStep = $(".news-container", this).height();
		var listItemMarginB = parseInt($list.find(".news-item").css("marginBottom"));

		$list.append("<div class=\"news-chapter\"></div>");
		var $currentSheat = $list.find(".news-chapter").last();
		var sheatHeight = 0;

		$items.each(function(i){
			sheatHeight += $(this).height() + listItemMarginB;
			if(sheatHeight > listScrollStep) {
				sheatHeight = $(this).height() + listItemMarginB;
				$list.append("<div class=\"news-chapter\"></div>");
				$currentSheat = $list.find(".news-chapter").last();
			}
			$(this).appendTo($currentSheat);
		});

		$(".nav").click(function(e){
			e.preventDefault();

			var scroll = listScrollStep;
			if($(this).hasClass("nav-d")) {
				scroll*=-1;
			}
			listTop += scroll;
			if(-listTop < 0 || -listTop > listHeight) {
				listTop -= scroll;
			}
			$list.stop().animate({"top": listTop}, 750);
		});
	});
});
$(function() {
	$("body.archive ul.archive-list span").click(function() {
		$("body.archive ul.archive-list li").removeClass("opened");
		$(this).parents("li").addClass("opened");

		$("body.archive ul.archive-list li.opened ul li:first").trigger("click");
	})
});
$(function() {
	$("body.archive ul.archive-list ul li, body.archiveNews ul.archive-list li").click(function() {
		var monthOfYear = this.id;

		$("body.archive div.release ul, body.archive ul.archive-list ul li").removeClass("opened");
		$("body.archive div.release ul." + monthOfYear).addClass("opened");

		var month = $(this).html().toLowerCase();
		var year  = $("body.archive ul.archive-list li.opened span").html();
		if ($("body").hasClass("archiveNews")) {
			$("body.archive div.release h3 span").html(year);
		} else {
			$("body.archive div.release h3 span").html(month + " " + year);
		}

		$(this).addClass("opened");
	})

	$("body.archive ul.archive-list ul li:first, body.archiveNews ul.archive-list li:first").trigger("click");
})

$(function() {
	$("#content .videopr").click(function() {
		var videoPath = '/playerXML.jsp?from=' + $(this).attr("href") + '&id=' + $(this).attr("id");
		$("body").addClass("veiled");
		$(".videoframe").show();
		var topscroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
		$(".videoframe").css("top", topscroll + 100);
		$("#player").each(function() {
			swfobject.embedSWF(
				'/images/player.swf?_xmlpath='+escape(videoPath), 'player', '375', '345', '9.0.0"', '','',''
			);
		})
		return false;
	})

	$("#close").click(function() {
		$("body").removeClass("veiled");
		$(".videoframe").hide();
		$(".videowrapper div").empty().html("<div id='player'></div>");
	})
	
	$("a.anketa-link").click(function() {
		var topscroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
		$("div.anketa").css("top", topscroll + 100);
		$("body").addClass("veiled");
		$("div.anketa").show();
		return false;
	})
	$("div.anketa .close").click(function() {
		$("body").removeClass("veiled");
		$("div.anketa").hide();
		
		$("form#anketa input[name=city]").attr("value", "Город");
		$("form#anketa input[name=other_product_category]").attr("value", "Другое");
		$("form#anketa input[name=other_brand]").attr("value", "Другое");
		$("form#anketa input, form#anketa h2, form#anketa h3, form#anketa label, form#anketa select, form#anketa textarea, form#anketa a, form#anketa ul, form#anketa p:not(.result)").show();
		$("div.anketa input#other_country").hide();
		$("div.anketa input#other_country").attr("value", "");
		
		if ($("form#anketa select[name=country]").val() == "") {
			$("form#anketa select[name=country]").val("Россия");
		}
		
		$("p.result").hide().removeClass("success");
	})
})
$(function() {
	$("a.subscr").click(function() {
		$("form#subscribtion input").removeAttr("checked");
		var topscroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
		//$("div.subscribtion").css("top", topscroll + 150);
		$("div.subscribtion").show();
		$("body").addClass("veiled");
		if ($(this).hasClass("press")) {
			$("form#subscribtion input#press").attr("checked", "checked");
		} else if ($(this).hasClass("news")) {
			$("form#subscribtion input#news").attr("checked", "checked");
		}
		return false;
	})

	$("div.subscribtion a.close").click(function() {
		$("body").removeClass("veiled");
		$("body").removeClass("unsubscribe");
		$("div.subscribtion").hide();
		
		$("form#subscribtion input, form#subscribtion h4, form#subscribtion label, form#subscribtion p").show();
		$("p.result").hide();
		return false;
	})
});

$(function() {
	$('form#anketa textarea').bind('keydown keypress keyup',function() {
		if (this.value.length > 200) {
			this.value = this.value.substring(0, 200);
		}
	});
});

/** vacancies scripts **/
var VacanciesPopup = function(containerName) {
	this.container = new Object();
	this.title = "";
	this.description = "";
	this.requirements = "";
	this.date = "";
	this.id = "";
	
	/** constructor **/
	this.init = function(containerName) {
		this.container = $(containerName);
		this._bindEvents();
	}
	
	/** show popup **/
	this.show = function() {
		this.container.find("h3").html(this.title);
		this.container.find("p.description").html(this.description);
		this.container.find("p.date").html(this.date);
		this.container.find("p.requirements").html(this.requirements);

        /*var frame = this.container.find("iframe");
        frame.attr("src", frame.attr("rel") + "?id=" + this.id + "&name=" + this.title);
		*/
		this.container.find("iframe").remove();
		this.container.fadeIn();
		window.location.hash = "show";
		
		
	}
	
	/** hide popup **/
	this.hide = function() {
		this.container.fadeOut();
		this.container.find("iframe").attr("src","#");
		
		
	}
	
	/** bind popup event to init popup **/
	this._bindEvents = function() {
		var self = this;
		
		/** close popup **/
		this.container.find(".close").click(function() {
			self.hide();
		});
	}
	
	this.init(containerName);
}
$(function() {
	if(vacanciesPopup == undefined) {
		var vacanciesPopup = new VacanciesPopup("#vacancies-popup");
	}
	
	$("#vacancies-list li span").click(function() {
		var container = $(this).closest("li");
		
		vacanciesPopup.id = container.attr("id");
		vacanciesPopup.requirements = container.attr("requirements");
		vacanciesPopup.title = container.find("h3").html();
		vacanciesPopup.description = container.find("p.description").html();
		vacanciesPopup.date = container.find("p.date").html();
		
		vacanciesPopup.show();
	});
});

