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

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

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

	//###   Add the interaction to the mini-basket   ###
	AddBasketInteraction();

	//###############   Add to Basket Form Action (links or buttons - non-complex)   ###############
	$("#mm-basket-add-form").validate({
		submitHandler: function(form) {
			//###   Disable the Submit button   ###
			$("#mm-basket-add-form button").fadeTo("slow", 0.20).attr("disabled","disabled");

			SubmitUpdateProduct( $("#mm-basket-add-form") );
			return false;
		}
	});
	$("#rm-basket-add-form").validate({
		submitHandler: function(form) {
			//###   Disable the Submit button   ###
			$("#rm-basket-add-form button").fadeTo("slow", 0.20).attr("disabled","disabled");

			SubmitUpdateProduct( $("#rm-basket-add-form") );
			return false;
		}
	});

	//###   Form values adjusted - so need to refresh the price   ###
	$("#rm-basket-add-form button[type='submit'], #mm-basket-add-form button[type='submit']").fadeTo("slow", 0.20).attr("disabled","disabled").addClass("disabled");
	if ( $("#product-details #rm-width:hidden").length > 0 && $("#product-details #rm-drop:hidden").length > 0 ) {
		$("#rm-basket-add-form button[type='submit']").fadeTo("fast",1).removeAttr('disabled').removeClass('disabled');
	}

$("form input[name='width'], form select[name='width'], form input[name='drop'], form select[name='drop']").keypress(function (e) {
	if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
		return false;
	}
});

	$("form select[name='width'], select[name='drop']").bind(($.browser.msie ? "click" : "change"), function () {
		UpdateForm($(this));
	});

//	$("form input[name='width'], form select[name='width'], form input[name='drop'], select[name='drop']").bind(($.browser.msie ? "click" : "change"), function () {
//	$("form input[name='width'], form select[name='width'], form input[name='drop'], select[name='drop']").blur(function () {
	$("form input[name='quantity'], form input[name='width'], form select[name='width'], form input[name='drop'], form select[name='drop']").keyup(function () {
		UpdateForm($(this));
	});
	
	function UpdateForm($Field) {
		var $Parent = $Field.parents("form");
		var $InputWidth = $Parent.find("input[name='width']");
		var $InputDrop = $Parent.find("input[name='drop']");
		var $SelectWidth = $Parent.find("select[name='width']");
		var $SelectDrop = $Parent.find("select[name='drop']");
		var Incomplete = false;
		
		//###   Round up   ###
		var originalValue = $Parent.find("input[name='width']").val();
		var roundedValue = Math.ceil( originalValue );
		if (roundedValue != originalValue && roundedValue > 0)
			$Parent.find("input[name='width']").val( roundedValue );
		originalValue = $Parent.find("input[name='drop']").val();
		roundedValue = Math.ceil( originalValue );
		if (roundedValue != originalValue && roundedValue > 0)
			$Parent.find("input[name='drop']").val( roundedValue );
		
		GetItemPrice( $Field );

		if ( $InputWidth.size() > 0 && ( $InputWidth.attr("value") == "Enter width" || $InputWidth.attr("value") == "" || parseFloat( $InputWidth.attr("value") ) <= 0) ) {
			Incomplete = true;
		}
		if ( $SelectWidth.size() > 0 && ( $SelectWidth.attr("value") == "Select width" || $SelectWidth.attr("value") == "" ) ) {
			Incomplete = true;
		}
		if ( $InputDrop.size() > 0 && ( $InputDrop.attr("value") == "Enter drop" || $InputDrop.attr("value") == "" || parseFloat( $InputDrop.attr("value") ) <= 0) ) {
			Incomplete = true;
		}
		if ( $SelectDrop.size() > 0 && ( $SelectDrop.attr("value") == "Select drop" || $SelectDrop.attr("value") == "" ) ) {
			Incomplete = true;
		}

/*		if ( ($Parent.find("input[name='width']").attr("value") != "Enter width" && $Parent.find("select[name='width']").attr("value") != "Select width") 
		&& ($Parent.find("input[name='width']").attr("value") != "" || $Parent.find("select[name='width']").attr("value") != "") 
		&& (parseFloat($Parent.find("input[name='width']").attr("value")) > 0) || (parseFloat($Parent.find("select[name='width']").attr("value")) > 0) 
		&& ($Parent.find("input[name='drop']").attr("value") != "Enter drop" && $Parent.find("select[name='drop']").attr("value") != "Select drop")
		&& ($Parent.find("input[name='drop']").attr("value") != "" || $Parent.find("select[name='drop']").attr("value") != "")
		&& (parseFloat($Parent.find("input[name='drop']").attr("value")) > 0) || (parseFloat($Parent.find("select[name='drop']").attr("value")) > 0) ) { */
		if (Incomplete) {
			$Parent.find(".from").fadeIn("normal");
			$Parent.find("button[type='submit']").fadeTo("slow", 0.20).attr("disabled","disabled").addClass("disabled");
		} else {
			$Parent.find(".from").fadeOut("normal");
			$Parent.find("button[type='submit']").fadeTo("slow", 1).removeAttr("disabled").removeClass("disabled");
		}
	}
	
