$(document).ready(function() {
	showCounter();
	zoomImage();
	toggleParagraph();
	//hlAddrPoint(); 
	//passageSchemeZoom();
	if($('#home_content').size()){optimizeHomeCatBlock()};
	logoShadowHeightFix();
	if($('#calculator').size()){claculator();}
});



function logoShadowHeightFix() {
	$(".logo_shadow_block").css("height",$(".logo_col").height());
}



function optimizeHomeCatBlock() {

	var img_height = 0;
	$(".p_cars .p_car .p_car_img").each(function(intIndex) {
		if($(this).height() > img_height)
			img_height = $(this).height();
	});
	
	$(".p_cars .p_car .p_car_img").css("height",img_height);


	var height = 0;
	$(".p_cars .p_car").each(
		function(intIndex) {
			if($(this).height() > height)
				height = $(this).height();
		}
	);
	
	$(".p_cars .p_car").css("height",height);

}



function showCounter(){
	try{document.getElementById('counter').innerHTML = '<a href="http://www.liveinternet.ru/click" '+'target=_blank><img src="http://counter.yadro.ru/hit?t14.5;r'+escape(document.referrer)+((typeof(screen)=='undefined')?'':';s'+screen.width+'*'+screen.height+'*'+(screen.colorDepth?screen.colorDepth:screen.pixelDepth))+';'+Math.random()+'" alt="liveinternet.ru: iieacaii ?enei oeoia ca 24 ?ana, iinaoeoaeae ca 24 ?ana e ca naaiai\y" '+'border=0 width=88 height=31></a>';}
	catch(e){};
}



function zoomImage(){
	$("a.imgZoom").fancybox({
		'zoomOpacity' : true,
		'overlayShow' : false,
		'zoomSpeedIn' : 150,
		'zoomSpeedOut' : 150
	}); 
}



function toggleParagraph(){
	$(".pOut.min .pContent").hide(); 

	$(".pOut.min h3").toggle(function(){
		$(this).addClass("active");
		}, function () {
		$(this).removeClass("active");
	});

	$(".pOut.min h3").click(function(){
		$(this).next(".pOut.min .pContent").slideToggle("fast");
	});
};



function hlAddrPoint(){
	$('#addrList').mouseover(function(e) {
		var overed = $(e.target);
		overed.parents('li').addClass('hl');
		overed.parents('li').find('.point').addClass('hl');
		
	});
	
	$('#addrList').mouseout(function(e) {
		var outed = $(e.target);
		outed.parents('li').removeClass('hl');
		outed.parents('li').find('.point').removeClass('hl');
	});
}



//заказ авто
function MailSend(){
	var form = $('#orderAuto form');//форма
	var params = {action:'mail_send'};//данные
	var fields = form.find('.field');//поля формы

	fields.each(function(){
		params[$(this).attr('name')] = $(this).val();
	});
	
	$.ajax({
		type: "POST",
		url: "/action.php",
		data: params,
		success: function(){
			tggOrdForm();//скрывает форму
			fields.val('');//очищает поля
		}
	});
}




//скрывает/открывает форму
function tggOrdForm(){
	var formOut = $('#orderAuto');
	
	if(formOut.hasClass('hidden')){
		formOut.removeClass('hidden');
		$('#blBg').removeClass('hidden');
		ordFormValidation('required', 'send');//валидация формы
	}
	else{
		formOut.addClass('hidden');
		$('#blBg').addClass('hidden');
	}
	
	
	
}



//валидация форм
function ordFormValidation(fldClass, bttId){
	var reqFields = $('input.'+fldClass);//обязателные поля
	
	checkFields();
	reqFields.keyup(function(){
		checkFields();
	});
	
	function checkFields(){
		var button = $('#'+bttId);
		var reqFieldsNum = reqFields.size();
		var filledNum = 0;

		reqFields.each(function(){
			if($(this).val() != '')
				filledNum = filledNum + 1;
		});
		
		if(filledNum == reqFieldsNum)
			button.attr('disabled', '').removeClass('disabled');
		else
			button.attr('disabled', 'true').addClass('disabled');
	}
	
}



//открывает схемы проезда для конкретного адреса
function passageSchemeZoom(){
	$("a.imgZoom").fancybox({
		'zoomOpacity' : true,
		'overlayShow' : true,
		'zoomSpeedIn' : 150,
		'overlayOpacity' : 0.5,
		'zoomSpeedOut' : 150
	}); 
}



