jQuery.fn.activeItemMenu = function(userOptions) {
	var options = {
		linkClassActive: "active",
		levelURL: 2
	}
	$.extend(options,userOptions);	
	var hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/');
	$('a',$(this)).each(function(){
    	var href = $(this).attr('href');		
		href = href.split('/');		
        if (href[options.levelURL-1] == hashes[options.levelURL]) {
            if(hashes.length > 3) $(this).addClass(options.linkClassActive);
        }
    });
}

/* Кредит */
  function fix_model(){
	  if($("#mark_field").css('display')!='none'){
		  var val = $('#mark_field').val();
		  $('.models select').hide().attr("name","none");
		  $('#model_field'+val).show().attr("name","order[model_id]");
	  }
  }
  function validate(){
	  ["fio", "phone", "email",""]
	  if(($('#order_fio').attr('value').length < 5) || ($('#order_phone').attr('value').length < 5) || ($('#order_email').attr('value').length < 3)){
		  alert('Поля «Ф. И. О.», «Номер телефона» и «Адрес эл. почты» обязательны для заполнения');
		  return false;
	  } else if(!$("#order_phone").attr('value').match(/^\+?(\d+[\- ]?)([- ]?\(\d+\)[- ]?)?(\d+[\- ]?)+\d$/)){
		  alert('Неверный формат поля «Номер телефона». Попробуйте ввести телефон в формате 123-456 или 8-(0123)-456-78-90');
		  return false;
	  } else if(!$("#order_email").attr('value').match(/^\S+@\S+\.\S+.$/)){
		  alert('Неверный формат поля «Адрес эл. почты»');
	  return false;
	}
	setTimeout(function(){$("#order_submit").attr("disabled","true")},10);
	return true;
  }
  
  function fix_model(){
	  if($("#mark_field").css('display')!='none'){
		  var val = $('#mark_field').val();
		  $('.models select').hide().attr("name","none");
		  $('#model_field'+val).show().attr("name","order[model_id]");
	  }
  }
  
  $(fix_model());
  
  function fix_complect(){
	  var model = $('#model_field'+$('#mark_field').val()).val();
	  if(model) $("#complects").load("/credit/complects/" + model + '/');
  }			
  $(fix_complect());
  
  if(navigator.userAgent.match(/MSIE 6/)){
	  $(function(){$(".menu_item").mouseout(function(){setTimeout(fix_model, 100)}) })
  }
/* Конец Кредит */

