var base = {
	url : '',
	pie : true,
	cufon : false,
	fixpng : false,
	html5 : true
}
if($.browser.msie && base.html5) {
	$.getScript(base.url+'js/html5.js');
}

if($.browser.msie && base.pie) $.getScript(base.url+'js/pie/pie.js');
if($.browser.msie && $.browser.version == 6 && base.fixpng) {
	$.getScript(base.url+'js/pngfix.js');
	DD_belatedPNG.fix('.fixpngJs');
}

var img_index = 0;


$(document).ready(function(){

	$('.pieJs').pie();
	
	$('input.placeholder, textarea.placeholder').placeholder();

	var nav_a = $('nav a'),
		nav_a_active = nav_a.filter('.active');

	nav_a.not('.active').hover(function(){
		nav_a_active.removeClass('active').removeClass('hover').css({fontWeight:'normal'})
		var width = $(this).outerWidth();
		$(this).css({width:width,padding:0,fontWeight:'bold'}).addClass('hover');
	},function(){
		nav_a_active.addClass('active').css({fontWeight:'bold'});
		$(this).removeAttr('style').removeClass('hover');	
	});

	var width = nav_a_active.outerWidth();
	nav_a_active.css({width:width,padding:0,fontWeight:'bold'}).addClass('hover');

	jQuery('#list_car, #list_photo').jcarousel();
	
	$( "#slider-range-min" ).slider({
		range: "min",
		min: 6,
		max: 78,
		create: function(event, ui) { $(this).append('<div class="ui-slider-value"><span>6 мес</span></div>'); },
		slide: function( event, ui ) {
			$( "#amount" ).val( ui.value );
			$(".ui-slider-value span").html(ui.value + ' мес');
			calculate();
		},
		change: function( event, ui ) { $(".ui-slider-value").css("left", $(".ui-slider-handle").css("left")); $(".ui-slider-value span").html(ui.value + ' мес');}
	});
	$("#slider-range-min").mousemove(function(){
		$(".ui-slider-value").css("left", $(".ui-slider-handle").css("left"));
	});
	
	$("input[name=firstpay]").keyup(function(){	
		calculate();
	});
	
	$('.colors a:first').addClass('active');
	
	$("div#carousel").smoothDivScroll({
		scrollingHotSpotLeft: "#back",
		scrollingHotSpotRight: "#next",
		scrollableArea: "ul.scrollableArea",
		scrollWrapper: "div#carousel_content",
		scrollStep: 5,
		scrollInterval: 25,
		visibleHotSpots: "always"
	});

	var tabs_span = $('.tabs span');

	$('.tabs .name a').click(function(){
		var li = $(this).parents('li');
		li.find('.info').slideToggle(500,function(){
			li.toggleClass('open');	
		});
		return false;
	});

	$('.navi .active').parent().next('li').css('visibility','hidden').end().prev('li').css('visibility','hidden');
	
	$(".cars .block").hover(function(){
        $(this).toggleClass("bg_no");
    });
	
	$(".search-result-table tr").hover(function(){
        $("td", this).toggleClass("hover");
    });
	
	$(".marka_info .more_info tr").hover(function(){
        $(this).toggleClass("tr_hover");
    });
	
	$(".cars .tabcontent").hide();
	$(".cars .tabcontent:first").show();
	
	$(".cars .tabs-menu a").click(function() {
		if (!$(this).hasClass("active")) {
			$(".cars .tabs-menu a").removeClass("active");
			$(this).addClass("active");
			$(".cars .tabcontent").hide();
			var activeTab = $(this).attr("href").replace("#", "");
			$('#tab_'+ activeTab).show();
			location.href="#"+ activeTab;
		}
	});
	
	$(".car-description .previews a").click(function(){
		$(".car-description .current").removeClass("current");
		$(this).parents("li").addClass("current");
		img_index = parseInt($(this).attr("class").replace("img", ""));
		$(".car-description .img-wrap .full-size a").attr("href", $(this).attr("href"));
		$(".car-description .img-wrap .full-size-img").attr("src", '/uploads/images/catalog/r3_' + $(this).attr("href").replace("/uploads\/images\/catalog/", ""));
		return false;
	});
	
	$(".car-description .img-wrap .full-size img").click(function(){
		jQuery.slimbox(img_array, img_index, {counterText: "Изображение {x} из {y}"});
		return false;
	});
	
	$(".editlink, .addauto a").click(function (){
		$(this).attr("href");
		returnlink = location.href;
		returnlink = returnlink.replace(/(http:\/\/(.*)\/)(catalog)(.*)/, "/$3$4");
		returnlink = escape(returnlink);
		location.href = $(this).attr("href") + "&returnlink=" + returnlink;
		return false;
	});
	$(".deletelink").click(function (){
		if (confirm('Вы, действительно, хотите удалить модель?')){
			$(this).attr("href");
			returnlink = location.href;
			returnlink = returnlink.replace(/(http:\/\/(.*)\/)(catalog)(.*)/, "/$3$4");
			returnlink = escape(returnlink);
			location.href = $(this).attr("href") + "&returnlink=" + returnlink;
		}
		return false;
	});
	
	if (window.location.hash){
		$(".cars .tabs-menu a[href="+ window.location.hash +"]").click();
	}
	
	$(".modification .info").each(function(){
		var info = this;
		$(".tab_content", info).hide();
		$("ul.tabs2 li:first a", info).addClass("active"); //Activate first tab
		$(".tab_content:first", info).show(); //Show first tab content

		//On Click Event
		$("ul.tabs2 li a", info).click(function() {

			$("ul.tabs2 li a", info).removeClass("active"); //Remove any "active" class
			$(this).addClass("active"); //Add "active" class to selected tab
			$(".tab_content", info).hide(); //Hide all tab content

			var activeTab = $(this).attr("href"); //Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); //Fade in the active ID content
			return false;
		});
	});
	
	$("#zakazform").submit(function() { 
                
		if($("#zakazform #name").val() == "" || $("#zakazform #name").val() == "Имя")   
			$("#form-result").html("Сообщите ваше имя!");
		
		else if($("#zakazform #phone1").val() == "" || $("#zakazform #phone1").val() == "Телефон")
			$("#form-result").html("Сообщите ваш телефон!");
			
		else if($("#zakazform #extra").val() == "" || $("#zakazform #extra").val() == "Сообщение")
			$("#form-result").html("Напишите ваше сообщение!");
			
		else 
		{
			$.post("/feedback?action=zakaz",
			{ brand: $("#zakazform input[name=brand]").val(),
			  model: $("#zakazform input[name=model]").val(),
			  name: $("#zakazform #name").val(), 
			  phone: $("#zakazform #phone1").val(),
			  mail: $("#zakazform #mail").val(),
			  extra: $("#zakazform #extra").val()
			},
				function(data){
					$("#form-result").html(data);
					$("#zakazform").get(0).reset();
			});
		}
		
		return false;
	});
	
	$.get('/feedback?action=getbrand', function(data) {
		$('#credit-form select[name=brand], .item_info .credit select[name=brand]').append(data);
		if (brand_id) {
			$('select[name=brand] option[value='+ brand_id +']').attr("selected", "selected");
			$('select[name=brand]').change();
		}
	});
	
	$('<select class="forms-08" name="brand"><option>Выберите марку</option></select>').replaceAll("#credit-form input[name=brand]");
	$('<select class="forms-08" name="model"></select>').replaceAll("#credit-form input[name=model]");
	$('<select class="forms-08" name="compl"></select>').replaceAll("#credit-form input[name=compl]");
	$('<select class="forms-08" name="price"></select>').replaceAll("#credit-form input[name=price]");
	
	$("select[name=brand]").change(function(){
		$("#credit-form select[name=model] option, .item_info .credit select[name=model] option").remove();
		$("select[name=compl] option").remove();
		$("select[name=price] option").remove();
		$.get('/feedback?action=getmodel&brand='+$("option:selected", this).val(), function(data) {
			$('#credit-form select[name=model]').append('<option>Выберите модель</option>');
			$('#credit-form select[name=model], .item_info .credit select[name=model]').append(data).show();
			if (model_id) {
				$('select[name=model] option[value='+ model_id +']').attr("selected", "selected");
				$('select[name=model]').change();
			}
		});
	});
	
	$("select[name=model]").change(function(){
		var model_select = $("option:selected", this).val();
		$("select[name=compl] option, select[name=price] option").remove();
		$.get('/feedback?action=getimg&model='+model_select, function(data) {
			$(".credit_img").html(data);
			$('.colors a:first').addClass('active');
		});
		$.get('/feedback?action=getcompl&model='+model_select, function(data) {
			$('select[name=compl]').append(data);
			
			$.get('/feedback?action=getprice&model='+model_select, function(data) {
				$('select[name=price]').append(data);
				$("input[name=cost]").val($("select[name=price] option:selected").html().replace(/ руб./, ''));
				if (compl_id) {
					$('select[name=compl] option[value='+ compl_id +']').attr("selected", "selected");
					$('select[name=compl]').change();
				}
				calcstav();
				calculate();
			});
		});
		
	});
	
	$("select[name=compl]").change(function(){
		$("select[name=price]").val($(this).val());
		$("input[name=cost]").val($("select[name=price] option:selected").html().replace(/ руб./, ''));
		calcstav();
		calculate();
	});
	
	$("select[name=price]").change(function(){
		$("select[name=compl]").val($(this).val());
		$("input[name=cost]").val($("select[name=price] option:selected").html().replace(/ руб./, ''));
		calcstav();
		calculate();
	});
	
	$("input[name=bithday]").mask("99/99/9999");
	$("input[name=phone], input[name=work_phone]").mask("(999) 999-9999");
	
	$(".chkday").change(function(){
		if ($(".chkday:checked").length == 7){
			$("#anyday").attr("checked", true);
			$(".chkday").attr("disabled", "disabled");
		} else
			$("#anyday").attr("checked", false);
	});
	
	$("#anyday").change(function(){
		if ($(this).attr("checked") == true){
			$(".chkday").attr("checked", true);
			$(".chkday").attr("disabled", "disabled");
		} else {
			$(".chkday").removeAttr("disabled");
			$(".chkday").attr("checked", false);
		}
	});
	
	if (anyday){
		$("#anyday").attr("checked", true);
		$("#anyday").change();
	}
	
	$("#anytime").change(function(){
		if ($(this).attr("checked") == true){
			$("#st, #fn").attr("disabled", "disabled");
		} else {
			$("#st, #fn").removeAttr("disabled");
		}
	});
	
	if (anytime){
		$("#anytime").attr("checked", true);
		$("#anytime").change();
	}
	
	$("#credit-form").submit(function() {
		var str="";
		if ($("#mon").is(":checked")) {
			str+="Пн,"
		} 
		if ($("#tue").is(":checked")) {
			str+="Вт,"
		}
		if ($("#web").is(":checked")) {
			str+="Ср,"
		}
		if ($("#thu").is(":checked")) {
			str+="Чт,"
		}
		if ($("#fri").is(":checked")) {
			str+="Пт,"
		}
		if ($("#sat").is(":checked")) {
			str+="Сб,"
		}
		if ($("#sun").is(":checked")) {
			str+="Вс,"
		}
		str = str.substr(0,str.length-1);
		str+=";";
		if ($("#anytime:checked").length)
			str+='любое время';
		else	
			str+=$("#st").val()+"-"+$("#fn").val();
		$("#calltime").val(str);
		
		$("#credit-form input[name=brand_id]").val($("#credit-form select[name=brand] option:selected").val());
		$("#credit-form input[name=model_id]").val($("#credit-form select[name=model] option:selected").val());
		$("#credit-form input[name=compl_id]").val($("#credit-form select[name=compl] option:selected").val());
		$("#credit-form select[name=brand] option:selected").val($("#credit-form select[name=brand] option:selected").html());
		$("#credit-form select[name=model] option:selected").val($("#credit-form select[name=model] option:selected").html());
		$("#credit-form select[name=compl] option:selected").val($("#credit-form select[name=compl] option:selected").html());
		$("#credit-form select[name=price] option:selected").val($("#credit-form select[name=price] option:selected").html());
		return true;
	});
	
	$(".credit form").submit(function() {
		$(".credit form input[name=brand_id]").val($(".credit form select[name=brand] option:selected").val());
		$(".credit form input[name=model_id]").val($(".credit form select[name=model] option:selected").val());
		$(".credit form input[name=compl_id]").val($(".credit form select[name=compl] option:selected").val());
		
		return true;
	});
	
	//$("#tabs").tabs();
	$("#feedbackform").submit(function() { 
                
		if($("#feedbackform #name").val() == "" || $("#feedbackform #name").val() == "Имя")   
			$("#div-feedbackform").html("Сообщите ваше имя!");
		
		else if($("#feedbackform #phone1").val() == "" || $("#feedbackform #phone1").val() == "Телефон")
			$("#div-feedbackform").html("Сообщите ваш телефон!");
			
		else if($("#feedbackform #extra").val() == "" || $("#feedbackform #extra").val() == "Сообщение")
			$("#div-feedbackform").html("Напишите ваше сообщение!");
			
		else 
		{
			$.post("/feedback?action=feedback",
			{ name: $("#feedbackform #name").val(), 
			  phone: $("#feedbackform #phone1").val(),
			  mail: $("#feedbackform #mail").val(),
			  extra: $("#feedbackform #extra").val()
			},
				function(data){
					$("#div-feedbackform").html(data);
			});
		}
		
		return false;
	});
});