function claculator(){
	var carPrice = $('#aPrice'),
		startPaymentAbs = $('#startPaymentAbs'),
		startPaymentPerc = $('#startPaymentPerc'),
		period = $('#period'),
		interRate = $('#interRate'),
		runBtt = $('#button'),
		amount = $('#amount'),
		perMonth = $('#perMonth');
	

	
	addEventFunc({fields:[carPrice, startPaymentAbs, startPaymentPerc], event:'keypress', func:function(e){
		if(48 > e.which || e.which > 57)
			e.preventDefault();
	}});
	
	
	addEventFunc({fields:[startPaymentAbs, carPrice], event:'keyup', func:function(e){
		if(e.which == 8 || e.which == 0 || (e.which<=57 && e.which>=48)){
			var price = carPrice.getVal(),
				startPayment = startPaymentAbs.getVal();
			if(price != 0 && startPayment != 0)
				startPaymentPerc.val(Math.round(startPayment*100/price));
		}
	}});
	
	
	addEventFunc({fields:[startPaymentPerc], event:'keyup', func:function(e){
		if(e.which == 8 || e.which == 0 || (e.which<=57 && e.which>=48)){
			if(e.target.value > 100)
				e.target.value = 100;
			
			var price = carPrice.getVal(),
				startPayment = startPaymentPerc.getVal();
			if(price != '' && startPayment != '')
				startPaymentAbs.val(Math.round(price*startPayment/100));
		}
	}});
	
	
	validation({fields:[carPrice, startPaymentAbs, startPaymentPerc], button:runBtt});
	
	
	runBtt.click(function(){
		var resArr = [perMonth, amount];
		
		
		//расчёт для каждого выходного поля
		$(resArr).each(function(){
			this.removeClass('notActual').set();  //расчёт и запись результата
		});
		
		
		//устновка не-актуальности выходных данных
		$([carPrice, startPaymentAbs, startPaymentPerc, period]).each(function(){
			this.one(this.getEvent(), function(){
				$(resArr).each(function(){
					this.addClass('notActual');
				});
			});
		});
		
	});
	
	
	
	//service
	function validation(par){
		var fArr = par.fields,
			btt = par.button;
		
		for(var i=0; i<=fArr.length-1; i++){
			fArr[i].keyup(function(){
				for(var i=0; i<=fArr.length-1; i++){
					if(fArr[i].getVal() == ''){
						if(!btt.attr('disabled')){
							btt.fadeOut(function(){
								$(this)
									.addClass('disabled')
									.attr('disabled', true)
									.fadeIn()
							});
						}
						return false;
					}
				}

				if(btt.attr('disabled')){
					btt.fadeOut(function(){
						$(this)
							.removeClass('disabled')
							.removeAttr('disabled')
							.fadeIn()
					});
				}
			});
		}
	}
	
	
	perMonth.set = function(){
		var price = carPrice.getVal(),
			startPayment = startPaymentAbs.getVal(),
			rate = interRate.getVal()/1200,
			nper = period.getVal()-1,
			pv = price - startPayment,
			res;
			
		res = Math.round((rate*pv*Math.pow((1+rate), nper))/(Math.pow((1+rate), nper)-1)).numFormat();
		this.html(res);
	}
	
	
	amount.set = function(){
		var res = (perMonth.getVal()*period.getVal()).numFormat();
		this.html(res);
	}
	
	
	$.prototype.getVal = function(){
		var res;
		if(this.attr('tagName') == 'INPUT' || this.attr('tagName') == 'SELECT')
			res =  this.val();
		else
			res = this.text().replace(/\D/, '');
			
		return res.split(' ').join('');
	}
	
	
	$.prototype.getEvent = function(){
		if(this.attr('tagName') == 'INPUT')
			return 'keyup';
		else if(this.attr('tagName') == 'SELECT')
			return 'change';
	}
	
	
	function addEventFunc(par){
		$(par.fields).each(function(){
			this.bind(par.event, function(e){
				par.func(e);
			});
		});
	}
		
		
	Number.prototype.numFormat = function(){
		var f = this.toString(),
			h = f;
				
		if(f.length > 3) {
			f = '';
			for(j = 3; j < h.length; j+=3) {
				i = h.slice(h.length - j, h.length - j + 3);
				f = ' ' + i +  f + '';
			}
			j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
			f = j + f;
		}
		
		return f;
	}
}







	