//	$("#content form input").change(function() {
//	$("#content #rm-basket-add-form input, #content #mm-basket-add-form input").change(function() {
	$("#content #rm-basket-add-form input:not([name='width'],[name='depth']), #content #mm-basket-add-form input:not([name='width'],[name='depth'])").bind(($.browser.msie ? "click" : "change"), function () {
		GetItemPrice( $(this) );
	});
}); //###   End of DOM Ready   ###

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

	$("#shopping-basket #basket-contents").hide();
	$("#shopping-basket #mini-cart-controls li:first a").click(function () {
		$("#shopping-basket #basket-contents").toggle(
			"slow",
			function callback() {
				if ( $(this).is(':hidden') )
					$("#shopping-basket #mini-cart-controls li:first a").html("View basket");
				else
					$("#shopping-basket #mini-cart-controls li:first a").html("Hide basket");
		});

		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!
	}, function() {
		$(".basket-delete", jQuery(this)).stop().fadeTo("slow", 0);
	});
}

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);

			//var URLSegments = $Element.attr("href").split("/");
			//alert("URL:" + URLSegments.pop());

			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");
		}
	});
}

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 form via AJAX   ###
	$.ajax({
		url: urlPath,
		type: "POST",
		dataType: "html",
		success: function (html) {
			//alert(html);
			if ($("#modules #shopping-basket").size() > 0) {
				$("#modules #shopping-basket").parent().replaceWith(html);
				AddBasketInteraction();
				//###   Open Cart   ###
				$("#shopping-basket #mini-cart-controls li:first a").trigger('click');

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

function GetItemPrice( $fieldID ) {
//	var EntryID = $fieldID.attr("rel");
	var EntryID = $("#entry_id").attr("rel");

	if (EntryID.length > 0) {
		//###   Send form via AJAX   ###
		$.ajax({
			url: "/AjaxHandler/price/" + EntryID,
			type: "POST",
			data: $fieldID.parents("form").serialize(),
			dataType: "html",
			success: function (html) {
				$fieldID.parents("form").find(".price").html(html);
				//alert(html);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//alert(textStatus + errorThrown);
				//$("#contact-form button").fadeTo("slow", 1).removeAttr("disabled")
			},
			complete: function (XMLHttpRequest, textStatus) {
				//alert(textStatus);
			}
		});
	}
}



//###   ADD TO BASKET FORM SUBMISSION  ###
function SubmitUpdateProduct($form) {
	//###   Send form via AJAX   ###
	$.ajax({
		url: $form.attr("action"),
		type: "POST",
		data: $form.serialize(),
		dataType: "html",
		success: function (html) {
			//alert(html);
			GetCart();
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//alert(textStatus + errorThrown);
		},
		complete: function (XMLHttpRequest, textStatus) {
			//alert(textStatus);
			if ( $("#madetomeasure-panel").is(':hidden') || $("#madetomeasure-panel").length == 0 ) {
				$("#rm-basket-add-form button").fadeTo("slow", 1).removeAttr("disabled");
			} else {
				$("#mm-basket-add-form button").fadeTo("slow", 1).removeAttr("disabled");
			}
		}
	});
} //###   End of SubmitAddProduct function   ###

