$(document).ready(function(){
	/* new header */
	function debug(name) {$("#debug").text(name)};
	var globalWidth = 0;

	var menuNum = $("#mTabs a").length;
	var menuBase = 0;
	var menuCurrent = 0;
	
	var tabs_array = [];
	var int_array = [];
	var goBack;
	
	var leftPos = 0;
	
	$(window).load(function(){
		for(var i = 0; i < menuNum; i++) {
			tabs_array.push(parseInt($("#tab" + i).width()));
			int_array.push(parseInt($("#int" + i).width()));
		}
		showMenu();
	});
	

	
	for(var i = 0; i < menuNum; i++) {
		var g = $("#tab" + i).hasClass("on");
		if(g === true) {
			menuBase = i;
			menuCurrent = i;
		};
	}
	
	var dID = menuCurrent;
	function showMenu() {
		leftPos = 0;
		$("#tab" + menuCurrent).removeClass("on");
		$("#int" + menuCurrent).removeClass("show");

		menuCurrent = dID;
		
		$("#tab" + menuCurrent).addClass("on");
		$("#int" + menuCurrent).addClass("show");
		
		for(var i = 0; i < menuCurrent; i++) {
			leftPos = leftPos + $("#tab" + i).width();
			if(i > 0) {leftPos = leftPos - 0 + 1};
		}
		
		var g = tabs_array[menuCurrent];
		var gg = int_array[menuCurrent];
		g = Math.round(g / 2);
		gg = Math.round(gg / 2);
		leftPos = leftPos - 0 + g - gg;
		if(leftPos < 0) {leftPos = 0};
		if(leftPos - 0 + int_array[menuCurrent] > $("#mw").width()) {
			leftPos = $("#mw").width() - int_array[menuCurrent] - 2;
		}
		
		$("#int" + menuCurrent).css("left", leftPos);
	}
	
	for(var i = 0; i < menuNum; i++) {
		$("#tab" + i).focus(function(){$(this).blur(0)});

		$("#tab" + i).hover(
			function(){
				time = 0;
				clearInterval(goBack);
				dID = this.id.toString().slice(3) - 0;

				showMenu();
			},
			function(){
				goBack = setInterval(timer, 200);
			}
		);
		
		$("#int" + i).hover(
			function(){
				time = 0;
				clearInterval(goBack);
			},
			function(){
				goBack = setInterval(timer, 200);
			}
		);
	};
	
	var time = 0;
	function timer() {
		if(time < 5) {
			time++;
		} else {
			clearInterval(goBack);
			time = 0;
			dID = menuBase;
			showMenu();
		}
	}
	
	
	// --------------------------
	$(window).resize(function() {
		resizeMe();
		showMenu();
	});
	
	function resizeMe() {
		tabsWidth = 0;
		globalWidth = 240 - (1200 - $("#mw").width());
		globalWidth = Math.round(globalWidth / 14);
		var r = parseInt(7 + globalWidth);
		if(r > 24) {r = 24};
		for(var i = 0; i < menuNum; i++) {
			$("#tab" + i + " span").css("padding-left",r).css("padding-right",r);
			tabsWidth = tabsWidth + $("#tab" + i).width() + 1;
		}
	};
	resizeMe();
	
	$(document).ready(function(){
		for(var i = 0; i < menuNum; i++) {
			tabs_array.push(parseInt($("#tab" + i).width()));
			int_array.push(parseInt($("#int" + i).width()));
		}
		showMenu();
	});
	
	// add car script 19.11.2009 by IonDen
	$("div.fBlock a").focus(
		function(){
			$(this).blur(0);
		}
	);
	
	for(var i = 0; i < 3; i++) {
		if(i !== 0) {
			$("#fbc" + i).slideUp(5);
			$("#fb" + i).addClass("fbNone");
		};
	};
	
	$("#next0").click(
		function(){
			if (checkForm() == 0) {
				window.scrollTo(0,200);
				var curMenuUp = 1;
				$("#fbc" + 0).slideUp(500);
				$("#fbc" + 1).slideDown(500);
				$("#fb" + 1).removeClass("fbNone");
				$("#fb" + 0).addClass("fbOff");
				
				var mark = $('#marka').attr('value');
				if (mark == '120' || mark == '91' || mark == '92' || mark == '93' || mark == '94' || mark == '95' || mark == '97' || mark == '98') {
					$('#showMetal').attr('checked', false);
					$(".color").removeClass("metal");
				}
				
			} else {
				alert('Необходимо заполнить обязательные поля.');
			}
		}
	);
	$("#next1").click(
		function(){
			var flag = checkColor();
			if (flag == 0) {
				$("#fbc" + 1).slideUp(500);
				$("#fbc" + 2).slideDown(500);
				$("#fb" + 2).removeClass("fbNone");
				$("#fb" + 1).addClass("fbOff");
			} else {
				$('#colorError').html('<img src="/img/ico/ico-alert.gif" align="absmiddle"> необходимо выбрать цвет.');
				$('#colorError').show();
			}
		}
	);
	$("#fb0").click(
		function(){
			$("#fbc" + 0).slideDown(500);
			$("#fbc" + 1).slideUp(500);
			$("#fbc" + 2).slideUp(500);
			$("#fb" + 0).removeClass("fbNone").removeClass("fbOff");
			$("#fb" + 1).addClass("fbNone").removeClass("fbOff");
			$("#fb" + 2).addClass("fbNone").removeClass("fbOff");
		}
	);
	$("#fb1").click(
		function(){
			if (checkForm() == 0) {
				var curMenuUp = 1;

				$("#fbc" + 1).slideDown(500);
				$("#fbc" + 0).slideUp(500);
				$("#fbc" + 2).slideUp(500);
				$("#fb" + 0).addClass("fbOff");
				$("#fb" + 1).removeClass("fbNone").removeClass("fbOff");
				$("#fb" + 2).addClass("fbNone").removeClass("fbOff");
				
				var mark = $('#marka').attr('value');
				if (mark == '120' || mark == '91' || mark == '92' || mark == '93' || mark == '94' || mark == '95' || mark == '97' || mark == '98') {
					$('#showMetal').attr('checked', false);
					$(".color").removeClass("metal");
				}
				window.scrollTo(0,200);
			} else {
				alert('Необходимо заполнить обязательные поля.');
			}
		}
	);
	$("#fb2").click(
		function(){
			if (checkForm() == 0) {
				var flag = checkColor();
				if (flag == 0) {
					var curMenuUp = 2;
					$("#fbc" + 2).slideDown(500);
					$("#fbc" + 0).slideUp(500);
					$("#fbc" + 1).slideUp(500);
					$("#fb" + 0).addClass("fbOff");
					$("#fb" + 1).addClass("fbOff").removeClass("fbNone");
					$("#fb" + 2).removeClass("fbNone").removeClass("fbOff");
				} else {
					$('#colorError').html('<img src="/img/ico/ico-alert.gif" align="absmiddle"> необходимо выбрать цвет.');
					$('#colorError').show();
				}
			} else {
				alert('Необходимо заполнить обязательные поля.');
			}
		}
	);
	
	var details = false;
	$("#details").slideUp(5);
	
	$("#showDetails").change(
		function(){
			if(details === false) {
				details = true;
				$("#details").slideDown(800);
			} else {
				details = false;
				$("#details").slideUp(800);
			}
		}
	);
	
	var metallic = true;
	
	$("#showMetal").change(
		function(){
			if(metallic === true) {
				metallic = false;
				$(".color").removeClass("metal");
				$(".color").addClass("nometal");
			} else {
				metallic = true;
				$(".color").removeClass("nometal");
				$(".color").addClass("metal");
			}
		}
	);
	
	var colorNum = $(".colors td").length;
	
	for(var i = 0; i < colorNum; i++) {
		$("#fcr" + i).hover(
			function(){
				$(this).addClass("fHover");
			},
			function(){
				$(this).removeClass("fHover");
			}
		);
		
		$("#fcr" + i).click(
			function(){
				for(var z = 0; z < colorNum; z++) {
					$("#fcr" + z).removeClass("fOn");
				}
				$(this).addClass("fOn");
			}
		);
	};
	
	var photosNum = $(".fph div").length - 1;
	for(var i = 0; i < photosNum; i++) {
		$("#photo" + i).hover(
			function(){
				$(this).addClass("fpHover");
			},
			function(){
				$(this).removeClass("fpHover");
			}
		);
	};
	
    /* 23.12.2009
     * Informer JQ only
     * by IonDen
     */
 
    var infCurrent = 0;
	
	for(var i = 0; i < 4; i++) {
		$("#infTit" + i).hover(
			function(){
				infCurrent = parseInt(this.id.charAt(6));
				roll();
			}
		);
	}
	
	function roll() {
		for(var i = 0; i < 4; i++) {
			$("#infCont" + i).stop();
			if(i !== infCurrent) {
				$("#infCont" + i).animate({height:30},400);
				$("#infCont" + i).addClass("infClosed");
				$("#infCont" + i).removeClass("infOpend");
			} else {
				$("#infCont" + infCurrent).animate({height:323},400);
				$("#infCont" + i).removeClass("infClosed");
				$("#infCont" + i).addClass("infOpend");
			}
			
		}
	}
	
	var is_height = [];
	var scrCurrent = 0;
	var scrInt;
	var zTop_array = [0,0,0,0];
	var zTop = 0;
	
	for(var i = 0; i < 4; i++) {
		is_height.push($("#is" + i + " div").height());
	}
	
	for(var i = 0; i < 4; i++) {
		$("#is" + i + " .scrollUp").hover(
			function(){
				scrCurrent = this.id.charAt(2);
				scrInt = setInterval(moveUp, 10);
			},
			function(){
				clearInterval(scrInt);
			}
		);
		$("#is" + i + " .scrollDown").hover(
			function(){
				scrCurrent = this.id.charAt(2);
				scrInt = setInterval(moveDown, 10);
			},
			function(){
				clearInterval(scrInt);
			}
		);
	}
	
	function moveUp() {
		if(is_height[scrCurrent] > 292 && zTop < 0) {
			zTop = zTop_array[scrCurrent];
			zTop = zTop + 5;
			zTop_array[scrCurrent] = zTop;
			$("#is" + scrCurrent + " div").css("top", parseInt(zTop_array[scrCurrent]));
		}
	}
	function moveDown() {
		if(is_height[scrCurrent] > 292 && zTop > 292 - is_height[scrCurrent]) {
			zTop = zTop_array[scrCurrent];
			zTop = zTop - 5;
			zTop_array[scrCurrent] = zTop;
			$("#is" + scrCurrent + " div").css("top", parseInt(zTop_array[scrCurrent]));
		}
	}
});

