var pageTotal = 0;

function recalcTotal() {
	pageTotal = 0;
	
	$(".orderingtable").each(function() {
		sectionItems = 0;
		sectionTotal = 0;
		
		$("tr",this).each(function() {
			// qty   = parseInt($("td.qty input:checked",this).val());
			qty   = parseInt($("td.qty input",this).val());
			price = parseFloat($("td.price span.sellingprice",this).text().replace(/[^0-9.]/,""));

			if (!isNaN(qty)) {
				sectionItems += qty;
				sectionTotal += (qty * price);
				
				pageTotal += (qty * price);
			}		
		})
		
		$(this).parent().prev("h3").find(".colour-subtotal").html(sectionItems + " / &pound;" + sectionTotal.toFixed(2));
	})

	/*
	$(".orderingtable tr").each(function() {
		qty   = parseInt($("td.qty input",this).val());
		price = parseFloat($("td.price",this).text().replace(/[^0-9.]/,""));

		if (!isNaN(qty)) {
			pageTotal += (qty * price);
		}
	});
	*/

	// ENABLE ADD TO CART BUTTON?
	if (pageTotal > 0 && $("#ColourID").val() != "") {
		// OK, ENABLE
		$("#addproductop, #addproductbottom").attr("disabled","").removeClass("apdisabled");
	} else {
		// DISABLE
		$("#addproductop, #addproductbottom").attr("disabled","disabled").addClass("apdisabled");
	}
	
	$("#prodprice, #prodprice2").html("&pound;" + pageTotal.toFixed(2));
}

$(document).ready(function() {	
	$("#accordion-outer").accordion({
		header: "h3"
	});

	$("a[rel=facebox]").facebox({
		overlay: true
	});

	// CLICK TO CHANGE MAIN IMAGE
	$(".altimg").mouseover(function() {
		$(this).css("cursor","pointer");
	}).click(function() {
		$(".altimg").removeClass("altimgactive");
		$(this).addClass("altimgactive");

		// NEW INFOS
		newImgTitle = $(this).attr("title");
		newImgAlt   = $(this).attr("alt");
		newImgPath  = $(this).attr("src").replace(/prodtiny/,"prodmed");
		
		$("#imgmain").fadeTo(100,0.01,function() {
			$("#imgmain").attr({
				"src": newImgPath,
				"alt": newImgAlt,
				"title": newImgTitle
			}).fadeTo(500,1);
		});
	});

	$(".qty input").change(function() {
		if (isNaN($(this).val())) {
			$(this).val("");
		} else {
			recalcTotal();
		}
	});
	
	$("#ColourID").change(function() {
		recalcTotal();
	});
	
	recalcTotal();
});
