// SHOW THE LAST ACTION MESSAGE AT THE TOP OF THE CART
function lastActionHero(theClass,theMessage) {
	// FADE IN
	$("#lastaction").hide().addClass(theClass).text(theMessage).fadeIn(1000,function() {
		// STAY ON SCREEN FOR HALF A SECOND
		$("#lastaction").fadeTo(500,1,function() {
			// FADE OUT
			$("#lastaction").fadeOut(1000,function() {
				$("#lastaction").removeClass(theClass);
			});
		});
	});
}

// BIND EVENTS TO THE INPUTS ETC. IN THE SHOPCART
function bindCartEvents() {
	// BIND A RELOADER ONTO THE QUANTITY BOXES
	$("#a4ucart input").change(function() {
		theID = $(this).attr("id");
		theVal = $(this).val();
		
		$(this).replaceWith(ajaxImg);
	
		// SEND THE MODIFICATION REQUEST
		$.post("/fastorder/fo_modprod.asp",{
			"prodNum": theID,
			"newQty":  theVal
		},function(responseText) {
			switch (responseText) {
				case "NaN":
					lastActionHero("actionerror","The new quantity must be numeric");
				break;
			}
			
			// RELOAD CART
			reloadShopcart();
		});
		
		return false;
	});

	// BIND ANOTHER RELOADER ONTO THE DELETE IMAGES	
	$("#a4ucart a").click(function() {
		$("img",this).attr("src","/images/ajax.gif");
	
		// GET THE DELETE LINK
		$.get($(this).attr("href"),function(responseText) {
			// RELOAD CART
			lastActionHero("actionok","Product removed from cart");
			reloadShopcart();
		});
		
		return false;
	});
	
	// AND ANOTHER RELOADER ON THE SCHOOL SESSION SELECTOR
	$("#School").change(function() {
		theObj = $(this);
		theVal = $(this).val();
		$(this).replaceWith(ajaxImg);
		
		// SEND THE SESSION MODIFIER
		$.get("/fastorder/fo_setschool.asp?session=" + theVal,function(responseText) {
			reloadShopcart();
			ajaxImg.replaceWith(theObj);
		});
	});
	
	// AND A FOURTH ONTO THE DELIVERY AREA SELECTOR
	$("#DelivArea").change(function() {
		theObj = $(this);
		theVal = $(this).val();
		$(this).replaceWith(ajaxImg);
		
		// SEND THE SESSION MODIFIER
		$.get("/fastorder/fo_setdeliv.asp?session=" + theVal,function(responseText) {
			// RELOAD CART
			lastActionHero("actionok","Delivery area changed");
			reloadShopcart();			
		});
	});
	
	// A FIFTH! ONTO THE EUROPEAN COUNTRY SELECTOR
	$("#DeliveryEuroCountry").change(function() {
		theObj = $(this);
		theVal = $(this).val();
		$(this).replaceWith(ajaxImg);
		
		// SEND THE SESSION MODIFIER
		$.get("/fastorder/fo_seteurodeliv.asp?session=" + theVal,function(responseText) {
			// RELOAD CART
			lastActionHero("actionok","European country changed");
			reloadShopcart();			
		});
	});
}

// RELOAD THE SHOPCART AND REBIND EVENTS
function reloadShopcart() {
	$("#a4ucart").load("/fastorder/inc_cart.asp",function() {
		bindCartEvents();
	});
	
	$("#minicart").load("/inc_minicart2.asp");
}

// EXECUTE DRILLDOWN SEARCH
function DrillDownSearch() {
	$("#searchresults").empty().append(ajaxImg);
	
	$.post("/fastorder/fo_search.asp",{
		"genre":   $("#Genre").val(),
		"subject": $("#Subject").val(),
		"stage":   $("#Stage").val(),
		"age":     $("#Age").val()
	},function(responseTable) {
		$("#searchresults").html(responseTable);
		bindSearchEvents();
	});
}
	
// EXECUTE KEYWORD SEARCH
function KeywordSearch() {
	$("#searchresults").empty().append(ajaxImg);
	searchText = $("#Keywords").val();
	
	$.post("/fastorder/fo_search.asp",{
		"Keywords": searchText
	},function(responseTable) {
		$("#searchresults").html(responseTable);
		bindSearchEvents();
	});
}

// EXECUTE SERIES SEARCH
function SeriesSearch() {
	$("#searchresults").empty().append(ajaxImg);
	searchText = $("#Series").val();

	$.post("/fastorder/fo_search.asp",{
		"series": searchText
	},function(responseTable) {
		$("#searchresults").html(responseTable);
		bindSearchEvents();
	});
}