/* -------------------------------------------------------------------------------------------
 * Advansed Car Search
 * 21.06.2010
 * by IonDen
 */

(function($){
    $.fn.set_acs = function(options) {
        // base part
		var defaults = {
			state : true,
			show : true
		};
        var options = $.extend(defaults, options);
		if(options.state === false) {
			$("#acs_base").hide();
			change_top(0);
		} else {
			$("#acs_base").show();
			change_top(1);
		}
		
		$("#acs_hide").click(function(event){
			event.preventDefault();
			
			if(options.state === true) {
				options.state = false;
				$("#acs_base").fadeOut(400);
				change_top(0);
			} else {
				options.state = true;
				$("#acs_base").fadeIn(400);
				change_top(1);
			}
		});
		
		function change_top(num) {
			if(num === 0) {
				$("#acs_hide i").hide();
				$("#acs_hide em").show();
			} else {
				$("#acs_hide i").show();
				$("#acs_hide em").hide();
			}
		}
		
		// work part
		var what_cars = 0; // все (0), только новые(1), только подержанные (2)
		var city_name = "";
		var city_id = "";
		
		// переключаем диапазон машин
		$("#acs_switcher > a").click(function(event){
			event.preventDefault();
			$("#acs_switcher > a").removeClass("on");
			$(this).addClass("on");
			var temp_id = $(this).attr("id");
			what_cars = parseInt(temp_id.slice(3));
		});
		
		// меняем город поиска
		var raw_cities = "";
		var end_cities = "";
		var acs_hover = false;
		var acs_hover_2 = false;
		var acs_off = 0;
		var acs_cities_opend = false;
		
		$("#acs_change_city > li > a").hover(
			function() {
				acs_hover_2 = true;
			},
			function() {
				acs_hover_2 = false;
			}
		);
		
		$("#acs_change_city > li > a").click(function(event) {
			event.preventDefault();

			if(acs_cities_opend === false) {
				acs_cities_opend = true;
				
				raw_cities = $(this).parent().find("ul").html();
				acs_off = $(this).offset();
				
				end_cities = '<div class="acs_popup" id="ch_city"><ul>';
				end_cities += raw_cities;
				end_cities += '</ul></div>';
				
				$("body").append(end_cities);
				
				$("#ch_city").css("left", acs_off.left - 180).css("top", acs_off.top - 40);
				
				$("div.acs_popup").hover(
					function() {
						acs_hover = true;
					},
					function() {
						acs_hover = false;
					}
				);
				
				if(navigator.userAgent.indexOf("MSIE 6.0") !== -1) {
					$("select").css("visibility", "hidden");
				};
				
				$("#ch_city a").click(function(event) {
					event.preventDefault();
					city_name = $(this).text();
					city_id = $(this).attr("id");
					city_real_id = city_id.replace('city_id_', '');
					$('#gorod').attr('value', city_real_id);
					$("#acs_city > b").text(city_name);
					acs_hover = false;
					hide_acs_popup();
				});
				
				$(document.body).mousedown(function() {
					if(acs_hover_2 === false) {
						hide_acs_popup();
					}
				});
			} else {
				hide_acs_popup();
			}
		});
		
		function hide_acs_popup() {
			if(acs_hover === false) {
				$("div.acs_popup").remove();
				$("#acs_marks").hide();
				
				acs_cities_opend = false;
				acs_marks_opend = false;
				
				if(navigator.userAgent.indexOf("MSIE 6.0") !== -1) {
					$("select").css("visibility", "visible");
				};
			}
		}
		
		// открываем/закрываем произвольные блоки
		if(options.show === true) {
			$("div.acs_inf").show();
			$("div.acs_hide").removeClass("acs_show").addClass("acs_hide");
		} else {
			$("div.acs_inf").hide();
			$("div.acs_hide").removeClass("acs_hide").addClass("acs_show");
		}
		
		$("div.acs_hide > a").live("click",function(event) {
			event.preventDefault();
			$(this).parent().parent().find("div.acs_inf").slideUp(300);
			$(this).parent().removeClass("acs_hide").addClass("acs_show");
		});
		$("div.acs_show > a").live("click",function(event) {
			event.preventDefault();
			$(this).parent().parent().find("div.acs_inf").slideDown(300);
			$(this).parent().removeClass("acs_show").addClass("acs_hide");
		});
		
		// очищаем форму поиска (при желании тут можно написать свою логику)
		$("#acs_clear").click(function(event) {
			event.preventDefault();
			
			$("div.acs_inf input:checkbox").removeAttr("checked");
			$("div.acs_inf input:text").attr("value","");
			$("#acs_marks input:checkbox").removeAttr("checked");
			
			$("#acs_switcher > a").removeClass("on");
			$("#sw_0").addClass("on");
		});
		
		// показываем попапчик с остатком
		var dp_off_1 = 0;
		var dp_off_2 = 0;
		
		
		$("#acs_base label").live("mouseup",function() {
			dp_off_1 = $(this).parent().offset();
			dp_off_2 = $(this).parent().parent().offset();
			//if ($(this).children().attr('checked') == false) {
		       $("body").oneTime("0.2s", function() {
			     show_smpop();
			   });
			//}
		});
		
		
		$('.but_bb').live('click', function() {
		  show_smpop(1);
		});
		
		$('.but_aa').live('click', function() {
		  show_smpop(1);
		});
		
		var end_smpop = "";
		function show_smpop(flfl) {

			var last_num    = 0;
			var city  	    = $('#city').attr('value');
			var price_from  = $('#price_from').attr('value');
			var price_to    = $('#price_to').attr('value');
			var qsa   	    = '';
			var photo 		= $('#photo').attr('checked');
			var year_s 		= $('#year_s').attr('value');
			var year_f 		= $('#year_f').attr('value');
			var volume_from	= $('#volume_from').attr('value');
			var volume_to	= $('#volume_to').attr('value');
			var probeg	    = $('#probeg').attr('value');;
			
			if (photo == true) {
				photo = 'on';	
			} else {
				photo = 'off';
			}
			

				
			var marks_ids 		= '';
			var kuzov_ids 		= '';
			var gearbox_ids 	= '';
			var wheel_ids   	= '';
			var engine_type_ids = '';

			$('input').attr('rel', 'marks_lbl').each(function(table){
				if ($(this).attr('rel') == 'marks_lbl') {
			   		if ($(this).attr('id').indexOf('marks_') != -1) {
			   			if ( $(this).attr('checked') == true ) {
			   				splm = $(this).attr('id').split('_');
			   				marks_ids += splm[1]+':';
			   			}
			   		}
				}
			});
			
			marks_ids = marks_ids.substring(0, (marks_ids.length-1));
			
			
			
			
			$('input').attr('rel', 'kuzov_lbl').each(function(table){
				if ($(this).attr('rel') == 'kuzov_lbl') {
			   		if ($(this).attr('id').indexOf('kuzov_') != -1) {
			   			if ( $(this).attr('checked') == true ) {
			   				splm = $(this).attr('id').split('_');
			   				kuzov_ids += splm[1]+':';
			   			}
			   		}
				}
			});
			 
			kuzov_ids = kuzov_ids.substring(0, (kuzov_ids.length-1));
			
			
			
			$('input').attr('rel', 'gearbox_lbl').each(function(table){
				if ($(this).attr('rel') == 'gearbox_lbl') {
			   		if ($(this).attr('id').indexOf('gearbox_') != -1) {
			   			if ( $(this).attr('checked') == true ) {
			   				splm = $(this).attr('id').split('_');
			   				gearbox_ids += splm[1]+':';
			   			}
			   		}
				}
			});

			gearbox_ids = gearbox_ids.substring(0, (gearbox_ids.length-1));
			
			
			
			
			$('input').attr('rel', 'engine_type_lbl').each(function(table){
				if ($(this).attr('rel') == 'engine_type_lbl') {
			   		if ($(this).attr('id').indexOf('enginetype_') != -1) {
			   			if ( $(this).attr('checked') == true ) {
			   				splm = $(this).attr('id').split('_');
			   				engine_type_ids += splm[1]+':';
			   			}
			   		}
				}
			});
		
			engine_type_ids = engine_type_ids.substring(0, (engine_type_ids.length-1));
			
			
			
			
			$('input').attr('rel', 'wheel_lbl').each(function(table){
				if ($(this).attr('rel') == 'wheel_lbl') {
			   		if ($(this).attr('id').indexOf('wheel_') != -1) {
			   			if ( $(this).attr('checked') == true ) {
			   				splm = $(this).attr('id').split('_');
			   				wheel_ids += splm[1]+':';
			   			}
			   		}
				}
			});
			 
			wheel_ids = wheel_ids.substring(0, (wheel_ids.length-1));
			
				
			qsa = 'type=carsCount&city='+city+'&price_from='+price_from+'&price_to='+price_to+'&photo='+photo+'&marks='+marks_ids+'&year_s='+year_s+'&year_f='+year_f+'&kuzov='+kuzov_ids+'&volume_from='+volume_from+'&volume_to='+volume_to+'&probeg='+probeg+'&gearbox='+gearbox_ids+'&wheel='+wheel_ids+'&engine_type='+engine_type_ids;
			
			if (flfl == 1) {
				location.href='/usedcars/?'+qsa;
				return;
			}

			if (qsa != '') {
				
			    $.ajax({
				    url:'/ajax/carSale.php',
			        type: 'GET',
			        data: qsa,
			        cache: false,
			        success: function(table){
			        	
					last_num = table;
					// вот тут нужно будет подсчитать сколько там у нас товаров покажет и вывести цифру, как на яндекс.маркете 
					
					$("div.acs_popup").remove();
					end_smpop = '<div class="acs_popup" id="ch_num"><div>';
					end_smpop += '<span>Выбрано моделей: ' + last_num + ' </span> <input type="button" class="but_bb" value="Показать" />';
					end_smpop += '</div></div>';
					
					$("body").append(end_smpop);
					$("#ch_num").css("left",dp_off_2.left - 250).css("top",dp_off_1.top - 2);
					 
					$("div.acs_popup").hover(
						function() {
							acs_hover = true;
						},
						function() {
							acs_hover = false;
						}
					);
			
		        }, 
			        error: function(){
			          //  alert('ERROR');
			        }
			    });
				
			}
			
			$(document.body).mousedown(function() {
				hide_acs_popup();
			});
		}
		
		// переключаем кузова
		var hull_status = false;

		$("#hull_switch > a").click(function(event) {
			event.preventDefault();
			if(hull_status === false) {
				hull_status = true;
				$("#hull_switch > a > span").text("оставить популярные");
				$("#acs_else").slideDown(200);
			} else {
				hull_status = false;
				$("#hull_switch > a > span").text("показать все");
				$("#acs_else").slideUp(200);
			}
		});
		
		// показываем марки авто
		var acs_marks_opend = false;
		
		$("#acs_select_marks").hover(
			function() {
				acs_hover_2 = true;
			},
			function() {
				acs_hover_2 = false;
			}
		);
		
		$("#acs_select_marks").click(function(event) {
			event.preventDefault();
			
			if(acs_marks_opend === false) {
				hide_acs_popup();
				acs_marks_opend = true;
				
				$("#acs_marks").show();
				
				$("#acs_marks").hover(
					function() {
						acs_hover = true;
					},
					function() {
						acs_hover = false;
					}
				);
				
				$(document.body).mousedown(function() {
					if(acs_hover_2 === false) {
						hide_acs_popup();
					}
				});
			} else {
				hide_acs_popup();
			}
		});
	};
})(jQuery);


