$(function() {
	var pattern= /add_to_basket\[(\d+)\]/;
	$("a.buy").bind("click", function(e) {
		var href= $(this).attr("href");
		var match= pattern.exec(href);
		var cart= $("#cartbox");
		var product= {};
		cart.find("div").each(function () {
			var href= $(this).find("a").attr("href");
			if(!href) return;
			if($(this).hasClass("tocart")) return;
			product[href]= $(this);
		});
		$.get(href, function(data) {
			var result= jQuery("<div/>")
				.append(data.replace(/<script(.|\s)*?\/script>/g, ""))
				.find("#cartbox");

			var total= cart.find("div.total");
			if(total.length == 0) {
				cart.replaceWith( result );
				return;
			}

			// loop over the divs
			result.find("div").each(function() {
				var div= $(this);
				var href= div.find("a").attr("href");
				if(!href) return; 
				if(div.hasClass("tocart")) return;

				if(product[href]) {
					product[href].replaceWith( div ); 
					delete product[href];
					return;
				} else {
					div.hide();
					total.before( div );
					div.slideDown();
				}
			});
			total.replaceWith(result.find( "div.total"))

			// products to delete?
			jQuery.each( product, function(i, div) { div.remove(); });
		});
		$("#emptybasket").hide("slow");
		return false;
	});
});
	