function creditform(){
	$('#popup_div').togglePopup({ajaxurl: '/ajax?action=creditform', width: 700, height: 540, iframe: true});
}

$.fn.placeholder = function(){
	this.each(function(){
		$(this).attr('defaultvalue',$(this).val()).focus(function(){
			if($(this).val() == $(this).attr('defaultvalue'))
				$(this).val('');
		}).blur(function(){
			if($(this).val() == '')
				$(this).val($(this).attr('defaultvalue'));
		});
	});
}

$.fn.pie = function(a){
	if (window.PIE && $.browser.msie && base.pie) {
		if(a === 'remove')
		{
			this.each(function() {
				PIE.detach(this);
			});
		} else
		{
			this.each(function() {
				PIE.attach(this);
			});
		}
	}
	return this;
}

function overlay(act){
	var overlay = $('#blackout');
	if(act === 'hide'){
		overlay.hide();
		return false;
	}
	if(!overlay.length)
	{
		$('<div id="blackout" class="blackout"></div>').appendTo('body');
		overlay = $('#blackout');
	}
	overlay.css({height:$('body').height(),opacity:0.5}).show();
}

function isNumberKey(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;

	return true;
}

function No_telephone()
{
	if (this.document.getElementById('no_home_tel').checked)
		{
		this.document.getElementById('home_tel').style.visibility = "hidden";
		this.document.getElementById('home_tel_value').value = "Нет";
		}
	else
		{
		this.document.getElementById('home_tel').style.visibility = "visible";
		this.document.getElementById('home_tel_value').value = "";
		}
}
function PercentCost() 
{
	if (document.getElementById('Cost').value!="" && document.getElementById('Fpayment').value!="")
		{
		//document.getElementById('Percent').value="X";
		document.getElementById('Percent').value=Math.round(document.getElementById('Fpayment').value/document.getElementById('Cost').value*100);
		}
	else
		document.getElementById('Percent').value="--";
};

