
$(document).ready(function() {
	// TODO: Fix this
    var siteRoot = g_siteRoot; 	// HACK!! How to nicely inject site root to JS files
    
	/*
	$('#cart-update-dialog').jqm({modal:true, overlay:0, 
		// Have to delay turning on opacity to avoid prob with IE blanking out whole screen on 1st click
		onShow:function(hash){ hash.o.css('opacity', 0.3); hash.w.show(); }
	});
	*/
	$('#cart-update-dialog').jqm();
	
	// Stop IE caching ajax reqs (otherwise ajax stops working after 1st click)
	$.ajaxSetup({ cache: false });
	
	var removeLinkHandler = function() {
		var parent = $(this).parents('.item');
		var productId = parent.attr('id').substr('cart-item-'.length);
		//var countryId = $('#shippingCountry').val();
		$(parent).block({ message:null, overlayCSS:{ backgroundColor:'#999', opacity:'0.3'} });
		$.getJSON(siteRoot + '/ShoppingCart/RemoveProduct.aspx', 
			{'product.id':productId /*,'shippingCountry.id':countryId */ }, 
			updateCart);
		return false;
	};

	var bindAllRemoveItemLinks = function() {
		$('#cart .item .remove').bind('click', removeLinkHandler);
	};
	
	var rebindAllRemoveItemLinks = function() {
		$('#cart .item .remove').unbind('click', removeLinkHandler);
		bindAllRemoveItemLinks();
	};

	var updateCart = function(data) {
		if (null == data) return;
		var cartContainer = $("#cart .items");
		if (data.DeletedItems) {
			for (i=0; i<data.DeletedItems.length; i++)
				$("#cart-item-" + data.DeletedItems[i]).remove();
		}
		
		// Update individual items:
		var changedItem = null;
		if (null != data.Items) {
			for (var i=0; i<data.Items.length; i++) {
				// Try to find the cart item div:
				var cartId = "#cart-item-" + data.Items[i].ProductModelId;
				var cartItemDiv = $(cartId);
				if (cartItemDiv.length > 0) { // Update info:
					var quantityElem = $(cartId + " .quantity .amount");
					var priceElem = $(cartId + " .price .amount");
					var changed = quantityElem.text() != data.Items[i].Quantity.toString() || 
						priceElem.text() != data.Items[i].UnitPrice.GrossPrice.toString();
					quantityElem.text(data.Items[i].Quantity);
					priceElem.text(data.Items[i].TotalPrice.GrossPrice);
					if (changed) changedItem = cartItemDiv;
				}else { // Create new cart item div:
					cartContainer.append(tmpl("cart_item_tmpl", data.Items[i]));
					rebindAllRemoveItemLinks();
					changedItem = $(cartId);
				}
			}
		}
		if (null != changedItem)
			changedItem.effect("highlight", {color:'#FFD42A'}, 1000);
		
		// Update no. of items:
		$("#cart .summary .amount").text((data.Items) ? data.TotalItemsCount.toString() : '0');
		// Update total:
		$("#cart .total").show(); // May have been hidden if no items on first render of page
		$("#cart .total .amount").text(data.TotalPrice.GrossPrice);
		if (data.TotalItemsCount>0)
			$("#prf-desc").show(); // May have been hidden if no items on first render of page
		else 
			$("#prf-desc").hide();
			
		// Update shipping:
		if (data.CantShip) {
			$("#cart-shipping .message").show();
			$("#cart-shipping .total").hide();
		}
		else {
			$("#cart-shipping .message").hide();
			$("#cart-shipping .total").show();
			$("#cart-shipping .total .amount").text(data.Shipping);
		}
		return changedItem;
	};

	var addProductToCart = function(productId) {
		var link = $(this);
		$.getJSON(siteRoot + '/ShoppingCart/AddProduct.aspx', {'product.id':productId /*,'shippingCountry.id':countryId */ }, 
			function(data) { 
				updateCart(data);
				$("#cart-updating").hide();
				$("#cart-updated").show();
			}
		);
	
		$("#cart-updating").show();
		$("#cart-updated").hide();
		$('#cart-update-dialog').jqmShow();
		return false;
	};

	// TODO: Fix css styling so we don't have to have 2 separate bindings here:
	$('.product a.add').bind('click', function() {
		var parent = $(this).parents('.product');
		var productId = parent.attr('id').substr('product-'.length);
		addProductToCart(productId);
		return false;
	});
	$('.product-detail a.add').bind('click', function() { 
		var parent = $(this).parents('.product-detail');
		var productId = ($(".listbox option:selected").length > 0) ? $(".listbox option:selected").attr("value") : parent.attr('id').substr('product-'.length);
		addProductToCart(productId);
		return false;
	});
	
	bindAllRemoveItemLinks();
		
	$("#shippingCountry").change(function () {
		$.getJSON(siteRoot + '/ShoppingCart/ChangeShippingCountry.aspx', 
			{'shippingCountry.id':$("#shippingCountry").val()}, 
			function(data) { 
				if(!data.EmptyCart)
					updateCart(data);
				$("#cart-shipping .updating").hide();
				$("#cart-shipping .response").show();
			}
		);
		$("#cart-shipping .response").hide();
		$("#cart-shipping .updating").show();
	});		
});
