/** 
 * @fileOverview Order and basket methods.
 * @author Oliver Bishop / Tom McCourt
 * @version 1.0.0
 * @changeLog Created.
 */

var UKISA = UKISA || {};
UKISA.site = UKISA.site || {};
UKISA.site.Order = UKISA.site.Order || {};

YAHOO.util.Event.onDOMReady(function() {
	UKISA.site.Order.Basket.init();
});

UKISA.site.Order.Basket = {
	/** 
	 * Find all the classes of "add-to-basket" to automatically give them basket funtionality. The form must have the following elements in order for this to work.
	 * @example
	 * <form  class="add-to-basket">
	 * 	<input type="hidden" name="image-src" value="image_path.gif" />
	 * 	<input type="hidden" name="product-name" value="product name" />
	 * 	<input class="submit" />
	 * </form>
	 */
	init: function() {
		var use, form, i, ix, util;

		use = UKISA.locale.get("site.Order.Basket.automaticAddToBasket");

		if (!use || use === false) {
			return;
		}

		util = YAHOO.util;

		form = util.Selector.query("form.add-to-basket", "body");

		for (i = 0, ix = form.length; i < ix; i++) {
			util.Event.addListener(form[i], "submit", function(e) {

				util.Event.preventDefault(e);
				util.Event.stopEvent(e);

				UKISA.site.Order.Basket.add(util.Selector.query("input.submit", this, true));
			});
		}
	},
	/**
	 * This is the mini basket functionality.
	 */ 
	Mini: {
		/**
		 * Fetch the mini basket update with Ajax.
		 */
		update: function() {
			var canvas, callback, ajax, el;

			// Get the canvas DIV
			canvas = document.getElementById("mini-basket");

			callback = {
				success: function(o) {
					var response, nav;
					
					response = o.responseText;

					if (response != "" && canvas) {
						canvas.innerHTML = response;
					}
				},
				timeout: 8000
			};	

			// Send the Ajax request.
			ajax = YAHOO.util.Connect.asyncRequest("POST", "/ajax/order/mini_basket.jsp", callback);

			return false;
		}
	},
	/**
	 * Update the quantity.
	 */
	update: function(el, id) {
		var canvas, callback, ajax, qs;

		canvas = document.getElementById("basket-totals");

		callback = {
			success: function(o) {
				var json;

				json = YAHOO.lang.JSON.parse(o.responseText);

				var cell = YAHOO.util.Selector.query("td.t-line-total", "basket-row-" + id, true);

				cell.innerHTML = json[id].total;

				// Update the totals.
				UKISA.site.Order.Basket.totals();

				// Reset the button.
				el.value = "Update quantity";
			},
			failure: function() {
				// Reset the button.
				el.value = "Update quantity";
			},
			timeout: 8000
		};	

		el.value = "Please wait";

		// Set up the query string.
		qs = YAHOO.util.Connect.setForm("basket-form");  

		// Replace the success/fail urls that were intended for the page.
		qs = UKISA.util.URL.replaceParam("successURL", "/ajax/order/quantity_update.jsp", YAHOO.util.Connect);
		qs = UKISA.util.URL.replaceParam("failURL", "/ajax/order/quantity_update.jsp", YAHOO.util.Connect);

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("POST", "/servlet/ShoppingBasketHandler", callback);

		return false;
	},
	/**
	 * Add an item to the basket.
	 */
	add: function(bt) {
		var el, modal, canvas, content, callback, busy, ajax, qs, action, message, itemId, itemIds, i, ix, modalError, modalFinish;

		el = YAHOO.util.Dom.getAncestorByTagName(bt, "form");

		modalError = function() {
			var a = document.createElement("div");
			a.id = "add-to-basket-content";

			var b = document.createElement("p");
			b.className = "error";
			b.innerHTML = "Sorry, there was a problem and the item was not added to your basket.";

			a.appendChild(b);

			return a;
		};

		modalFinish = function() {
			var a, b, c, d, e, f, g;

			a = document.createElement("div");
			a.id = "add-to-basket-content";

			b = document.createElement("div");
			b.className = "content";


			d = document.createElement("p");
			
			if (el["product-name"]) {
				d.innerHTML = "<strong>" + el["product-name"].value + "</strong> was successfully added to your basket.";
			} else {
				d.innerHTML = "The item was added to your basket";
			}

			g = document.createElement("p");
			g.className = "action";
		
			e = document.createElement("a");
			e.className = "view-basket";
			e.innerHTML = "<img src=\"/web/images/buttons/go_checkout.gif\" alt=\"View your basket\" />";
			e.href = "/servlet/ShoppingBasketHandler?failURL=/order/index.jsp&successURL=/order/index.jsp";

			f = document.createElement("input");
			f.className = "continue";
			f.alt = "Continue shopping"
			f.src = "/web/images/buttons/continue.gif";
			f.type = "image";
			f.onclick = function() {
				UKISA.widget.Container.hide();
				UKISA.widget.Container.destroy();
				UKISA.widget.Container = null; 
			};

			b.appendChild(d);
			g.appendChild(e);
			g.appendChild(f);
			b.appendChild(g);

			if (el["image-src"]) {
				c = document.createElement("img");
				c.className = "product-image";
				c.alt = (el["product-name"]) ? el["product-name"].value : "";
				c.src = el["image-src"].value;
				a.appendChild(c);
			}
			a.appendChild(b);

			return a;
		};

		// Create the modal.
		modal = new UKISA.widget.Modal("add-to-basket-modal");
		modal.show();

		// Get the canvas DIV
		content = document.getElementById("content");

		busy = YAHOO.util.Selector.query("input[name=submit]", el, true);

		message = document.getElementById("add-to-basket-status");

		if (message) {
			message.parentNode.removeChild(message);
		}

		message = document.createElement("p");
		message.className = "error";
		message.id = "add-to-basket-status";

		callback = {
			success: function(o) {
				var json, q;

				if (busy) {
					busy.alt = "Add to basket";
				}

				json = YAHOO.lang.JSON.parse(o.responseText);

				if (json.success) {
					//message.className = "success";
					//message.innerHTML = json.message;

					modal.setBody(modalFinish());
					q = YAHOO.util.Selector.query("p strong", "add-to-basket-modal", true)
					if (q) {
						Cufon.replace(q);
					}

					UKISA.site.Order.Basket.Mini.update();
				} else {
					//message.innerHTML = json.message;
					
					modal.setBody(modalError());
				}
				//el.appendChild(message);
			},
			failure: function(o) {
				if (busy) {
					busy.alt = "Add to basket";
				}

				//message.innerHTML = json.message;
				//el.appendChild(message);

				modal.setBody(modalError());
			},
			timeout: 8000
		};	

		// Get the ration button value.
		if (el["ItemID"] && el["ItemID"].length) {
			for (i = 0, ix = el["ItemID"].length; i < ix; i++) {
				if (el["ItemID"][i].checked) {
					itemId = el["ItemID"][i].value;
					break;
				}
			}
		} else if (el["ItemID"]) {
			itemId = el["ItemID"].value;
		} else {
			itemId = "";
		}

		// Get the ration button value.
		if (el["ItemIDs"] && el["ItemIDs"].length) {
			for (i = 0, ix = el["ItemIDs"].length; i < ix; i++) {
				if (el["ItemIDs"][i].checked) {
					itemIds = el["ItemIDs"][i].value;
					break;
				}
			}
		} else if (el["ItemIDs"]) {
			itemIds = el["ItemIDs"].value;
		} else {
			itemIds = "";
		}
		
		// Set up the query string.
		qs = [
			"ItemType=" + el["ItemType"].value,
			"ItemID=" + itemId,
			"ItemIDs=" + itemIds,
			"action=" + el["action"].value,
			"Quantity=" + (typeof el["Quantity"] !== "undefined" || !el["Quantity"]) ? el["Quantity"].value : "1",
			"successURL=/ajax/response_json.jsp",
			"failURL=/ajax/response_json.jsp"
		];

		if (typeof el["Note"] !== "undefined") {
			qs.push("Note=" + el["Note"].value);
		}

		// IE6 workaround where the input names cannot match the <form> attribute names.
		action = (el.getAttributeNode) ? el.getAttributeNode("action").value : el.getAttribute("action");

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("POST", action, callback, qs.join("&"));

		return false;
	},

		
	/**
	 * Add an item to the basket replacing the Add to Basket button. THIS WAS DONE BECAUSE OF AN UNKNWOWN YUI CONTAINER ERROR IN IE - ERROR MESSAGE: "FAILED" 
	 */
	addInline: function(bt) {
		var el, submit, status;

		el = YAHOO.util.Dom.getAncestorByTagName(bt, "form");

		submit = bt;

		submit.src = "/web/images/global/loading.gif";
		submit.alt = "Please wait";

		status = document.createElement("p");
		
		callback = {
			success: function(o) {
				var json, q;

				json = YAHOO.lang.JSON.parse(o.responseText);

				if (json.success) {

					status.innerHTML = "<strong>The item was successfully added to your basket.</strong>";

					submit.parentNode.replaceChild(status, submit);

					UKISA.site.Order.Basket.Mini.update();
				} else {
					
					status.innerHTML = "<strong>Sorry, there was a problem and the item has not been added to your basket.</strong>";

					submit.parentNode.replaceChild(status, submit);
				}
			},
			failure: function(o) {
				
				status.innerHTML = "<strong>Sorry, there was a problem and the item has not been added to your basket.</strong>";

				submit.parentNode.replaceChild(status, submit);

			},
			timeout: 8000
		};	

		// Get the ration button value.
		if (el["ItemID"] && el["ItemID"].length) {
			for (i = 0, ix = el["ItemID"].length; i < ix; i++) {
				if (el["ItemID"][i].checked) {
					itemId = el["ItemID"][i].value;
					break;
				}
			}
		} else if (el["ItemID"]) {
			itemId = el["ItemID"].value;
		} else {
			itemId = "";
		}
		
		// Set up the query string.
		qs = [
			"ItemType=" + el["ItemType"].value,
			"ItemID=" + itemId,
			"action=" + el["action"].value,
			"Quantity=" + (typeof el["Quantity"] !== "undefined" || !el["Quantity"]) ? el["Quantity"].value : "1",
			"successURL=/ajax/response_json.jsp",
			"failURL=/ajax/response_json.jsp"
		];

		if (typeof el["Note"] !== "undefined") {
			qs.push("Note=" + el["Note"].value);
		}

		// IE6 workaround where the input names cannot match the <form> attribute names.
		action = (el.getAttributeNode) ? el.getAttributeNode("action").value : el.getAttribute("action");

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("POST", action, callback, qs.join("&"));

		return false;
	},

	/**
	 * Delete an item from the basket.
	 */
	remove: function(el, basketItemId) {
		var canvas, basket, div, tbody, table, row, cell, callback, ajax, instance;

		instance = this;

		// Create all the elements.
		canvas = document.getElementById("basket-row-" + basketItemId);
		basket = document.getElementById("basket");
		div = document.createElement("div");
		tbody = document.createElement("tbody"); // Must have a <TBODY> or this won't work in IE6.
		table = document.createElement("table");
		row = document.createElement("tr");
		cell  = document.createElement("td");

		// Add all the elements together.
		tbody.appendChild(canvas.cloneNode(true));
		table.appendChild(tbody);
		div.appendChild(table);
		cell.appendChild(div);
		row.appendChild(cell);
		canvas.parentNode.replaceChild(row, canvas);

		// Set styles.
		cell.className = "animate";
		cell.setAttribute("colSpan", basket.rows[0].cells.length); // Need this camelcase for IE6.
		div.style.overflow = "hidden";

		// Change the button to a busy status and add class to change the CSS background.
		el.value = "Busy";
		el.className = "busy";
	
		// Make the Ajax call to remove the item from the basket.
		callback = {
			success: function(o) {
				var anim, fields, items, group, i, ix;

				// Change the button state.
				el.value = "Removed";
				el.className = "";

				// Animate the DIV element.
				anim = new YAHOO.util.Anim(div, { height: { to: 0 } }, .5, YAHOO.util.Easing.easeOut);
				anim.onComplete.subscribe(function() {
					var msgAnim, rows;
					// Count the number of table rows minus 1 (the headers) to get the number of products.
					rows = basket.getElementsByTagName("tr");

					// Count the remaining rows (2 equals headers plus last product).
					if (rows.length === 3) {
						// Resuse the row to add a status message.
						div.innerHTML = "<p class=\"empty-basket\">There are no items in your basket.</p>";
						
						msgAnim = new YAHOO.util.Anim(div, { height: { to: 40 } }, .5, YAHOO.util.Easing.easeOut);
						msgAnim.onComplete.subscribe(function() {
							// Update the mini basket with the new quantity.
							UKISA.site.Order.Basket.Mini.update();
						});
						msgAnim.animate(); 

					} else {
						// Get rid of the row.
						row.parentNode.removeChild(row);
					}

					// Update the BasketItemIDs field for quantity updates.
					fields = YAHOO.util.Selector.query("input.item-id", basket);
					items = [];

					for (i = 0, ix = fields.length; i < ix; i++) {
						items.push(fields[i].value);
					}

					group = document.getElementById("basket-item-group");

					if (group) {
						group.value = items.join(",");
					}

				}); 
				anim.animate(); 
				
				instance.totals();
			},
			failure: function() {},
			timeout: 8000
		};	

		// Set up the query string.
		qs = [
			"action=",
			"delete",
			"&",
			"BasketItemID=",
			basketItemId,
			"&",
			"successURL=",
			"/ajax/response_json.jsp",
			"&",
			"failURL=",
			"/ajax/response_json.jsp"
		];

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("POST", "/servlet/ShoppingBasketHandler", callback, qs.join(""));
	
		return false;
	},
	/**
	 * Get the totals for the basket with Ajax.
	 */
	totals: function() {
		var canvas, callback, ajax, qs;

		canvas = document.getElementById("basket-totals");

		callback = {
			success: function(o) {
				var response, nav;
				
				response = o.responseText;

				if (response != "") {
					canvas.innerHTML = response;
				}
			},
			failure: function() {},
			timeout: 8000
		};	

		// Set up the query string.
		qs = [
			"successURL=",
			"/ajax/order/basket_totals.jsp",
			"&",
			"failURL=",
			"/ajax/order/basket_totals.jsp"
		];

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("POST", "/servlet/ShoppingBasketHandler", callback, qs.join(""));

		return false;
	}
};

UKISA.site.Order.Payment = {
	toggleBillingAddress: function(el) {
		if (!el.checked) {
			document.getElementById("billingAddress").disabled = false;
			document.getElementById("billingAddress").value = "";
			document.getElementById("billingTown").disabled = false;
			document.getElementById("billingTown").value = "";
			document.getElementById("billingCounty").disabled = false;
			document.getElementById("billingCounty").value = "";
			document.getElementById("billingPostCode").disabled = false;
			document.getElementById("billingPostCode").value = "";
		} else {
			document.getElementById("billingAddress").disabled = true;
			document.getElementById("billingAddress").value = document.getElementById("address").value;
			document.getElementById("billingTown").disabled = true;
			document.getElementById("billingTown").value = document.getElementById("town").value;
			document.getElementById("billingCounty").disabled = true;
			document.getElementById("billingCounty").value = document.getElementById("county").value;
			document.getElementById("billingPostCode").disabled = true;
			document.getElementById("billingPostCode").value = document.getElementById("postcode").value;
		}
	}
};
