this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */
	
	$("a.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
	
	$("span.tooltip").hover(function(e){											  
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$("span.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


$(document).ready(
function()
{

	if (!navigator.cookieEnabled)
		$('#wocookies').show();
	
	tooltip();

	$("#calc select").change(function(e)
	{
		$("#razmeri").load(
			"/calculator",
			$("#calcForm").formSerialize(),
			function(data)			
			{
				calculateSpeed();
			}
		)
	});

	$("#search").focus(function(e)
	{
		if($("#search").val() == "Поиск")
		{
			$("#search").val("");
			$("#search").removeClass("gray");
		}
	});
	
	$("#search").blur(function(e)
	{
		if($("#search").val() == "")
		{
			$("#search").addClass("gray");
			$("#search").val("Поиск");
		}
	});
	
	$("#tyresFilterForm select").change(function(e)
	{
		$("#tyresSubmit").attr("disabled", "disabled")
		$("#tyresStatus").html("&nbsp;&nbsp;&nbsp;&nbsp;")
		$("#tyresStatus").addClass("loading")

		$("#tyresStatus").load(
			"/tyres",
			$("#tyresFilterForm").formSerialize(),
			function(data)
			{
				$("#tyresStatus").removeClass("loading")
				if(data!="Шины с указанными параметрами не найдены"
				   && data!="Шин с указанными параметрами не найдено"
				   && data!="Задайте хотя бы 1 параметр"
				   && data!="Расчет невозможен. Такого размера нет в наличии.") {

					$("#tyresSubmit").removeAttr("disabled");
				}
			}
		)

	});
	
	$("#wheelsFilterForm select").change(function(e)
	{
		$("#wheelsSubmit").attr("disabled", "disabled")
		
		$("#wheelsStatus").html("&nbsp;&nbsp;&nbsp;&nbsp;")
		$("#wheelsStatus").addClass("loading")

		$("#wheelsStatus").load(
			"/wheels",
			$("#wheelsFilterForm").formSerialize(),
			function(data)
			{
				$("#wheelsStatus").removeClass("loading")
				if(data!="Дисков с указанными параметрами не найдено"
				   && data!="Задайте хотя бы 1 параметр"
				   && data!="Расчет невозможен. Такого размера нет в наличии."
				)
					$("#wheelsSubmit").removeAttr("disabled");
			}
		)

	});

	$("#trailersFilterForm select").change(function(e)
	{
		$("#trailersSubmit").attr("disabled", "disabled")
		
		$("#trailersStatus").html("&nbsp;&nbsp;&nbsp;&nbsp;")
		$("#trailersStatus").addClass("loading")

		$("#trailersStatus").load(
			"/trailers",
			$("#trailersFilterForm").formSerialize(),
			function(data)
			{
				$("#trailersStatus").removeClass("loading")
				if(data!="Прицепов не найдено")
				{
					$("#trailersSubmit").removeAttr("disabled");
				}
			}
		)

	});
	
	if($("#card_id"))
		$("#card_id").change(function(e)
		{
			changeCard($("#card_id").val());
		});

//	$(".delivery_town")
//		.autocomplete("/get_delivery_towns")

	// Shipping page. Tyre

	$("#tyresShortFilterForm select").change(function(e) {
		loadTyresV();
	});
	
	//страница калькулятора доставки. диски
	$("#wheelsShortFilterForm select").change(function(e) {
		loadWheelsV();
	});

});

function showSpecMore()
{
	$("div.spec-more-line").show()
	$("div.spec-more").hide()
	return false;
}

function calculateSpeed()
{
	var speed = $('#speed').val()
	if(speed > 0)
	{
		var d1 = parseInt($('#diametrOldVal').html())
		var d2 = parseInt($('#diametrNewVal').html())
		
		if(d1 != 0)
		{
			var newSpeed = speed*d2/d1;
			var res = $('#speedReal').html(newSpeed.toFixed(2))
			var speedPercentage = (newSpeed - speed)/(speed/100)
			$('#speedPercentage').html(speedPercentage.toFixed(2) + '%')
		}
	}
}

function dostavka_display_delivery()
{
	_hide_dostavka_delivery_town()
	_show_dostavka_delivery()
	$('#delivery-local').hide();
}

function dostavka_display_none()
{
	_hide_dostavka_delivery()
	_hide_dostavka_delivery_town()
	$('#delivery-local').show();
}

function dostavka_display_delivery_town()
{
	_hide_dostavka_delivery()
	_show_dostavka_delivery_town()
	$('#delivery-local').hide();
}

function _show_dostavka_delivery()
{
	$('#adressFieldSet').show();
	$('.deliver-nacenka').show();
	$('.notebene').show();
}

function _hide_dostavka_delivery()
{
	$('#adressFieldSet').hide();
	$('.deliver-nacenka').hide();
	$('.notebene').hide();
}

function _show_dostavka_delivery_town()
{
	$('#deliveryTownDisclaimer').show()
	$("#deliveryTownFieldSet").show()
	$('#adressFieldSet').hide();
	$('.notebene').show();
}

function _hide_dostavka_delivery_town()
{
	$('#deliveryTownDisclaimer').hide()
	$("#deliveryTownFieldSet").hide()
	$('#adressFieldSet').hide();
	$('.notebene').hide();
}


function check_dysplay_show(delivery){
	
	$('#adressFieldSet').show();
	$('.deliver-nacenka').show();
	$('.notebene').show();	
}


function showModifs(id)
{
	$(".opentable").hide();
	$("div.modifsbit").hide();
	$("div.modelbit").show();
	$("#model_"+id).hide();
	$("#modifs_"+id).show();
	return false;
}

function showWheels(id, a)
{
	$("a.act").removeClass("act");
	$(a).addClass("act");
	$(".opentable").hide();
	$("#tableLoading").css('margin-top', ($(a).position().top - 220) + 'px');
	$("#tableLoading").show();
	if($("#wheels_table_"+id).length)
		$("#wheels_table_"+id).show();
	else
		$.post( '/podbor',
				{id:id},
				function(data, textStatus) {
//						$(data).appendTo($(a).parents("div.wheelbit"));
						$("#tableLoading").hide();
						$(data).appendTo($('.otbot'));
						$("#wheels_table_"+id).css('margin-top', ($(a).position().top - 220) + 'px');
//						alert($(a).position().top);
						},
				"html");
	return false;
}

function addToCart(type, id, order, bt, shiftElement)
{
	showCartLoading(shiftElement ? shiftElement : bt, shiftElement != null);
	
	if(order != true)
		order = false;
	
	var card_id = "0";
	var target = "#cart"
	var target_url = "/"
	if(order)
	{
		card_id = $("#card_id").val();
		target = "#cart_order";
		target_url = "/ordernow"
	}
	
	$(target).load(
		target_url,
		{"action":"add", "type":type, "id":id, "order":order, "card_id":card_id},
		function(data)
		{ hideCartLoading();}
	);
	
	return false;	
}

function addToCartWDelivery(type, id, order, bt, to_delivery_town, col)
{
	$('.delivery_popup').hide()
	showCartLoading(bt);
	
	if(order != true)
		order = false;
	
	var card_id = "0";
	var target = "#cart"
	var target_url = "/"
	if(order)
	{
		card_id = $("#card_id").val();
		target = "#cart_order";
		target_url = "/ordernow"
	}
	
	$(target).load(
		target_url,
		{"action":"add", "type":type, "id":id, "col":col, "order":order, "card_id":card_id, "set_delivery":1, "to_delivery_town":to_delivery_town},
		function(data)
		{ hideCartLoading();}
	);
	
	return false;	
}

function delFromCart(type, id, order)
{
	showCartLoading();
	
	if(order != true)
		order = false;
	
	var card_id = "0";
	var target = "#cart"
	var target_url = "/"
	if(order)
	{
		card_id = $("#card_id").val();
		target = "#cart_order";
		target_url = "/ordernow"
	}

	$(target).load(
		target_url,
		{"action":"del", "type":type, "id":id, "order":order, "card_id":card_id},
		function(data)
		{	hideCartLoading();}
	);
	
	return false;	
}

function removeFromCart(type, id, order)
{
	showCartLoading();
	
	if(order != true)
		order = false;
	
	var card_id = "0";
	var target = "#cart"
	var target_url = "/"
	if(order)
	{
		card_id = $("#card_id").val();
		target = "#cart_order";
		target_url = "/ordernow"
	}
	
	$(target).load(
		target_url,
		{"action":"remove", "type":type, "id":id, "order":order, "card_id":card_id},
		function(data)
		{	hideCartLoading();	}
	);

	return false;	
}

function showCartLoading(bt, fromModel)
{
	$("div.cart-loading").each(function(i){ $(this).removeClass('hide'); $(this).addClass('show'); });
	//alert($(bt).offset().top);
	if(bt)
	{
		var topVal = $(bt).offset().top + 2
		var leftVal = $(bt).offset().left + (fromModel ? $(bt).width() + 10 : 100);
		$('.loading-big-wrap').css({top: topVal}).css({left: leftVal});
		$('.loading-big-wrap').show();
	}
}
function hideCartLoading()
{
	$("div.cart-loading").each(function(i){ $(this).removeClass('show'); $(this).addClass('hide'); });
	$('.loading-big-wrap').hide();
}


function changeCard(card_id)
{
	var card_id = $("#card_id").val();
	var target = "#cart_order";
	var target_url = "/ordernow"
	
	$(target).load(
		target_url,
		{"action": "change_card", "order":true, "card_id":card_id},
		function(data)
		{		}
	);
	
	return false;
}

function toggleTownsList(id)
{
	$("#"+id).toggle();
	return false;
}

function showFilter(id)
{
	var buttons = new Array('tyres', 'wheels', 'trailers')
	
	$(".mform-c4").removeClass("mform-c4");
	$("#miniFilter").hide();
	$("#podborMiddle").show();
	
	for(var i=0; i<3; i++)
	{
		
		if(buttons[i] == id)
		{
			$("#" + buttons[i] + 'Active').hide();
			$("#" + buttons[i] + 'Passive').show();
			$("#" + buttons[i] + 'Filter').show();
		}
		else
		{
			$("#" + buttons[i] + 'Active').show();
			$("#" + buttons[i] + 'Passive').hide();
			$("#" + buttons[i] + 'Filter').hide();
		}
	}
}

function podborPoModeli(sel)
{
	var url = $(sel).val();
	if(url != "0")
		window.location = url;
}


function showDeliveryPopup(lot_id)
{
	$(".delivery_popup").hide()
	$("#delivery_popup_"+lot_id).show()
	$(document).scrollTop(0);
	return false;
}

var filials_towns;
var filials_towns_names;
function initFilialsTowns(_filials_towns, _filials_towns_names)
{
	filials_towns = _filials_towns
	filials_towns_names = _filials_towns_names
}	

function checkDeliveryTown(delivery_town, popup_block, _cur_url)
{
	if (filials_towns[delivery_town] != undefined)
		popup_block.find(".delivery_hint").html('В данном городе есть филиал интернет-магазина КолесаМира.<br /><a href="?ctid='+filials_towns[delivery_town]+'&return_path='+_cur_url+'">Сменить текущий город на '+filials_towns_names[delivery_town]+'?</a><br />').show(500)

	else
		popup_block.find(".delivery_hint").hide().text("")
}

function calcDeliveryCost(from_town_id, to_delivery_town, v, popup_block)
{
//	to_delivery_town = to_delivery_town[0]
	if (to_delivery_town == "0")
	{
		popup_block.find(".add_to_basket").hide()
		popup_block.find(".delivery_cost").hide()
		return
	}

	var delivery_cost_block = popup_block.find(".delivery_cost")

	$(delivery_cost_block).load(
		"/",
		{"action":"calc_delivery_cost", "from_town_id":from_town_id, "to_delivery_town":to_delivery_town, "v":v},
		function(data)
		{
			popup_block.find(".add_to_basket").show() 
			popup_block.find(".delivery_cost").show() 
		}
	);
}

function calcDeliveryCostOnOrder(from_town_id, to_delivery_town, v)
{
	if (to_delivery_town == "0")
		return

	$("#delivery_cost").load(
		"/",
		{"action":"calc_delivery_cost", "from_town_id":from_town_id, "to_delivery_town":to_delivery_town, "v":v},
		function(data)
		{ $("#delivery_cost").show() }
	);
}

//считаем стоимость доставки не странице доставки. 

function loadTyresV(startMode)
{
	$.ajax({
		url: "/tyres",
		data: $("#tyresShortFilterForm").formSerialize(),
		success: function(data)
		{
			$("#deliveryCostMsg").hide()
			$("#tyresDeliveryMsg .status").text('')
			$("#wheelsDeliveryMsg .status").text('')

			var res = $.parseJSON(data)
			if (res.finded == "1")
			{
				tyres_v = res.max_v
				$('#tyresDeliveryCntInput').attr("disabled","")
			}
			else
			{
				tyres_v = 0
				$('#tyresDeliveryCntInput').attr("disabled","disabled")
			}

			if (startMode) {
				loadWheelsV();
			} else {
				calcDeliveryCostOnPage(deliveryTownId);
			}
		}
	});
}

function loadWheelsV()
{
	$.ajax({
		url: "/wheels",
		data: $("#wheelsShortFilterForm").formSerialize(),
		success: function(data)
		{
			$("#deliveryCostMsg").hide()
			$("#tyresDeliveryMsg .status").text('')
			$("#wheelsDeliveryMsg .status").text('')

			var res = $.parseJSON(data)
			if (res.finded == "1")
			{
				wheels_v = res.max_v
				$('#wheelsDeliveryCntInput').attr("disabled","")
			}
			else
			{
				wheels_v = 0
				$('#wheelsDeliveryCntInput').attr("disabled","disabled")
			}
			
			calcDeliveryCostOnPage(deliveryTownId);
		}
	});
}

function calcDeliveryCostOnPage(from_town_id)
{
	var to_delivery_town = $("#deliveryTownPage").val()
	if (to_delivery_town == "0")
	{
		$("#deliveryInfoDiv").show()
		$("#deliveryCostMsg").text("Укажите город доставки.")
		return
	}

	if ( !(tyres_v!=undefined && $("#tyresDeliveryCntInput").text()!="0") && !(wheels_v!=undefined && $("#wheelsDeliveryCntInput").text()!="0") )
	{
		$("#deliveryInfoDiv").show()
		$("#deliveryCostMsg").text("Укажите количество дисков или шин.")
		$("#tyresDeliveryMsg .status").text('');
		$("#wheelsDeliveryMsg .status").text('');
		return
	}


	var tyres_v_total = 0
	if (tyres_v!=undefined && $("#tyresDeliveryCntInput").text())
		tyres_v_total += tyres_v*$("#tyresDeliveryCntInput").text()

	var wheels_v_total = 0
	if (wheels_v!=undefined && $("#wheelsDeliveryCntInput").text())
		wheels_v_total += wheels_v*$("#wheelsDeliveryCntInput").text()

	var v = tyres_v_total + wheels_v_total
		        	
	$.ajax({
		url: "/",
		type: "post",
		data: ({action:"calc_delivery_cost", 
			json_mode: 1,
			from_town_id:from_town_id, 
			to_delivery_town:to_delivery_town, 
			v:v, 
			tyres_v:tyres_v_total, 
			wheels_v:wheels_v_total }) ,

		success: function(data)
		{ 
			res = jQuery.parseJSON(data)
			$("#deliveryCostMsg").text(res.total)
			$("#deliveryCostMsg").show()

			if (res.tyres != undefined)
			{
				$("#tyresDeliveryMsg .status").text(res.tyres)
			}
			else
			{
				$("#tyresDeliveryMsg .status").text(tyres_v ? '' : 'Расчет невозможен. Такого размера нет в наличии.')
			}

			if (res.wheels != undefined)
			{
				$("#wheelsDeliveryMsg .status").text(res.wheels)
			}
			else
			{
				$("#wheelsDeliveryMsg .status").text(wheels_v ? '' : 'Расчет невозможен. Такого размера нет в наличии.')
			}
		}
	});

}

function countPlus(countWrp)
{
	var count = parseInt(countWrp.text())
	if (count < 16)
		countWrp.text(count+1)
}

function countMinus(countWrp)
{
	var count = parseInt(countWrp.text())
	if (count > 0)
		countWrp.text(count-1)
}

function countMinusNZ(countWrp)
{
	var count = parseInt(countWrp.text())
	if (count > 1)
		countWrp.text(count-1)
}

function goShippingTo(shippingTo) 
{
	if (shippingTo) {
		window.location = '/' + _shippingHandle + '/' + shippingTo;
	}
	return true;
}
