(function($) {

$(function() {
	$(".addtocart").click(function() {
		var getId = $(this).attr("href").split("/");
		
		if(!$.cookie("goods")) {
			$.cookie("goods", "{}", { path: '/'});
		}

		var cookies = $.evalJSON($.cookie("goods"));
		cookies[getId[2]] = 1;				
			
		$.cookie("goods", $.toJSON(cookies), {
			path: "/"
		});
		
		$(this).before("<a href='/cart/'>В корзине</a>");
		$(this).remove();
		
		return false;
	});

	/*$("div.description div.gallery a").click(function() {
		$(this).parent().find("img").css("border", "none");
		$(this).find("img").css("border", "1px solid");
		
		$("div.description span.bigimage img").attr("src", $(this).attr("href"));
		return false;
	});*/

	var number_format = function(str) {
		var l  = str.length;

		if(str  == '0') {
			return '';
		}

		return [str.substring(0, i = (l - Math.floor(l / 3) * 3)), str.substring(i).match(/(\d{3})/g).join(".")].join(".").replace(/^\./, '');
	};
		
	var calc = function(trs, skip_min_validation) {
		if (!trs) {
			trs = $("body.inner table tr");
		}
		
		if (!skip_min_validation && trs.toArray().length == 1) {
			return;
		}
		
		$(trs).each(function(i, item) {
			var inputs = $(item).find("input, select");
			var amount = parseInt(inputs.eq(1).val()) * parseInt(inputs.eq(2).val()) + "";

			if (amount == "NaN") {
				return;
			}

			var nf = number_format(amount);

			$(this).find("span.price").text(nf);
		});


		var sum = 0;
		
		$("span.price").each(function(i, item) {
			sum += parseInt($(item).text().replace(/\./g, ""));
		});
		
		$("#total span").html(number_format(sum + ""));
	};
	
		
	calc();
	
	$("body.inner table tr td a").click(function() {
		var i = $(this).siblings("input");
		var skip_min_validation = true;

		var line = $(this).closest("tr");
		
		switch($(this).attr("href")) {
			case "/plus/":
				i.val(parseInt(i.val()) + 1);
				if(i.val() < 1) i.val(1);
				break;
			case "/minus/":
				i.val(parseInt(i.val()) - 1);
				if(i.val() < 1) i.val(1);
				break;
			case "/delete/":
				$(this).closest("tr").remove();
				var cooks = $.evalJSON($.cookie("goods"));
				
				var id = $(this).closest("tr").find("input").attr("name").match(/\d+/).pop();
				
				delete(cooks[id]);
				
				$.cookie("goods", $.toJSON(cooks), {
					path: "/"
				});
				
				if($("tr").toArray().length == 1) {
					return false;
				}
				break;
			default:
				return true;
		}

		calc(line, skip_min_validation);
		
		return false;
	});

	
	$("body.inner table tr td select").change(function() {
		calc($(this).closest("tr"), true);
	});
});

})(jQuery);

