$(document).ready(function(){
	
	basket_recalc();

	$(".buy").click(function() {

			$(this).parent().append('<div class="tip">В корзине</div>');
			$(".tip").animate({ opacity: "hide" }, 2500);
		
	});

	$(".up").click(function() {

		var v = $(this).next("div").text();
		v = parseInt(v);
		$(this).next("div").text( v + 1 );

		coun = $(".count b").text();
		$(".cart").fadeOut("fast", function() {$(".count b").html((parseInt(coun) +1));});
		$(".cart").fadeIn("fast");			

		id = $(this).parent().parent().attr("id");
		id = id.replace("product_", "");
		
		$.ajax({
			type: "GET",
			url: "/basket?up="+id,
			success: function(msg){
	
					basket_recalc();

			}
		});	
			
			
	});
	
	
	$(".down").click(function() {
		var v = $(this).prev("div").text();
		v = parseInt(v);
		if (v > 1) {
			$(this).prev("div").text( v - 1 );

			coun = $(".count b").text();
			$(".cart").fadeOut("fast", function() {$(".count b").html((parseInt(coun) - 1));});
			$(".cart").fadeIn("fast");					

			id = $(this).parent().parent().attr("id");
			id = id.replace("product_", "");

			$.ajax({
				type: "GET",
				url: "/basket?down="+id,
				success: function(msg){
	
						basket_recalc();
						
				}
			});	

		}

	});	
	
});


function basket_recalc()
{	
	var n = 0;
	var total = 0;		
	var end = false;

	while(end == false) {

	n++;	

		var price = $("#price_"+n).text();
		var col = $("#col_"+n).text();

		price = price.replace(" руб", "");
		price = price.replace(" ", "");			

		$("#sum_"+n).text(formatPrice(price*col) + " руб");

		total = total + price*col;

		z = n+1;
		if ($("#name_"+z).text() == '') { end = true; }
	}

	$("#total").text(formatPrice(total) + " руб");

}

function addToBasket(id, parent) {

				$.ajax({
					type: "GET",
					url: "/basket?add="+id+"&parent="+parent,
					success: function(msg){
	
						coun = $(".count").text();
						$(".count").fadeOut("fast", function() {$(".count").html((parseInt(coun) +1));});
						$(".count").fadeIn("fast");					
						

					}
				});
}

function formatPrice (price) {
	
		var new_str = '';
		var z = 0;

		price = String(price);

		for (i=price.length-1; i > -1; i--) {
	
			if ( (z%3) == 0) {
				new_str = price[i] + " " + new_str;
			} else {
				new_str = price[i] + new_str;
			}
			
			z++;
		}

		return new_str;	
}