// BIND EVENTS TO THE SEARCH RESULTS TABLE
function bindSearchEvents() {
	$("#searchtable tr.prodrow:odd").addClass("altrow");
	
	// INDIVIDUAL PRODUCT ADDITION LINKS
	$(".cartadd").click(function() {	
		// GET SIBLING PRODUCT IDS
		ParentTD  = $(this).parent();
		IDBox     = $(this);
		ProductID = $(this).siblings(".SearchProdID").val();
		Qty       = $(this).siblings(".SearchQty").val();
				
		ajaxImg.insertAfter(IDBox);
		
		// SEND AJAX CALL
		$.post("/fastorder/fo_addprod.asp?mode=prodid",{
			"ProdID": ProductID,
			"Qty":    Qty
		},function(responseText) {			
			switch (responseText) {
				case "OK":
					lastActionHero("actionok","Product added to cart successfully");
					reloadShopcart();
				break;
				case "PNF":
					lastActionHero("actionerror","Product could not be found");
				break;
				case "NaN":
					lastActionHero("actionerror","Quantity needs to be numeric");
				break;
				default:
					alert(responseText);
				break;
			}
	
			ajaxImg.remove();
			$("img",ParentTD).remove();
			tickImg.clone().insertAfter(IDBox);
		});
		
		return false;
	});
	
	// SERIES ADDITION LINK
	$(".cartseriesadd").click(function() {
		// GET SIBLING VALUES
		ParentTD = $(this).parent();
		IDBox    = $(this);
		SeriesID = $(this).siblings(".SearchSeries").val();
		Qty      = $(this).siblings(".SearchQty").val();
		
		ajaxImg.insertAfter(IDBox);
		
		// SEND AJAX CALL
		$.post("/fastorder/fo_addprod.asp?mode=series",{
			"Series": SeriesID,
			"Qty":    Qty
		},function(responseText) {
			switch (responseText) {
				case "OK":
					lastActionHero("actionok","Series added to cart successfully");
					reloadShopcart();
				break;
				case "PNF":
					lastActionHero("actionerror","Series could not be found");
				break;
				case "NaN":
					lastActionHero("actionerror","Quantity needs to be numeric");
				break;
			}

			ajaxImg.remove();
			$("img",ParentTD).remove();
			tickImg.clone().insertAfter(IDBox);
		});
		
		return false;
	});
}

$(document).ready(function() {
	// SET UP THE AJAX STUFF
	$.ajaxSetup({
		cache: false,
		error: function(request,statusText,exceptionThrown) {
			alert("An error occured with the last request - please retry shortly.");
			ajaxImg.remove();
		},
		timeout: 3000
	});
	
	// BIND EVENTS TO THE SHOPCART BOXES
	bindCartEvents();
	
	// PRELOAD THE ACTIVITY INDICATOR
	$("<img>").attr("src","/images/ajax.gif");
	
	// PREPARE COMMON OBJECTS
	ajaxImg    = $("<img id=\"ajax\" src=\"/images/ajax.gif\" width=\"16\" height=\"16\" alt=\"activity\" />");
	tickImg    = $("<img src=\"/images/tick.png\" width=\"16\" height=\"16\" alt=\"activity complete\" />");
		
	// GENRE DRILLDOWN LOADS SEARCH OPTIONS
	$("#Genre").change(function() {
		// REMOVE ALL CURRENT OPTIONS FROM BOXES
		$("#Subject, #Stage, #Age").removeOption(/./).addOption("","-");
		
		// POST TO DRILL DOWN FUNCTION
		$.getJSON("/fastorder/fo_drilldown.asp?genre=" + escape($(this).val()),function(responseJSON) {
			if (responseJSON.subjects) $("#Subject").addOption(responseJSON.subjects,false);
			if (responseJSON.stages)   $("#Stage").addOption(responseJSON.stages,false);
			if (responseJSON.ages)     $("#Age").addOption(responseJSON.ages,false);
		});
	});
	
	// DRILLDOWN
	$("#Subject, #Stage, #Age").change(DrillDownSearch);
	$("#ExecDDSearch").click(function() {
		DrillDownSearch();
		return false;
	});
	
	// KEYWORD SEARCH
	$("#Keywords").change(KeywordSearch);
	$("#ExecKWSearch").click(function() {
		KeywordSearch();
		return false;
	});
	
	// LOAD PRODUCTS FROM A SERIES WHEN SERIES SELECTED
	$("#Series").change(SeriesSearch);
	$("#ExecSeriesSearch").click(function() {
		SeriesSearch();
		return false;
	});
	
	// A4U XMLHTTP FUNCTIONALITY
	$("#AddISBN").click(function() {
		// SHOW ACTIVITY INDICATOR
		ajaxImg.insertAfter($("#AddISBN"));
		
		// SEND AJAX CALL
		$.post("/fastorder/fo_addprod.asp?mode=isbn",{
			"ISBN":    $("#ISBN").val(),
			"ISBNQty": $("#ISBNQty").val()		
		},function(responseText) {
			switch (responseText) {
				case "OK":
					lastActionHero("actionok","Product added to cart successfully");
					reloadShopcart();
					
					// RESET ISBN FORM
					$("#ISBN").val("");
					$("#ISBN")[0].focus();
					$("#ISBNQty").val("1");
				break;
				case "PNF":
					lastActionHero("actionerror","Product could not be found");
				break;
				case "NaN":
					lastActionHero("actionerror","Quantity needs to be numeric");
					$("#ISBNQty")[0].focus();
				break;
			}
			
			ajaxImg.remove();
		});
		
		return false;
	});
	
	// COPY BILLING ADDRESS
	$("#usebilling").click(function() {
		if ($(this).is(":checked")) {
			$("#shipforename, #shipsurname, #shipcompanyname, #shipemail, #shipaddress1, #shipaddress2, #shipaddress3, #shipcity, #shipstate, #shippostcode, #shipcountry, #shipphone").each(function() {
				theBillID = $(this).attr("id").replace(/ship/,"");
				$(this).val($("#" + theBillID).val());
			});
		} else {
			// RESET TO DEFAULTS
			$("#shipforename, #shipsurname, #shipcompanyname, #shipemail, #shipaddress1, #shipaddress2, #shipaddress3, #shipcity, #shipstate, #shippostcode, #shipcountry, #shipphone").val("");
		}
	});
});