/* -------------------------------------------------------------------------------------------
 * Scroll blocks
 * 02.08.2010
 * by IonDen
 */

(function foo($){
    $.fn.set_scroll = function(options) {
		var defaults = {
			height : 50
		};
        var options = $.extend(defaults, options);
		var id = "#" + $(this).attr("id");
		var num = $(id + " div.ue").length;
		var base_width = $(id + " div.ue div").width();
		var all_width = $(id + " div.uni_cont").width();
		var vis_num = Math.floor(all_width / base_width);
		var current_width = Math.ceil(all_width / vis_num);
		var pp = Math.ceil((current_width - base_width) / vis_num);
		current_width = current_width + pp;
		var current_pos = 0;
		
		$(id + " div.ue_left").css("top",options.height / 2 - 2);
		$(id + " div.ue_right").css("top",options.height / 2 - 2);
		
		$(id + " div.uni_cont").height(options.height);
		$(id + " div.ue").width(current_width).css("background-position", base_width + ((current_width - base_width) / 2));
		
		$(id + " div.ue_left").click(function(e) {
			e.preventDefault();
			if(current_pos < 0) {
				current_pos++;
			}
			swing();
			return false;
		});
		$(id + " div.ue_right").click(function(e) {
			e.preventDefault();
			if(current_pos > vis_num - num) {
				current_pos--;
			}
			swing();
			return false;
		});
		$(id + " div.ue_left").mousedown(function() {
			return false;
		});
		$(id + " div.ue_right").mousedown(function() {
			return false;
		});
		
		function swing() {
			$(id + " div.uni_scroll").animate({left:current_width * current_pos},200,place_arrs);
		}
		
		function place_arrs() {
			if(current_pos === 0) {
				$(id + " div.ue_left").hide();
			} else if(current_pos < 0) {
				$(id + " div.ue_left").show();
			}
			
			if(current_pos === vis_num - num) {
				$(id + " div.ue_right").hide();
			} else if(current_pos > vis_num - num) {
				$(id + " div.ue_right").show();
			}
		}
		place_arrs();
	};
})(jQuery);