function PopUp(url, name, width,height,center,posleft,postop)
{
	showx = "";
	showy = "";
	
	if (posleft != 0) { X = posleft; }
	if (postop  != 0) { Y = postop  }
	
	if ((parseInt (navigator.appVersion) >= 4 ) && (center))
	{
		X = (screen.width  - width ) / 2;
		Y = (screen.height - height) / 2;
	}
	
	if (posleft == 0)
	{
		X = (screen.width  - width ) / 2;
	}	
	if ( X > 0 )
	{
		showx = ',left='+X;
	}

	if(postop  == 0)
	{
		Y = (screen.height - height) / 2;
	}	
	if ( Y > 0 )
	{
		showy = ',top='+Y;
	}
	
	Win = window.open( url, name, 'width='+width+',height='+height+ showx + showy + ',resizable=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no');
	return Win;
}

function em(box, server, zone, img)
{
 var at = String.fromCharCode(64);
 if (img == 1)
 	return '<a href="'+'mai'+'lto'+':'+box+at+server+'.'+zone+'">';
 else
 	return '<a href="'+'mai'+'lto'+':'+box+at+server+'.'+zone+'">'+box+at+server+'.'+zone+'<'+'/a>';
}

function calculate()
{
	var firstpay = $("input[name=firstpay]");
	var cost = $("input[name=cost]");
	var month = $("input[name=month]");
	
	if (cost.val() == 0){
		firstpay.val(0);
		return;
	}
	
	if (firstpay.val() < 1000){
		return;
	}
	
	if ( firstpay.val()*100/cost.val() > 70) {
		firstpay.val(cost.val()*70/100);
		$(".firstpay_err").html('Сумма первоначального взноса не может превышать 70% от стоимости автомобиля');
		return;
	}
	$(".firstpay_err").html('');
	firstpersent = Math.round(firstpay.val()*100/cost.val());
	var sum = cost.val()*(1-firstpersent/100);
	var pc = 8;
	
	$("input[name=monthpay]").val(Math.round((sum*pc/1200)/(1-Math.pow(1/(1+pc/1200), month.val()))));
}

