$(document).ready(function(){
	$("#slider-txt").show();
	$("#slider-txt ul").liScroll();
	
	$.get('/ajax?action=getbrand', function(data) {
			$('.selection select[name=brand]').append(data);
			$('#credit-form select[name=brand]').append(data);
			if (typeof brand_id != "undefined" && brand_id != ''){
				$('.selection select[name=brand] option[value='+ brand_id +']').attr("selected", "selected");
				$('#credit-form select[name=brand] option[value='+ brand_id +']').attr("selected", "selected");
				$("#credit-form select[name=brand]").change();
			}
	});
	
	$('<select class="forms-03" name="brand"><option>Выбрать марку</option></select>').replaceAll("#credit-form input[name=brand]");
	$('<select class="forms-03" name="model"><option value="0">Выбрать модель</option></select>').replaceAll("#credit-form input[name=model]");
	$('<select class="forms-03" name="cost"><option value="0">Выбрать комплектацию</option></select>').replaceAll("#credit-form input[name=cost]");
	
	$("#credit-form select[name=brand]").change(function(){
		$("#credit-form select[name=model] option:gt(0)").remove();
		$("#credit-form select[name=cost] option:gt(0)").remove();
		$.get('/ajax?action=getmodel&brand='+$("option:selected", this).val(), function(data) {
			$('#credit-form select[name=model]').append(data).show();
			if (typeof model_id != "undefined" && model_id != ''){
				$('#credit-form select[name=model] option[value='+ model_id +']').attr("selected", "selected");
				$("#credit-form select[name=model]").change();
			}
		});
	});
	
	$("#credit-form select[name=model]").change(function(){
		$("#credit-form select[name=cost] option:gt(0)").remove();
		$.get('/ajax?action=getcompl&model='+$("option:selected", this).val(), function(data) {
			$('#credit-form select[name=cost]').append(data).show();
			if (typeof compl_id != "undefined" && compl_id != ''){
				$('#credit-form select[name=cost] option[value='+ compl_id +']').attr("selected", "selected");
				$("#credit-form select[name=cost]").change();
			}
		});
	});
	
	$("#credit-form").submit(function() {
		if ($("#credit-form select[name=brand] option:selected").val() == 0) {
			alert("Выберите марку автомобиля!");
			return false;
		} else if ($("#credit-form select[name=model] option:selected").val() == 0) {
			alert("Выберите модель автомобиля!");
			return false;
		} else if ($("#credit-form select[name=cost] option:selected").val() == 0) {
			alert("Выберите комплектацию автомобиля!");
			return false; 
		}
		
		$("#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=cost] option:selected").val($("#credit-form select[name=cost] option:selected").html());
		return true;
	});
	
	var $tabs = $('.model-menu a');
	var $models = $('.models-list');

	var tabOpen = function($tab) {
		// Закрываем все активные табы и убираем класс .active
		tabsClose();

		// Открываем таб, на который нажали
		$tab.parent().addClass('active');
		var modelName = $tab.children('span').attr('class');
		$models.children('.' + modelName).css('display', 'block');
	}

	var tabsClose = function() {
		$tabs.removeClass('active');
		$models.children('li').css('display', 'none');
	}

	// При загрузке открыть первый
	//tabOpen($tabs.first());

	$tabs.click(function () {
		tabOpen($(this));

		// Убираем "Скачёк"
		//return false;
	});
	
	$('.menu li:has(a.menu-down)').hover(function() {
		$(this).children('a').addClass('active2');
		}, function() {
		$(this).children('a').removeClass('active2');
	});

    
    if (typeof brand != "undefined" && brand != '')
    	tabOpen($(".model-menu ."+brand).parent());
	if (typeof model != "undefined" && model != '')
		$('.models-list a.'+ model).addClass('active');
     
	$(".menu li ul li ul li").hover(function(){
		$(".model-info img", this).attr("src", $("img", this).attr("src2"));
	}, function(){});
	
	$(".tab_content").hide();
	$("ul.tabs li:first a").addClass("active"); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li a").click(function() {

		$("ul.tabs li a").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").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;
	});
	
	$('.modifications input[type=checkbox]').change(function(){
		if ($('.modifications input[type=checkbox]:checked').length > 1)
			$('.modifications .compare-button').removeAttr('disabled');
		else 
			$('.modifications .compare-button').attr('disabled', 'yes');
	});

	//$("#tabs").tabs();
	
	hash = document.location.hash;
	if (hash.match(/#anchc(.*)/i)) {
		compl = hash.replace("#anchc", "");
		$("#compl_"+compl).slideToggle();
	}
	
	var active_brand = '';
	var act = '1'
	var outtimer, x;
	var obj= new Array();
	var obj_index;
	/*$('.model-menu li:not(.active)').hover(
	function(){
		clearTimeout(outtimer);
		x = y = z = 0;
		active_brand = $(this).find('span').attr("class");
		$('.hover-model-menu').show();
		var li_object = $(this);
		//if (active_brand != act){
			$(".hover-model-menu .models").css("margin-left", "0px");
			$(".hover-model-menu .models ul").remove();
			$(".hover-model-menu .models img").remove();
			$('.hover-model-menu .models').append('<img id="loader" src="/img/loader.gif">');
			$.ajax({
				url: '/ajax?action=getmodels&brand='+$(this).find('span').attr('class'),
				success: function(data) {
					act = active_brand;
					$(".hover-model-menu .models img").remove();
					$(".hover-model-menu .models ul").remove();
					$(".hover-model-menu .models").append(data);
					$(".hover-model-menu .models li:nth-child(5n)").css("margin-right", 0);
					switch(active_brand) {
						case 'toyota':
							$(".hover-model-menu").css("margin-left", "300px");
							break;
						case 'chery':
							$(".hover-model-menu").css("margin-left", "370px");
							break;
						case 'hyundai':
							$(".hover-model-menu").css("margin-left", "370px");
							break;	
						case 'chance':
							$(".hover-model-menu").css("margin-left", "570px");
							break;
						case 'tagaz':
							$(".hover-model-menu").css("margin-left", "350px");
							break;
						case 'great-wall':
							$(".hover-model-menu").css("margin-left", "700px");
							break;
						case 'volkswagen':
							$(".hover-model-menu").css("margin-left", "800px");
							break;
						default:
							$(".hover-model-menu").css("margin-left", "0px");
					}	
					var cars_block_width = $('.hover-model-menu').width();
					$(".topbg").width(cars_block_width-16);
					$(".bottombg").width(cars_block_width-16);	

					x = $(li_object).find('a').offset().left;
					offset = $(li_object).hasClass('last') ? 23 : 19;
					y = $('.hover-model-menu').offset().left;
					z = x - y;
					$('.hover-model-menu .treug').css("left", z + offset);
				}
			});
		//}
	},
	function(){
		outtimer = setTimeout(function(){$('.hover-model-menu').hide()}, 50);
	});
	
	$('.hover-model-menu').hover(
	function(){
		clearTimeout(outtimer);
		$('.model-menu li span[class='+active_brand+']').parent().parent().addClass('active');
	},
	function(){
		$(this).hide();
		$('.model-menu li span[class='+active_brand+']').parent().parent().removeClass('active');
	});*/
	
	$("#callback").submit(function() { 
                
		if($("#callback input[name='name']").val() == "")   
			alert("Укажите ваше имя!");
			//$("#callback .msg").html("Укажите ваше имя!");
		else if($("#callback input[name='phone']").val() == "")
			alert("Укажите ваш телефон!");
			//$("#callback .msg").html("Укажите ваш телефон!");
		else 
		{
			$.post("/ajax?action=backcall",
			{ name: $("#callback input[name='name']").val(),
			  phone: $("#callback input[name='phone']").val()
			},
				function(data){
					if (data == "ok") {
						$("#callback").html('<div class="result">Спасибо!<br />С вами обязательно свяжутся!</div>');
					}
			});
		}
		
		return false;
	});
});