$(function() {
		   
	// Поиск в шапке
	$('#search a').bind('click',function() {
		var text_search = $('#search .text').val();
		if((text_search.length == 0) || (text_search == 'поиск')){
			alert('Необходимо заполнить поле поиска!');
			return false;
		}
		else if((text_search.length < 3) && (text_search != 'поиск')){
			alert('Запрос должен содержать не менее 3 символов!');
			return false;
		} else {			
			$('#search').submit();
			return false;
		}		
	});
	
	// Заголовки
	Cufon.replace('#cityMainList div.salon_item_inner div.markCity a, #cityMainList div.salon_item div.font12 a, .sheme a, .shemeRight a, #cityLogo td a, #marksLogo td a, p.copy, .header_marks, .header_marks2, #pts, .itemSearchAjax h2 a, .header_text, .action_item h3 a, #action_table td.w50 table td.actionReview h1, h1.header_city, #content_inner .header_vacancies, #content_inner h1.header_city_list, #cityMainList div.salon_item_inner h2, h1.header_city2, .headerCity, .header', {hover:true});
	Cufon.replace('.SiteLink a');
	Cufon.now();
	
	$('#flash .map').flash({src:'/t/i/menu/map_main_w.swf',width:670,height:370,menu:false,wmode:'opaque'});
	$('#flash .menu, #flash_inner .menu').flash({src:'/t/i/menu/menu_mark.swf',width:906,height:65,menu:false,wmode:'opaque'});
			
	// Меню (активные разделы)
	$("#menu").activeItemMenu({levelURL:2});
	$("#menu > li").hover(function(){
		$(this).children("a").addClass("active");
		$(this).find("ul").show();
	},function(){
		$(this).children("a").removeClass("active");
		$(this).find("ul").hide();
	});
	
	$(".new_responce").live("click",function() {$("#form").toggle("slide")});
	
	/* Оформление таблиц */
	$(".stextStyle tbody tr:even, .btextModel tr:even").addClass('even');
	$(".tablesorter").tablesorter({headers:{6:{sorter:false}},widgets:['zebra']});

	/* Галерея */
	$("#galleryVidjet .menuGal a:eq(0)").addClass("act");
	$("#galleryVidjet .menuGal a").live("click",function(){
		var href = $(this).attr("href");
		
		$("#galleryVidjet .slideGal img").animate({opacity:0},400);
		
		$("#galleryVidjet .menuGal a").removeClass("act");
		$(this).addClass("act");
		$("#galleryVidjet .slideGal img").animate({opacity:1},400)
		setTimeout(function(){
			$("#galleryVidjet .slideGal img").attr("src",href);
		},400);		
		return false;
	});
	
 	$(".saleCart a").live("click",function(){
		if($(this).attr('class')!='mergeBg'){
			var mod = $(this).attr('mod');
			$(this).addClass('mergeBg');		
		} else {
			var mod = $(this).attr('mod');
			$(this).removeClass('mergeBg');	
		}		
		$.post(window.location.protocol+'//'+window.location.host+"/mod/ajax/curt.backend.php",{mod:mod},function(data){
			$(".countCurt").html(data);																						   
		});	
	});
	
	$("a[@class=addNote] ins").live("click",function(){
		if($(this).attr('class')!='mergeBg'){
			var mod = $(this).attr('mod');
			$(this).addClass('mergeBg');		
		} else {
			var mod = $(this).attr('mod');
			$(this).removeClass('mergeBg');	
		}		
		$.post(window.location.protocol+'//'+window.location.host+"/mod/ajax/curt.backend.php",{mod:mod},function(data){
			$(".countCurt").html(data);																						   
		});	
	});	
	
	 $("a.delAllCurt").click(function(){		
		var ans = confirm("Удалить все автомобили из гаража?");
		if(ans){
			$(".contentCurt").animate({opacity:'.3'},300);
			setTimeout(function(){		
				$.post(window.location.protocol+'//'+window.location.host+"/mod/ajax/curt.backend.php",{del:"all"},function(data){
					$(".contentCurt").html(data);	
					$(".countCurt").html('0');
					$(".contentCurt").css({opacity:"1"});
					scroll(0,0);
				});
			},2000);			
		} else return false;
	});
	 
	/* Trade IN */
	$("#brand").change(function(){
		$("#brand option:selected").each(function() {
			if($(this).val() != '') {
				$("#model").html('<option value="">Зазрузка</option>');
				$.post("/ajax/tradein.backend.php",{id:$(this).val()},function(data){
					$("#model").html(data);
				});
			}
		});
    });
	
	$(".check_tradein").bind("submit",function(){
		var error = 0;
		var idelemcheck = [
			'brand',
			'model',
			'probeg',
			'color',
			'obem',
			'worth',
			'fio',
			'phone',
			'email',
			'comment'
		];
		for(i=0;i<idelemcheck.length;i++) {
			if($("#"+idelemcheck[i]).val().length == 0) {
				alert("Ошибка! Необходимо заполнить все поля помеченные звездочкой!");
				$("#"+idelemcheck[i]).focus();
				error++;
				break;
				return false;
			}
		}		
		if(error == 0) {
			$(".check_tradein").submit();
		} else {
			return false;	
		}
	});	
	
	/* record_maintenance_and_repair */
	$("#brand_2").change(function(){
		$("#brand_2 option:selected").each(function(){if($(this).val()!=''){$("#model_2").html('<option value="">Зазрузка</option>');$.post("/ajax/record_maintenance_and_repair.backend.php",{id:$(this).val()},function(data){$("#model_2").html(data)});}});
    });
	
	$(".check_record_maintenance_and_repair").bind("submit",function(){
		var error = 0;
		var idelemcheck = [
			'brand_2',
			'model_2',
			'numvin',
			'city',
			'datetime',
			'fio',
			'phone',
			'comment'
		];
		for(i=0;i<idelemcheck.length;i++) {
			if($("#"+idelemcheck[i]).val().length == 0) {
				alert("Ошибка! Необходимо заполнить все поля помеченные звездочкой!");
				$("#"+idelemcheck[i]).focus();
				error++;
				break;
				return false;
			}
		}
		if(error == 0) {
			$(".check_record_maintenance_and_repair").submit();
		} else {
			return false;
		}
	});
	$("#pts tr").hover(function(){$(this).addClass("active")},function(){$(this).removeClass("active")});
								
});