function calc2()
{	
	var firstpay = $("input[name=firstpay]");
	var monthpay = $("input[name=monthpay]");
	var month = $("input[name=month]");
	var cost = $("input[name=cost]");
	var stav = $("input[name=stav]");
	
	if (isNaN(parseInt(firstpay.val())) || parseInt(firstpay.val())>trprice()) return;
	
	if (!isNaN(parseInt(monthpay.val()))){
		c=parseInt(cost.val());
		if(isNaN(c)){
			c=0;
		} 
		p=parseInt(firstpay.val());
		if (isNaN(p)){
			p=0;
		}
		s=parseFloat(stav.val()) 
		if (isNaN(s)){
			s=0;
		}
		s/=100;
		m=parseInt(monthpay.val());
		if (isNaN(m)){
			m=0;
		}
		
		t=(12*c-12*p)/(12*m+p*s-c*s);
		t=t.toFixed();
		month.val(t);
		$('#slider-range-min').slider('value', t);
	} else if (!isNaN(parseInt(month.val()))){
		c=parseInt(cost.val());
		if(isNaN(c)){
			c=0;
		} 
		t=parseInt(month.val());
		if (isNaN(t)){
			t=0;
		}
		s=parseFloat(stav.val()) 
		if (isNaN(s)){
			s=0;
		}
		s/=100;
		p=parseInt(firstpay.val());
		if (isNaN(p)){
			p=0;
		}
		
		m=((c-p)*(s*t+12))/(12*t);  
		m=m.toFixed();
		monthpay.val(m);
	}
}

function calcstav() {
	var firstpay = $("input[name=firstpay]");
	var cost = $("input[name=cost]");
	var stav = $("input[name=stav]");
	
	pr = parseInt(cost.val());
	if(isNaN(pr)){
		pr=0;
	} 
	fp=parseInt(firstpay.val());
	if (isNaN(fp)){
		fp=0;
	}
	it=pr-fp;
	if (it<300000)
		stav.val("5.5");
	else if (it>=300000 && it<700000)
		stav.val("4.7");
	else if (it>=700000 && it<1500000)
		stav.val("4.2");
	else if (it>=1500000 && it<2000000)
		stav.val("3.7");
	else if (it>=2000000 && it<2500000)
		stav.val("3.2");
	else if (it>=2500000)
		stav.val("0");
}

calcstav();

function trprice()
{
	return parseInt($('input[name=cost]').val())*0.7;
}