function creditform(){
	PopUp('/creditform', 'credit', 830, 800, 1);
}

function creditform_param(brand, model, compl){
	PopUp('/creditform?brand_id='+brand+'&model_id='+model+'&compl_id='+compl, 'credit', 830, 800, 1);
}

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( '', name, 'width='+width+',height='+height+ showx + showy + ',resizable=no,scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no');
	//alert(url);
	Win.location.href = url;
	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 turnOff(name) {
	$("img[name="+name+"]").attr("src", "/img/kupon2.jpg");
}

function turnOn(name) {
	$("img[name="+name+"]").attr("src", "/img/kupon21.jpg");
}

jQuery.fn.liScroll = function(settings) {
	settings = jQuery.extend({
	travelocity: 0.10
	}, settings);		
	return this.each(function(){
		var $strip = jQuery(this);
		$strip.addClass("newsticker")
		var stripWidth = 0;
		var $mask = $strip.wrap("<div class='mask'></div>");
		var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
		var containerWidth = $strip.parent().parent().width(); 	
		$strip.find("li").each(function(i){
			stripWidth += jQuery(this, i).outerWidth(true)+250;
		});
		$strip.width(stripWidth);			
		var totalTravel = stripWidth;
		var defTiming = totalTravel/settings.travelocity;	
		function scrollnews(spazio, tempo){
			$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
		}
		scrollnews(totalTravel, defTiming);				
		$strip.hover(function(){
			jQuery(this).stop();
		},
		function(){
			var offset = jQuery(this).offset();
			var residualSpace = stripWidth;
			var residualTime = residualSpace/settings.travelocity;
			scrollnews(residualSpace, residualTime);
		});			
	});	
};
