// synonym to console.log || alert
log = (function() {
	return (window.console && console.firebug) ? function(){ console.notifyFirebug(arguments, "log", "firebugAppendConsole"); } : alert;
})();

$(document).ready(function() {
	$(".line2 .kartn a").click(function() {
		$(".line2 .kartn").hide();
		$(".line2 .kart_wrapper").show();
	});
	$(".line2 .kart_wrapper a").click(function() {
		$(".line2 .kartn").show();
		$(".line2 .kart_wrapper").hide();
	});
	
	var latestEventDate;
	$("input.cat_item_order").mouseup(function() {
		var metadata = $(this).metadata(), eventDate;
		eventDate = latestEventDate = new Date();
		$.post("/cart.rpc?action=add&id=" + metadata.itemId + "&qty=1", function() {
			$.getJSON('cartinfo', function(response) {
				if (eventDate == latestEventDate) {
					var cartinfo = eval('(' + response.content + ')');
					$(".line2:visible .kart_wrapper .itemsCount").html(cartinfo.total.names);
					$(".line2:visible .kart_wrapper .itemsSum").html(cartinfo.total.sum);
				}
			});
		});
		$(".line2 .kartn").hide();
		$(".line2 .kart_wrapper").show();
		/*
		$.ajax({
			url: "/cart",
			dataType: "json",
			success: function (data) {
				// ахтунг с регулярными выражениями очень сильно влияет на производительность, нужно разобраться почему ие6 вылетает при попытке пропарсить весь content
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				data.body = data.trimmedcontent.match(new RegExp('<body>.*<\/body>', 'g') )[0];
				var itemsCount = $(data.body).find(".itemsCount").html();
				var itemsSum = $(data.body).find(".itemsSum").html();
				$(".line2:visible .kart_wrapper .itemsCount").html(itemsCount);
				$(".line2:visible .kart_wrapper .itemsSum").html(itemsSum);
			}
		});
		*/
		return(false);
	});
	
	$(".lnav .items").hide();
	$(".lnav .items .current").parent().show();
	$(".lnav h2").click(function() {
		$(this).next(".items").toggle();
	});
	
	$(".ktbl input.kq").keyup(function() {
		$(this).parent().parent().find(".catItemSum span").html($(this).val() * $(this).parent().parent().find(".catItemPrice span").html());
		if($(this).val() <= 0) $(this).parent().parent().find(".catItemSum span").html("0");
		totalSumCalc();
	});
	
	$(".catItemDelete a").click(function() {
		$(this).parent().parent().find("input.kq").val(0);
		$(this).parent().parent().find(".catItemSum span").html("");
		$(this).parent().parent().hide();
		totalSumCalc();
		return(false);
	});
	
	$("form.search a").click(function() {
		$("form.search").submit();
		return(false);
	});
	
	/*tooltips*/
	$(".im img").tooltip({ 
		delay: 0, 
		showURL: false, 
		track: true, 
		bodyHandler: function() {
			var metadata = $(this).metadata();
			return $("<img/>").attr("src", $(this).parent().attr("rel")).attr("width", metadata.imgWidth).attr("height", metadata.imgHeight); 
		}
	});
	/*tooltips*/
	
	/*left menu - show amount*/
	$(".lnav h2").each(function() {
		var header = $(this);
		$.ajax({
			url: $(this).attr("id") + "?widget=catItemsCount",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				header.append(data.trimmedcontent);
			}
		});
	});
	
	$(".lnav .items a").each(function() {
		var header = $(this);
		$.ajax({
			url: $(this).attr("href") + "?widget=catItemsCount",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				header.append(data.trimmedcontent);
			}
		});
	});
	/*/left menu - show amount*/

	$(".price_block h3").each(function() {
		var header = $(this).parent();
		$.ajax({
			url: $(this).attr("id") + "?widget=price",
			dataType: "json",
			success: function (data) {
				data.trimmedcontent = data.content.toString().replace(new RegExp('\\r\\n', 'g'), '');
				header.find(".section_content").replaceWith(data.trimmedcontent);
			}
		});
	});

	if ($.browser.msie && $.browser.version == "7.0") {
		$(".tleft").height($(".main").height());
		$(".main").css("margin-bottom", "-100%");
	}
});

function totalSumCalc() {
	var totalSum = 0;
	var totalCount = $(".fkart:visible tr.kr:visible").length;
	$(".fkart:visible .catItemSum span").each(function() {
		if($(this).html().length > 0) totalSum += eval($(this).html());
	});
	$(".fkart:visible .ktotal span").html(totalSum);
	$(".kart_wrapper:visible .itemsCount").html(totalCount);
	$(".kart_wrapper:visible .itemsSum").html(totalSum);
	$(".ktbl input[name='order']").show();
	if(totalSum == 0) {
		$(".fkart:visible .ktotal span").html("0");
		$(".kart_wrapper:visible .itemsCount").html("0");
		$(".kart_wrapper:visible .itemsSum").html("0");
		$(".ktbl input[name='order']").hide();
		//$(".fkart:visible form").submit();
	}
	submitCart();
}

var t;
function submitCart(){
	clearTimeout(t);
	t = setTimeout(function(){
		$.ajax({
		type: "POST",
		url: "?q=cart.rpc&action=reset",
		data: $(".ktbl").serialize()
	});
	}, 500);
}


$(function(){
	/* validation */
	
	/* default messages */
	$.validator.messages.required = "Это поле является обязательным для заполнения";
	$.validator.messages.email = "Некорректный формат адреса электронной почты";
	/*/ default messages */
	
	$('form .required input').addClass('required');
	$('form .required textarea').addClass('required');
	$('form .email-wrapper .required input').addClass('email');
	$('form').each(function() { $(this).validate() });
	
	/*/ validation */
});