var CART_SUMMARY = "CartSummary";

function removeCartSummary() {
	Microgroove.helpers.killCookie(CART_SUMMARY, "/");
}

function updateCartSummary(totalItems, totalValue) {
    
	Microgroove.helpers.setMultiValueCookie(CART_SUMMARY,
		new Array("totalItems", "totalValue"),
		new Array(totalItems,totalValue), 
		null, "/");
}

function postShoppingCart(url, parameters, redirect) {
	$.post(url, parameters,
	  function(data){
	  	if ( data.returnCode == 0 ) {
	  		$.jGrowl("This item could not be added to your cart at this time.", {
				theme:  'error'
			});
	  		return;
	  	}
	    else if ( data.returnCode == 2 ) {
  			$.jGrowl("This item is already in your cart.", {
				theme: 'warning'
			});
	    	return;
	    }
	
			//insert the cart summary into a cookie so other pages can get access to the
			//summary without having to call the ShopBroker
	    updateCartSummary(data.totalItems, data.totalValue);
	    	
	    if ( redirect != null && redirect != "null" ) {
	    	window.location = redirect;
	    }
	    	
  		$.jGrowl("This item has been added to your cart.");

	    //update the cart summary
	    $("#cartCount").text(data.totalItems);
	    $("#cartPrice").text(data.totalValue);
	    $("#cartCreditBalance").text(data.creditBalance);
	  }
	  , "json");
}

function postCreditBalance(url, parameters) { 
	$.post(url, parameters,
	  function(data){
	  	if ( data.returnCode == 0 ) {
	  		$.jGrowl("There was a problem retrieving your store credit.", {
				theme:  'error'
			});
	  		return;
	  	}

	    $("#cartCreditBalance").text(data.creditBalance);
	  }
	  , "json");
}

jQuery(function(){
	var holder = Microgroove.helpers.getMultiValueCookie("HolderDetails", "a");
	if ( holder != null && holder != "null" ) {
		postCreditBalance('/digirama/customerbroker.ashx', '');
		$("#storeCredit").addClass("show");
	}
	
	//bind an event to the click event of "add to cart" buttons
	$(".btn-cart").bind("click", function(e){
		var mediaLicenseId = $(this).attr("medialicenseid");
		postShoppingCart('/digirama/shopbroker.ashx', 'MediaLicenseID=' + mediaLicenseId);
	});

	//check the cookie on page load to see if anything has been placed in the cart.
	//if so we get he values and update the value in the cart summary
	//in the same that we do when we originally add an item to the cart
	var totalValue = Microgroove.helpers.getMultiValueCookie(CART_SUMMARY, "totalValue");
	if ( totalValue != null && totalValue != "null" )
    $("#cartPrice").text(totalValue);
	
	var totalItems = Microgroove.helpers.getMultiValueCookie(CART_SUMMARY, "totalItems");
	if ( totalItems != null && totalItems != "null" )
		$("#cartCount").text(totalItems);
});