// JavaScript Document

$(document).ready(function()
{
	if($("#alert_msg").length) {
		alert($("#alert_msg").text());
	};

	/* Popup Data Object */
	jQuery.popupWindow = function(obj, options)
	{
		var optionsDef = {
			height: 'auto',
			template: 	'<div class="forOverlay">'+
							'<div class="overlay"></div>'+
							'<div class="popupEnterDiller">'+
								'<div class="close"><span>'+$('#form36').text()+'</span></div>'+
								'<div class="forPopupData">'+
									'{replace}'+
								'</div>'+
							'</div>'+
						'</div>',
			replaceContainer: 'forPopupData',
			hideClasses: '.overlay, .close',
			hideKey: 27,
			width: '760px'}

		options = $.extend(optionsDef, options);

		var newobj = $(options.template);
		obj = obj.clone(true);

		newobj.find('.'+options.replaceContainer).empty().append(obj.css('display','block'));

		newobj.find('.popupEnterDiller').css('height',options.height);
		newobj.find('.popupEnterDiller').css('width',options.width);

		var windowHeight = $(window).height();
		newobj.find('.popupContent').css('max-height',windowHeight-200);
		//alert(maxHeight);

		newobj.find(options.hideClasses).bind('click', {obj:newobj}, function(event){
			event.data.obj.hide().remove();
		});

		newobj.bind('keyup', {obj:newobj}, function(event){
			if(event.which == 27){
			event.data.obj.hide().remove();};
		});

		$('html body').append(newobj.css('display','block'));

		var heightPopup = newobj.find('.popupEnterDiller').innerHeight();
		var widthPopup = newobj.find('.popupEnterDiller').innerWidth();
		if(heightPopup>windowHeight)
		{
			newobj.find('.popupEnterDiller').css('margin-top','20px').css('margin-left','-'+widthPopup/2+'px');
			newobj.find('.popupEnterDiller').css('top','0');
		}
		else
		{
			newobj.find('.popupEnterDiller').css('margin-top','-'+heightPopup/2+'px').css('margin-left','-'+widthPopup/2+'px');
		}
		newobj.find("input:text").eq(0).focus().addClass("focus");
		$("html,body").scrollTop($("body").offset().top);
		newobj.find(".popupMenu").each(function()
		{
			HeightForRows($(this),$(this).find(" > ul > li"), $(this).find(" > ul > li").innerWidth());
		});

	};
	jQuery.popupClose = function(options)
	{
		var optionsDef = {
			classesClose: '.forOverlay'}

		options = $.extend(optionsDef, options);

		$(options.classesClose).remove();

	};

	$("body").removeClass("noscript");

	/*jQuery(".cusel").each(
	function()
	{
		var w = parseInt(jQuery(this).width()),
			scrollPanel = jQuery(this).find(".cusel-scroll-pane");
		if(w>=scrollPanel.width())
		{
			jQuery(this).find(".jScrollPaneContainer").width(w);
			scrollPanel.width(w);
		}
	});
	var params = {
		changedEl: ".lineForm select",
		visRows: 5,
		scrollArrows: true
	}
	cuSel(params);*/

	/* Popups */
	if($(".p1").length)
	{
		$(".p1").click(function()
		{
			$.popupWindow($(".popupdata1"),
							{width: '980px'});
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}
	if($(".p2").length)
	{
		$(".p2").click(function()
		{
			$.popupWindow($(".popupdata2"),
							{width: '450px'});
			$('.forOverlay').find('form').attr('id', 'form_call')
			$('.forOverlay').find('form').find('.dpr').addClass('datepicker');
			datepicker();
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}

	if($(".p3").length)
	{
		$(".p3").click(function()
		{
			$.popupWindow($(".popupdata3"),
							{width: '450px'});
			$('.forOverlay').find('form').attr('id', 'form_order')
			$('.forOverlay').find('form').find('.dpr').addClass('datepicker');
			datepicker();
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}

	if($(".p4").length)
	{
		$(".p4").click(function()
		{
			$.popupWindow($(".popupdata4"),
							{width: '450px'});
			$('.forOverlay').find('form').attr('id', 'form_feedback')
			$('.forOverlay').find('form').find('.dpr').addClass('datepicker');
			datepicker();
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}

	if($(".p5").length)
	{
		$(".p5").click(function()
		{
			$.popupWindow($(".popupdata5"),
							{width: '450px'});
			$('.forOverlay').find('form').attr('id', 'form_price')
			$('.forOverlay').find('form').find('.dpr').addClass('datepicker');
			datepicker();
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}
	
	if($(".p6").length)
	{
		$(".p6").click(function()
		{
			$.popupWindow($(".popupdata6"),
							{width: '450px'});
			$('.forOverlay').find('form').attr('id', 'form_faq')
			$('.forOverlay').find('form').find('.dpr').addClass('datepicker');
			datepicker();
			return false;
		});
		//setEqualHeight($(".popupMenu > ul > li"));
	}

	/* Top Menu */
	if($(".underTopMenu").length)
	{
		//по умолчанию выбрать первое меню
		if (!$(".underTopMenu li").hasClass('current')) {
			$(".underTopMenu li").eq(0).addClass('current');
			$(".mainMenuBody ul").eq(0).addClass('active');
		}


		/* Width Li-items */
		topMenuLiWidth($(".topMenu.active"));

		/* Under Top Menu Tabs*/
		$(".underTopMenu li a").click(function()
		{
			if( (!$(this).parent().hasClass("current")) && (!$(this).parent().hasClass("allServices")) )
			{
				$(this).parent().addClass("current").siblings().removeClass("current");
				$(this).parent().parent().parent().parent().find(".mainMenuBody").find(".topMenu").eq($(this).parent().index()).addClass("active").siblings().removeClass("active");
				/* Width Li-items */
				topMenuLiWidth($(".topMenu.active"));
				if ($(this).hasClass('topMenu1') && $('.promo1').length && $('.promo2').length) {
					$('.promo1').show();
					$('.promo2').hide();
					$('#mycarousel-index-top').jcarousel({
						visible: 1,
						scroll: 1
					});
				}
				if ($(this).hasClass('topMenu2') && $('.promo1').length && $('.promo2').length) {
					$('.promo2').show();
					$('.promo1').hide();
					$('#mycarousel-index-top2').jcarousel({
						visible: 1,
						scroll: 1
					});
				}


				return false;
			}
			else if($(this).parent().hasClass("current"))
			{
				return false;
			}
		});

		/* Hover Li-items */
		$(".topMenu > li").hover(function()
		{
			var curWidth = $(this).width();

			$(this).addClass("hover").css("z-index",90).siblings().css("z-index",1);
			$(this).siblings().find(".topMenuPodmenu").hide();
			$(this).find(".topMenuPodmenu").show().css("width",curWidth);
		}, function()
		{
			$(this).removeClass("hover");
			$(this).find(".topMenuPodmenu").hide();
		});
	};

	/* Search */
	if($(".search-txt").length)
	{
		$(".search-txt").focus(function()
		{
			$(this).addClass("focus");
			if($(this).attr("value")==$(this).attr("title"))
			{
				$(this).attr("value","");
			};
		});
		$(".search-txt").blur(function()
		{
			$(this).removeClass("focus");
			if($(this).attr("value")=="")
			{
				$(this).attr("value",$(this).attr("title"));
			};
		});
	};

	/* Select *
	var params = {
		changedEl: ".select1",
		visRows: 5,
		scrollArrows: true
	}
	cuSel(params);*/

	/* Main and Dop Content Blocks */
	if($(".mainContent").length)
	{
		var heightMainBlock = $(".mainContent").innerHeight();
		var heightH1 = 0;
		if($(".Title").length)
		{
			heightH1 = $(".Title").innerHeight();
		};

		if($(".mainContent").html())
		{
			$(".mainContent-infoBlock").css("min-height",heightMainBlock);
		};
	};

	/* Content Table */
	if($(".content table").length)
	{
		$(".content table").each(function(){
			if(!$(this).hasClass("simple")&&!$(this).hasClass("nocolor"))
			{
				$(this).find("tbody").each(function()
				{
					$(this).find("tr:first-child").addClass("first");
					$(this).find("tr:last-child").addClass("last");
				});
				$(this).find("tbody:last-child").addClass("last");
				$(this).find("thead tr th:first-child").addClass("first");
				$(this).find("thead tr th:last-child").addClass("last");
			};
		})
	};

	/* Breadcrumbs */
	if($(".bread").length)
	{
		$(".bread").find("li:last-child").addClass("last");
	}

	/* JCarousel */
	if($('#mycarousel-index-top').length)
	{
		$('#mycarousel-index-top').jcarousel({
			//auto: 5,
			visible: 1,
			scroll: 1
		});
	}

	if($('#mycarousel-index-top2').length)
	{
		$('#mycarousel-index-top2').jcarousel({
			//auto: 5,
			visible: 1,
			scroll: 1
		});
	}

	/* FeedBack */
	if($(".contactUs").length)
	{
		var obj = $(".main");
		obj.find(".feedback").find("table").hide();
		obj.find(".feedback").addClass("interactive");
		obj.find(".feedback .contactUs").toggle(function()
		{
			$(this).parent().parent().parent().find("table").show();
		}, function()
		{
			$(this).parent().parent().parent().find("table").hide();
		});
	}

	/* Tabs */
	if($(".tabs").length)
	{
		$(".tabs-title a").click(function()
		{
			if(!$(this).parent().hasClass("current"))
			{
				$(this).parent().addClass("current").siblings().removeClass("current");
				$(this).parent().parent().parent().find(".tabs-body").find(".tabs-body-block").eq($(this).parent().index()).addClass("active").siblings().removeClass("active");
			}
			if ($(this).hasClass('map_redraw'))
				map.redraw();
			return false;
		});
	}

	/* Sales Center */
	if($(".salesCenter-list-table").length)
	{
		$(".salesCenter-list-table").each(function()
		{
			if(!$(this).parent().hasClass("current"))
			{
				$(this).hide();
			}
		});

		$(".salesCenter-list h2 a").click(function() {
			if($(this).parent().parent().hasClass("current")) {
				$(this).parent().parent().removeClass("current");
				$(this).parent().parent().find(".salesCenter-list-table").slideUp();
			}
			else {
				$(this).parent().parent().addClass("current").siblings().removeClass("current");
				$(this).parent().parent().find(".salesCenter-list-table").slideDown().parent().siblings().find(".salesCenter-list-table").slideUp();
			}
			return false;
		});
	}

	/* Contacts */
	if($(".contactsNumFoto").length)
	{
		$(".contactsNumFoto").each(function()
		{
			$(".contactsNumFoto:first-child").addClass("first");
			$(".contactsNumFoto:last-child").addClass("last");
		});
	}

	/* FAQ */
	if($(".queSection").length)
	{
		slideUpAllQuestions(0);
		$(".toggleAllQuestions").show();

		$('.queSection-q a').click(function(){
			if(!$('.queSection .queSection-a:animated').length){
				var link = $(this);
				var queSection = link.parent().parent();
				var queSectionQ = queSection.find('.queSection-q:first');
				if(queSection.hasClass('open')){
					queSection.removeClass('open');
					queSectionQ.removeClass('open');
					queSection.find('.queSection-a:first').slideUp(500);
				}
				else {
					queSection.addClass('open');
					queSectionQ.addClass('open');
					queSection.find('.queSection-a:first').slideDown(500);
				}
			}
			return false;
		});

		$('.toggleAllQuestions').click(function(){
			if(!$('.queSection .queSection-a:animated').length){
				if($('.toggleAllQuestions').hasClass('open'))
					slideUpAllQuestions(500);
				else
					slideDownAllQuestions(500);
			}
			return false;
		});
	}

		/* Datepicker */
	datepicker();

	//карта филиалов или точек продаж
	if ($('#map_canvas').length) {
		map = new YMaps.Map($(".yaMap"));
		map.addControl(new YMaps.TypeControl());
		//map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.MiniMap());
		//map.addControl(new YMaps.ScaleLine());
		map.addControl(new YMaps.SearchControl());
		map.enableScrollZoom();
		var s = new YMaps.Style();
		s.iconStyle = new YMaps.IconStyle();
		s.iconStyle.href = "/images/balun.png";
		s.iconStyle.size = new YMaps.Point(33, 43);
		s.iconStyle.offset = new YMaps.Point(-12, -40);
		$(".mapItem").each(  function()
		{
			var coord1 = $(this).find('.m_coord1').text();
			var coord2 = $(this).find('.m_coord2').text();
			var scope = $(this).find('.m_scope').text();
			var text = $(this).find('.m_content').html();
			var pointOverlay = new YMaps.Placemark(new YMaps.GeoPoint(coord1, coord2), {style: s});
			pointOverlay.setBalloonContent(text);
			map.addOverlay(pointOverlay);
		});
		map.setCenter(new YMaps.GeoPoint(27.56164, 53.902257), 6);
	}

	//отдельная карта
	if ($('.map_single').length) {
		map = new YMaps.Map($(".map_single"));
		map.addControl(new YMaps.TypeControl());
		//map.addControl(new YMaps.ToolBar());
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.MiniMap());
		//map.addControl(new YMaps.ScaleLine());
		map.addControl(new YMaps.SearchControl());
		map.enableScrollZoom();
		var s = new YMaps.Style();
		s.iconStyle = new YMaps.IconStyle();
		s.iconStyle.href = "/images/balun.png";
		s.iconStyle.size = new YMaps.Point(33, 43);
		s.iconStyle.offset = new YMaps.Point(-12, -40);
		var map_item = $(".mapItem");
		var coord1 = map_item.find('.m_coord1').text();
		var coord2 = map_item.find('.m_coord2').text();
		var scope = map_item.find('.m_scope').text();
		var text = map_item.find('.m_content').html();
		var pointOverlay = new YMaps.Placemark(new YMaps.GeoPoint(coord1, coord2), {style: s});
		pointOverlay.setBalloonContent(text);
		map.addOverlay(pointOverlay);
		map.setCenter(new YMaps.GeoPoint(coord1, coord2), scope);
	}



});

/* ON RESIZE */
$(window).resize(function(){

});

function datepicker() {
	if($(".datepicker").length)
	{
		$(function(){

			if ($('#consts').hasClass('ru')) {
				$.datepicker.setDefaults({
					showAnim: 'slide',
					closeText: 'Закрыть',
					prevText: '<Пред',
					nextText: 'След>',
					currentText: 'Сегодня',
					monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
					monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн','Июл','Авг','Сен','Окт','Ноя','Дек'],
					dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
					dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
					dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
					weekHeader: 'Нед',
					dateFormat: 'dd.mm.yy',
					firstDay: 1,
					isRTL: false,
					showMonthAfterYear: false,
					yearSuffix: ''
				});
			}

			$('.datepicker_only_image').css({visibility: 'hidden', width:1}).datepicker({
				showOn: "button",
				buttonImage: "images/calendar.gif",
				buttonImageOnly: true
			});
			$('#courses_tab1_form').find('input, select').bind('change', function(){
				$('#courses_tab1_form').submit();
			});

			$('.datepicker').each(function() {
				if($(this).attr('name') == 'birth')
					$(this).datepicker({changeYear: true, changeMonth: true});
				else if ($(this).hasClass('fromNow'))
					$(this).datepicker({minDate: "0"});
				else
					$(this).datepicker();
			});
		});
	}
}

/******************/

function topMenuLiWidth(activeMenu)
{
	var colItems = activeMenu.find(" > li").length;
	var menuWidth = activeMenu.width();
	var possibleWidthLi =  Math.floor(menuWidth/colItems);
	var testWidth = possibleWidthLi*colItems;
	var difWidth = menuWidth-testWidth;
	activeMenu.find(" > li").css("width", Math.floor(possibleWidthLi));
	activeMenu.find(" > li:last-child").css("width", Math.floor(possibleWidthLi+difWidth));

	//setEqualHeight($(".topMenu.active > li :first-child"));
	//alert($(".topMenu.active > li :first-child").length);
}

/* Buttons hover */
function btnFocus(btn)
{
	$(btn).hover(function(){
		$(this).css("background-position","left -80px");
		$(this).find("input").css("background-position","right -121px");
		$(this).find("input").css("color","#fff").css("text-shadow","0 1px 1px rgba(0,0,0,0.2)");
	},
	function(){
		$(this).css("background-position","left 0px");
		$(this).find("input").css("background-position","right -39px");
		$(this).find("input").css("color","#41444e").css("text-shadow","0 1px 1px rgba(255,255,255,0.9)");
	});

	$(btn).mousedown(function(){
		$(this).css("background-position","left -165px");
		$(this).find("input").css("background-position","right -208px");
		$(this).find("input").css("color","#fff").css("text-shadow","0 1px 1px rgba(0,0,0,0.2)");
	}).mouseup(function(){
		$(this).css("background-position","left 0px");
		$(this).find("input").css("background-position","right -39px");
		$(this).find("input").css("color","#41444e").css("text-shadow","0 1px 1px rgba(255,255,255,0.9)");
	});
};

/* height block */
function setEqualHeight(columns)
{
	var tallestcolumn = 0;
	columns.each(
	function()
	{
		currentHeight = $(this).height();
		if(currentHeight > tallestcolumn)
		{
			tallestcolumn  = currentHeight;
		}
	}
	);
	columns.height(tallestcolumn);
};
function HeightForRows(parentBlock,childBlock, childBlockWidth)
{
	var widthBox = parentBlock.width();
	var widthBlock = childBlockWidth; /* width of small block whith margin and padding */
	var colBlockInRow = Math.floor(widthBox/widthBlock);
	var colRow = Math.ceil((childBlock.length)/colBlockInRow);
	var colElements = childBlock.length;
	//alert(colElements);
	var indexElement = 0;
	var maxHeight;
	childBlock.each(function()
		{
			$(this).css("height","auto");
		});

	for(i=1; i<=colElements; i+=colBlockInRow)
	{
		maxHeight = 0;
		for(j=0; j<colBlockInRow; j++)
		{
			indexElement = i+j-1;
			currentHeight = childBlock.eq(indexElement).height();
			if (maxHeight == 0 || currentHeight > maxHeight)
			{
				maxHeight = currentHeight;
			}
		}
		for(j=0; j<colBlockInRow; j++)
		{
			indexElement = i+j-1;
			childBlock.eq(indexElement).height(maxHeight);
		}

	}
};

/* Detect IE */
function detectIE67(){
  var browser = navigator.appName;
  if (browser == "Microsoft Internet Explorer"){
	var b_version = navigator.appVersion;
	var re = /\MSIE\s+(\d\.\d\b)/;
	var res = b_version.match(re);
	if (res[1] <= 7) return true;
  }
  return false;
}

/* FAQ */
function slideUpAllQuestions(speed){
	$('.queSection').each(function(){
		var queSection = $(this);
		queSection.removeClass('open');
		queSection.find('.queSection-q').removeClass('open');
		if(!speed)
			queSection.find('.queSection-a').hide();
		else
			queSection.find('.queSection-a').slideUp(speed);
	});
	//развернуть
	$('.toggleAllQuestions').removeClass('open').find('span').html($('#basic6').text());
}
function slideDownAllQuestions(speed){
	$('.queSection').each(function(){
		var queSection = $(this);
		queSection.addClass('open');
		queSection.find('.queSection-q').addClass('open');
		queSection.find('.queSection-a').slideDown(speed);
	});
	//свернуть
	$('.toggleAllQuestions').addClass('open').find('span').html($('#basic5').text());
}


