﻿// JavaScript Document

// Optimizing the space taken by elements with different height
function fullSpace(jQSelector){
	
	var leftHeight = 0;
	var rightHeight = 0;
	
	$(jQSelector).each(function(i){
		
		if(i == 0 || leftHeight <= rightHeight){
			$(this).css('float', 'left');
			leftHeight += $(this).outerHeight(true);
		}
		else{
			$(this).css('float', 'right');
			rightHeight += $(this).outerHeight(true);
		}
	})
}

jQuery(function($){
	
/*--- MODEL ---*/
	// Spreading footer menu li all the width
	function footerMenuAlign(){
		var n = $('#footer > div:first-child ul li').size();
		var sumLiWidth = 0;
		var mlul = parseFloat($('#footer > div:first-child ul').css('margin-left'));
		var wdiv = $('#footer > div:first-child').width();
		
		// Total width of all the list items
		for(var i = 0; i < n; i++){
			sumLiWidth += $('#footer > div:first-child ul li').eq(i).width();
		}
		
		// Margin-left for all the list items
		var ml = (wdiv - mlul - sumLiWidth) / (n - 1);
		if(ml >= 24)
		    ml = 24;
		
		$('#footer > div:first-child ul li:not(:first)').css('margin-left', ml + 'px');
	}
	
	// Similar height for elements
	$.fn.similarHeight = function(){
		var maxHeight = 0;
		
		this.each(function(){
			maxHeight = Math.max(maxHeight, $(this).height());
		})
		
		return this.height(maxHeight);
	}
	
	// Switchers for a gallery block
	function addSwitchButtons(jQSel){
		var n = $(jQSel + ' > .illustra').size();
		
		for(var i = 0; i < n; i++){
			if(i == 0)
				$(jQSel + ' > ul').append('<li class="this"></li>');
			else
				$(jQSel + ' ul').append('<li></li>');
		}
	}
	
	// Changing a gallery
	function galleryChange(jQSel, time){
		var imgNext = $(jQSel + ' > .illustra.this').next('.illustra').size()
		? $(jQSel + ' > .illustra.this').next('.illustra')
		: $(jQSel + ' > .illustra:first');
		
		var buttonNext = $(jQSel + ' > ul li.this').next('li').size()
		? $(jQSel + ' > ul li.this').next('li')
		: $(jQSel + ' > ul li:first');
		
		imgNext.addClass('next').siblings('.this').fadeOut(time, function(){
			$(this).removeClass('this').fadeIn().siblings('.illustra.next').removeClass('next').addClass('this');
		});
		
		buttonNext.addClass('this').siblings('.this').removeClass('this');
	}
	
	
/*--- HOLDING EVENTS ---*/
    $(window).resize(function(){
		
		// Margin-left for  list items in footer
		footerMenuAlign();
		
		// fullSpace
		fullSpace('ul.tw2 li.twoColumn');
		
		$('#half_1, #half_2').height('auto');
		
	});

	/*--- CONTROLLER ---*/
	
	// Set animation speed:
	var hillSpeed 		= 1000;
	var treeSpeed 		= 800;
	var blackElSpeed 	= 1100;
	var cloudsSpeed		= 1000;
	var h1Speed 		= 900;
	var carSpeed 		= 1200;
	
	// Set variable
	var bg_img = "-2300";
	var thisValue = 1;
	var lastValue = 3;
	var currentValue = 305;
		
	$('#switcher > div:first-child').slider({
		min: 0,
		max: 456,
		animate: true,
		value: currentValue,
		stop: function(ev, ui){
		
			// Hills animation
			if ( ui.value >= 0 && ui.value <= 96 ) 			{ bg_img = "-2300"; thisValue = 1; $(this).slider("value", 38);
			} else if ( ui.value > 96 && ui.value <= 224 )	{ bg_img = "-2100";    thisValue = 2; $(this).slider("value", 162);
			} else if ( ui.value > 224 && ui.value <= 384 )	{ bg_img = "-1900";  thisValue = 3; $(this).slider("value", 305);
			} else if ( ui.value > 384 && ui.value <= 456 ) { bg_img = "-1700";  thisValue = 4; $(this).slider("value", 430); }
			
			$('#bg img').animate({ marginLeft: bg_img + "px" }, hillSpeed);
			
			// Objects animation
			if ( lastValue > thisValue ) {
			
				$('#bg .tree li.i' + thisValue ).animate({ marginLeft: "-3000px"}, 10);
				$('#bg .blackEl li.i' + thisValue ).animate({ marginLeft: "-3000px"}, 10);
				$('#bg .clouds li.i' + thisValue ).animate({ marginLeft: "-3000px"}, 10);
				$('#bg .titleH1 li.i' + thisValue ).animate({ marginLeft: "-3000px"}, 10);
				$('#bg .car li.i' + thisValue ).animate({ marginLeft: "-3000px"}, 10);
				
				$('#bg .tree li.this').removeClass('this').animate({ marginLeft: "3000px"}, treeSpeed);
				$('#bg .blackEl li.this').removeClass('this').animate({ marginLeft: "3000px"}, blackElSpeed);
				$('#bg .clouds li.this').removeClass('this').animate({ marginLeft: "3000px"}, cloudsSpeed);
				$('#bg .titleH1 li.this').removeClass('this').animate({ marginLeft: "3000px"}, h1Speed);
				$('#bg .car li.this').removeClass('this').animate({ marginLeft: "3000px"}, carSpeed);
				
				$('#bg .tree li.i' + thisValue ).addClass('this').animate({ marginLeft: "-450px" }, treeSpeed);
				$('#bg .blackEl li.i' + thisValue ).addClass('this').animate({ marginLeft: "-170px" }, blackElSpeed);
				$('#bg .clouds li.i' + thisValue ).addClass('this').animate({ marginLeft: "-80px" }, cloudsSpeed);
				$('#bg .titleH1 li.i' + thisValue ).addClass('this').animate({ marginLeft: "-245px" }, h1Speed);
				$('#bg .car li.i' + thisValue ).addClass('this').animate({ marginLeft: "-240px" }, carSpeed);
				
			} else if ( lastValue < thisValue ) {			
		
				$('#bg .tree li.i' + thisValue ).animate({ marginLeft: "3000px"}, 10);
				$('#bg .blackEl li.i' + thisValue ).animate({ marginLeft: "3000px"}, 10);
				$('#bg .clouds li.i' + thisValue ).animate({ marginLeft: "3000px"}, 10);
				$('#bg .titleH1 li.i' + thisValue ).animate({ marginLeft: "3000px"}, 10);
				$('#bg .car li.i' + thisValue ).animate({ marginLeft: "3000px"}, 10);
				
				$('#bg .tree li.this').removeClass('this').animate({ marginLeft: "-3000px"}, treeSpeed);
				$('#bg .blackEl li.this').removeClass('this').animate({ marginLeft: "-3000px"}, blackElSpeed);
				$('#bg .clouds li.this').removeClass('this').animate({ marginLeft: "-3000px"}, cloudsSpeed);
				$('#bg .titleH1 li.this').removeClass('this').animate({ marginLeft: "-3000px"}, h1Speed);
				$('#bg .car li.this').removeClass('this').animate({ marginLeft: "-3000px"}, carSpeed);
				
				$('#bg .tree li.i' + thisValue ).addClass('this').animate({ marginLeft: "-450px" }, treeSpeed);
				$('#bg .blackEl li.i' + thisValue ).addClass('this').animate({ marginLeft: "-170px" }, blackElSpeed);
				$('#bg .clouds li.i' + thisValue ).addClass('this').animate({ marginLeft: "-80px" }, cloudsSpeed);
				$('#bg .titleH1 li.i' + thisValue ).addClass('this').animate({ marginLeft: "-245px" }, h1Speed);
				$('#bg .car li.i' + thisValue ).addClass('this').animate({ marginLeft: "-240px" }, carSpeed);
	
			} else if ( lastValue == thisValue ) {}
			
			lastValue = thisValue;

		}
	});
	

	// Margin-left for  list items in footer
	footerMenuAlign();
	
	
	// Middle paragraph in footer: p.i2
	(function(){
		var w = $('#footer p.i2').width();
		$('#footer p.i2').css('margin-left', -w / 2 + 'px');
	})()
	
	
	// Similar height for elements
	//$('#half_1, #half_2').similarHeight();
	
	
	// Sliding up
	$('div.block > a.more, #more_2').click(function(ev){
		var th = $(ev.target);
		ev.preventDefault();
		th.prev('div').slideToggle(300).toggleClass('open');
		
		if ( th.prev('div').attr('class') == 'fade open' ) { $(this).html('Скрыть'); }
		if ( th.prev('div').attr('class') == 'fade' ) { $(this).html('Подробнее'); }

	});
	
	
	// Pop-up menu with towns
	$('div.cities div.this > div > span').click(function(ev){
		var th = $(ev.target);
		
		th.siblings('ul').slideToggle(150);
	});
	
	$('ul.shops li.cityID' + $('div.cities div.this ul.popup li.this').index()).addClass('this');
	$('ul.buy li.cityID' + $('div.cities div.this ul.popup li.this').index()).addClass('this');
		
	// Выбран город -> click
	$('div.cities div.this ul.popup li').click(function()
	{		
		$('ul.shops li').removeClass('this');									// Список сервисов
		$('ul.buy li').removeClass('this');										// Список сервисов
		$('div.cities div.this ul.popup li.this').removeClass('this');			// Город в выпадающем списке
		$('div.cities div.this span.this').removeClass('this');					// Город
		$(this).addClass('this');
		$('div.cities div.this span.i' + $(this).index()).addClass('this');
		$('ul.shops li.cityID' + $(this).index()).addClass('this');
		$('ul.buy li.cityID' + $(this).index()).addClass('this');
		$('div.cities div.this ul.popup').slideToggle(150);
	});
	
	
	// Все города -> click
	$('div.cities div.this ul.popup li.all_city').click(function()
	{
		$('ul.shops li, ul.buy li').each(function(){ $(this).addClass('this'); });
	});
	
	// Discount/Alphabet Links
	$('ul.choose li a.discountLink').click(function()
	{
		var thisHref = $(this).attr('href');
		$(this).attr('href', thisHref + $('div.cities div.this ul.popup li.this').index() );
	});
		
	// Optimizing the space taken by elements with different height
	fullSpace('ul.tw2 li.twoColumn');
	
	
	// Colored cars
	$('.colorpicker > img:not(.this)').fadeOut();
	
	$('.colorpicker > ul li').click(function(ev){
		var th = $(ev.target);
		var i = th.parents('.colorpicker').find('ul li').index(th);
		var imgThis = th.parent().siblings('img.this');
		var imgI = th.parent().siblings('img').eq(i);
		
		if(th.hasClass('this'))
			return;
		
		th.siblings().removeClass('this').end().addClass('this');
		imgThis.fadeOut(200).removeClass('this');
		imgI.fadeIn(200).addClass('this');
	});
	
	
	// Gallery on a news page
	(function(){
		var timer;
		var duration = 1000;
		
		addSwitchButtons('.gallery');
		
		if(!timer){
			timer = setInterval(function(){
				galleryChange('.gallery', duration)
			}, duration * 8);
		}
		
		$('.gallery > ul li').live('click', function(ev){
			var target = $(ev.target);
			var i = $('.gallery ul li').index(target);
			
			if(target.hasClass('this'))
				return;
			
			if(timer)
				clearInterval(timer);
				
			target.addClass('this').siblings('.this').removeClass('this');
			$('.gallery > .illustra:animated').stop(true, true);
			
			$('.gallery > .illustra').eq(i).addClass('next').siblings('.this').fadeOut(duration, function(){
				$(this).removeClass('this').fadeIn().siblings('.illustra.next').removeClass('next').addClass('this');
			});
			
			timer = setInterval(function(){
				galleryChange('.gallery', duration);
			}, duration * 8);
		});
	})();
		
	// Валидация форм
	function validate()
	{
		var isValid = true;
		var $form = $(this);
		var formClass = $form.attr("class");
		
		if ( formClass == 'ajax' )
		{
			var sub = $("span.cuselActive").attr('val');
			var cc = $("span.cuselActive").attr('name');
			$('input[name=sub]').val(sub);
			$('input[name=cc]').val(cc);
		}
				
		// Error check
		if ( $('input[type=submit]').attr('class') == 'submit_protector' ) { isValid = false; return false; }
			
		var fields = "input[name=f_Subject], input[name=f_discount], input[name=f_admincontact], input[name=f_activity], input[name=f_city], input[name=f_address1], input[name=f_phone], input[name=f_backlink_adr], textarea[name=f_whatedit]";
		$(fields, $form).each(function(){
			var $this = $(this);
			var $val = $this.val();

			if($val == '' || $val == 'Заполните это поле')
			{
				$this.val("Заполните это поле");
				$this.addClass("error");
				isValid = false;
			}
			else if($this.attr("name") == "f_admincontact" && (!$val.match("^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}$")) )
			{
				$this.val("Не правильно введен E-mail");
				$this.addClass("error");
				isValid = false;
			}
			
			else
			{
				$this.removeClass("error");
				return true;
			}
		});
		
		if(isValid)
		{
			if ( formClass == 'ajax2' )
			{
				var message = $('input[name=f_message2]').val();
				var email = $('input[name=f_admincontact]').val();
				var sendmail = false;
				$.post('/js/email.php', 'ID='+ message +'&email='+ email, function(msg){
					if (msg=='FALSE') { $('input[name=f_admincontact]').addClass("error").val('Введенный E-mail не найден'); }
					else
					{
						$('div.the_form').css('display', 'none').after('<div class="loading"></div>');
						var url = $form.attr("action");
						var data = $("input, textarea", $form).serialize();
						$.post(url, data).success(function(data){ $('div.loading').css('display', 'none'); $('div.the_form').html('<p>Спасибо, ваша заявка принята.</p>').css('display', 'block'); });
						return false;
					}
				});
			}
			
			else
			{
				$('div.the_form').css('display', 'none').after('<div class="loading"></div>');
				var url = $form.attr("action");
				var data = $("input, textarea", $form).serialize();
				$.post(url, data).success(function(data){ $('div.loading').css('display', 'none'); $('div.the_form').html('<p>Спасибо, ваша заявка принята.</p>').css('display', 'block'); });
				return false;
			}
		}
		return false;
	}
	
	// Валидация форм - подключение
	$("form[class=ajax], form[class=ajax2]").submit(validate);
	$("form input, form textarea").focus(function(){ 
		$(this).removeClass("error"); 
		if( $(this).val() == "Заполните это поле" || $(this).val() == "Не правильно введен E-mail" || $(this).val() == "Введенный E-mail не найден") { $(this).val(""); }
	});
	
	// Add address
	$('a.plusPointer').click(function()
	{
		$(this).parent().next().slideToggle(300);
		$(this).fadeOut(300);
		return false;
	});
	
	
	
	// Styling checkboxes
	jQuery(".niceCheck").each(
	/* при загрузке страницы меняем обычные на стильные checkbox */
	function() {
		 changeCheckStart(jQuery(this));
	});
	
	function changeCheck(el)
	{
		var el = el,
			input = el.find("input").eq(0);
			  
		if(el.attr("class").indexOf("niceCheckDisabled")==-1)
		{	
			if(!input.attr("checked")) {
				el.addClass("niceChecked");
				input.attr("checked", true);
				$('input[type=submit]').removeClass('submit_protector');
			} else {
				el.removeClass("niceChecked");
				input.attr("checked", false).focus();
				$('input[type=submit]').addClass('submit_protector');
			}
		}
		
		return true;
	}
	
	function changeVisualCheck(input)
	{
	var wrapInput = input.parent();
		if(!input.attr("checked")) {
			wrapInput.removeClass("niceChecked");
			$('input[type=submit]').addClass('submit_protector');
		}
		else
		{
			wrapInput.addClass("niceChecked");
			$('input[type=submit]').removeClass('submit_protector');
		}
	}
	
	function changeCheckStart(el)
	{
		try
		{
		var el = el,
			checkName = el.attr("name"),
			checkId = el.attr("id"),
			checkChecked = el.attr("checked"),
			checkDisabled = el.attr("disabled"),
			checkTab = el.attr("tabindex"),
			checkValue = el.attr("value");
			if(checkChecked)
				el.after("<span class='niceCheck niceChecked'>"+
					"<input type='checkbox'"+
					"name='"+checkName+"'"+
					"id='"+checkId+"'"+
					"checked='"+checkChecked+"'"+
					"value='"+checkValue+"'"+
					"tabindex='"+checkTab+"' /></span>");
			else
				el.after("<span class='niceCheck'>"+
					"<input type='checkbox'"+
					"name='"+checkName+"'"+
					"id='"+checkId+"'"+
					 "value='"+checkValue+"'"+
					"tabindex='"+checkTab+"' /></span>");
			
			/* если checkbox disabled - добавляем соотвсмтвующи класс для нужного вида и добавляем атрибут disabled для вложенного chekcbox */		
			if(checkDisabled)
			{
				el.next().addClass("niceCheckDisabled");
				el.next().find("input").eq(0).attr("disabled","disabled");
			}
			
			/* цепляем обработчики стилизированным checkbox */		
			el.next().bind("mousedown", function(e) { changeCheck(jQuery(this)) });
			el.next().find("input").eq(0).bind("change", function(e) { changeVisualCheck(jQuery(this)) });
			if(jQuery.browser.msie)
			{
				el.next().find("input").eq(0).bind("click", function(e) { changeVisualCheck(jQuery(this)) });	
			}
			el.remove();
		}
		catch(e)
		{
			// если ошибка, ничего не делаем
		}
		
			return true;
	}
	
	// Open form
	$('a.editdata').parent().next().css('display', 'none');
	$('a.editdata').click(function()
	{
		$(this).parent().next().slideToggle(300);
		return false;
	});
	
})
