$(document).ready(function() {
	//###############   Add to Basket Trigger Action   ###############
	$('.basket-add').click(function() {
		var $buyButton = $(this);
		$buyButton.hide();

		//###   Ensure Cart is open   ###
		if( $("#modules #shopping-basket").is('.closed') ) {
			$("#modules #shopping-basket h3").click();
		}

		AjaxComms("add", $(this));
		return false;
	});

	AddBasketInteraction();
}); //###   End of DOM Ready   ###

function AddBasketInteraction() {
	//###############   Delete item from Basket Trigger Action   ###############
	$(".basket-delete").click(function() {
		$(this).hide();
		AjaxComms("delete", $(this));
		return false;
	});

	//###############   Additional Basket Information Rollover Action   ###############
	$("#shopping-basket li").hoverIntent(function() {
		$(".basket-delete", jQuery(this)).stop().show().fadeTo("slow", 1);	//###   Need to Show due to Element hidden - only makes it appear instantly 1st time! Use FadeTo otherwise Stop doesn't work!
		$("p", jQuery(this)).slideDown("slow");
	}, function() {
		$(".basket-delete", jQuery(this)).stop().fadeTo("slow", 0);
		$("p", jQuery(this)).slideUp("slow");
	});
} //###   End AddBasketInteraction

function AjaxComms(Action, $Element) {

	//###   Hide trigger   ###
	$Element.hide();

	//###   Send form via AJAX   ###
	$.ajax({
		url: $Element.attr("href"),
		type: "POST",
		dataType: "html",
		success: function (html) {
			//alert("Success: " +  html);

			//###   Refresh/update the visible cart   ###
			GetCart();
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert("Error: " + textStatus + " - " + errorThrown);
		},
		complete: function (XMLHttpRequest, textStatus) {
			//alert("Complete: " + textStatus);

			//###   Show trigger again   ###
			//$Element.show();
			$Element.fadeIn("slow");
		}
	});
} //###   End AjaxComms

function GetCart() {
	if ($("#modules #shopping-basket").size() > 0) {
		var urlPath = "/AjaxHandler/basket";
	} else if ( $(".content #basket-contents").size() > 0 ) {
		var urlPath = "/AjaxHandler/payment-basket";
	}

	//###   Send via AJAX   ###
	$.ajax({
		url: urlPath,
		type: "POST",
		dataType: "html",
		success: function (html) {
			if ($("#modules #shopping-basket").size() > 0) {
				$("#modules #shopping-basket").replaceWith(html);
				AddBasketInteraction();
			}

			if ( $(".content #basket-contents").size() > 0 ) {
				//###   Payment pages   ###
				$(".content #basket-contents").replaceWith(html);
				AddBasketInteraction();
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert("Error: " + textStatus + " - " + errorThrown);
		}
	});
} //###   End GetCart

