/* LIBRARY SCRIPTS
 * Specific functionality
 * 1.0
 
 * SCRIPT CHANGES (Eg. Date (dd/mm/yyyy), Name (Tom.McCourt), Change (function name))
 *
 * 13/07/2007, Tom.McCourt, Created
 * 17/08/2007, Mick Harper-Jones, Added Function OnLoadEvent().
------------------------------------------------------------*/

/* Load
------------------------------*/
var Event = {	
	onload: [],
	loaded: function() {
		if (arguments.callee.done) return;
		arguments.callee.done = true;
		for (i = 0;i < Event.onload.length;i++) Event.onload[i]();
	},
	pageLoad : function(func) {
		var oldonload = window.onload;
		if (typeof window.onload != "function") {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	},
	domLoad : function(fireThis) {
		this.onload.push(fireThis);
		if (document.addEventListener) 
			document.addEventListener("DOMContentLoaded", Event.loaded, null);
		if (/KHTML|WebKit/i.test(navigator.userAgent)) { 
			var _timer = setInterval(function() {
				if (/loaded|complete/.test(document.readyState)) {
					clearInterval(_timer);
					delete _timer;
					Event.loaded();
				}
			}, 10);
		}
		/*@cc_on @*/
		/*@if (@_win32)
		var proto = "src='javascript:void(0)'";
		if (location.protocol == "https:") proto = "src=//0";
		document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
		var script = document.getElementById("__ie_onload");
		script.onreadystatechange = function() {
		    if (this.readyState == "complete") {
		        Event.loaded();
		    }
		};
		/*@end @*/
		this.pageLoad(Event.loaded);
	},
	add: function(e, type ,fn) {
		if (e.attachEvent) {
		e['e' + type + fn] = fn;
		e[type + fn] = function() {e['e' + type + fn](window.event);}
		e.attachEvent('on' + type, e[type + fn]);
		} else
		e.addEventListener(type, fn, false);
	},
	remove: function(e, type, fn) {
		if (e.detachEvent) {
		e.detachEvent('on' + type, e[type + fn]);
		e[type + fn] = null;
		} else
		e.removeEventListener(type, fn, false);
	}
};
Event.domLoad(function() {
		PopUp.hookup("external", function() {
			return PopUp.newWindow(this);
		});
		
		if (Config.isPlanet())
			Navigation.init();
		
		ProductList.init();
		flickerFix();
		MiniSearch.init();
		MiniNewsLetterSignUp.init();
		MiniBasket.init();
		if(typeof sIFR == "function"){
			//sIFR.replaceElement(named({sSelector: "h1", sFlashSrc: UrlUtils.absoluteWebPath() + "/styles/font/gill-sans-light.swf", sColor: "#666666", sWmode: "transparent"}));
		}
		var bodyId = document.body.id;
		switch(bodyId) {
			case "home-page":
				Site.Pages.Home.Merchandising.init();
			break;
			case "product-details-page":
				Product.init();
				initLightbox();
			break;
		}
	}
);				

/* Zoom
------------------------------*/
var ProductZoom = {
	windowWidth		: 393,	// Size of zoom window
	windowHeight	: 409,
	viewportWidth	: 80,	// Size of viewport
	viewportHeight	: 80,
	productImg		: null,
	viewport		: null,
	zoomWindow		: null,
	zoomWindowImg	: null,
	sTop			: 0,
	sLeft			: 0,
	sBottom			: 0,
	sRight			: 0,
	init : function() {
		this.smallImg = $('main-product-image');

		if (!this.smallImg && this.smallImg.parentNode.nodeName.toLowerCase() !== ' a') { return; }

		this.productImg	= document.getElementById('drag-area');

		this.zoomWindow	= document.createElement('div');
		this.zoomWindow.id = 'product-zoom';

		this.zoomWindowImg = document.createElement('img');
		this.zoomWindow.appendChild(this.zoomWindowImg);
		document.body.appendChild(this.zoomWindow);

		// Load up the image using the anchor object
		this.load(this.smallImg.parentNode);

		if (!this.viewport) {
			this.viewport = document.createElement('div');
			this.viewport.id = 'viewport';
			document.body.appendChild(this.viewport);
		}

		this.productImg.onmousemove		= this.showZoom;
		this.productImg.onmouseout		= this.hideZoom;

		this.viewport.onmousemove		= this.showZoom;
		this.viewport.onmouseout		= this.hideZoom;	

		this.zoomWindow.style.width		= this.windowWidth + 'px';
		this.zoomWindow.style.height	= this.windowHeight + 'px';

		this.viewport.style.width		= this.viewportWidth + 'px';
		this.viewport.style.height		= this.viewportWidth + 'px';
		
		// Remove the alt text to stop it breaking the effect
		this.smallImg.alt = '';

		// Small image positions - MooTools
		//this.sTop		= this.getTop(this.smallImg);
		//this.sLeft	= this.getLeft(this.smallImg);
		this.sTop		= this.smallImg.getTop();
		this.sLeft		= this.smallImg.getLeft();
		this.sBottom	= this.sTop + this.smallImg.height;
		this.sRight		= this.sLeft + this.smallImg.width;		
		Debug.w('Top = ' + this.sTop + ' | Left = ' + this.sLeft);
	},
	load : function(e) {
		this.zoomWindowImg.src	= e.href;
		this.zoomWindowImg.alt	= e.title;
	},
	showZoom : function(event) {
		var PZ = ProductZoom;

		// Set the scale
		var scaleX	= PZ.zoomWindowImg.width / PZ.smallImg.width;
		var scaleY	= PZ.zoomWindowImg.height / PZ.smallImg.height;	

		// Get object detection mouse coords
		var mouseX	= (window.event) ? window.event.clientX : event.pageX;
		var mouseY	= (window.event) ? window.event.clientY : event.pageY;

		// Calculate offset
		var offsetWindowX	= Math.floor(PZ.windowWidth / scaleX);
		var offsetX			= Math.floor(offsetWindowX / 2);
		var offsetWindowY	= Math.floor(PZ.windowHeight / scaleY);
		var offsetY			= Math.floor(offsetWindowY / 2);

		// Stop and exit zoom if mouse is out of bounds of the small image
		if (mouseX < PZ.sLeft || mouseX > PZ.sRight || mouseY < PZ.sTop || mouseY > PZ.sBottom) {
			PZ.viewport.style.display	= 'none';
			PZ.zoomWindow.style.display = 'none';
			return;
		}
	
		// Set zoom container scroll sizes to position image
		PZ.zoomWindow.style.display = 'block';
		PZ.zoomWindow.scrollLeft	= scaleX * (mouseX - offsetX - PZ.sLeft);
		PZ.zoomWindow.scrollTop		= scaleY * (mouseY - offsetY - PZ.sTop);
		
		Debug.w('Scroll Top = ' + (scaleY * (mouseY - offsetY - PZ.sTop)) + ' | Scroll Left = ' + (scaleX * (mouseX - offsetX - PZ.sLeft)));

		// Mootools set CSS styles
		PZ.viewport.style.top		= mouseY - (PZ.viewportWidth / 2) + 'px';
		PZ.viewport.style.left		= mouseX - (PZ.viewportHeight / 2) + 'px';
		PZ.viewport.style.display	= 'block';
	},
	hideZoom : function(event) {
		ProductZoom.viewport.style.display		= 'none';
		ProductZoom.zoomWindow.style.display	= 'none';
	},
	getTop : function(e) {
			var curtop = 0;
			if (e.offsetParent) {
				while (e.offsetParent) {
					curtop += e.offsetTop
					e = e.offsetParent;
				}
			} else if (e.y) {
				curtop += e.y;
				}
			return curtop;
	},
	getLeft : function(e) {
		var curleft = 0;
		if (e.offsetParent) {
			while (e.offsetParent) {
				curleft += e.offsetLeft
				e = e.offsetParent;
			}
		} else if (e.x) {
			curleft += e.x;
			}
		return curleft;
	}
};

/* Product
------------------------------*/
var VariantMatrix = {
	imagePath		: UrlUtils.absoluteWebPath() + '/images/default/en/catalogue/swatch/',
	product			: null, // The product that has the variants
	variants		: null, // The list item that holds the radio button
	variantData		: null, // Json data for the current variant
	variantText		: '##name##, ##size##, in ##colour##',
	specSelection	: null,
	specCode		: null,
	specSize		: null,
	specStock		: null,
	specPrice		: null,
	specSelectionText : 'You have selected: ##name##, ##size## in ##colour##',
	init : function() {
		if (!document.getElementById) { return; }

		// Get matrix and the variant item containers
		this.product		= document.getElementById('variant-matrix');
		this.variants		= this.product.getElementsByTagName('li');

		// Exit if there are no variants
		if (this.variants.length < 1) { return; }

		Debug.p('Product count', this.variants.length);

		// Get spec elements
		this.specSelection	= document.getElementById('selected-product');
		this.specCode		= document.getElementById('spec-code');
		this.specSize		= document.getElementById('spec-size');
		this.specStock		= document.getElementById('spec-stock');
		this.specPrice		= document.getElementById('product-price');

		// Replace the radio buttons
		for (var i = 0, c = this.variants.length; i < c; i++) {
			if (this.variants[i].firstChild.nodeName.toLowerCase() === 'input') {
				this.setItem(this.variants[i]);
			}
		}
	},
	cleanVariantValue : function(value) {
		return "p" + value.replace("-", "");
	},
	setItem : function(variant) {
		Debug.w('Item is a variant');

		var radio = variant.getElementsByTagName('input');

		if (!radio) { return; }

		Debug.w('Label and radio exist', 1);

		radio = radio[0];

		//alert(radio.value + " - " + this.cleanVariantValue(radio.value));

		// Json array of variant data
		this.variantData = eval("ProductData." + this.cleanVariantValue(radio.value));
		
		// Create link for the swatch
		var link		= document.createElement('a');
		link.id			= radio.id + '-form-replacement';
		link.href		= '#';
		link.title		= this.variantText.replace('##name##', this.variantData.name).replace('##size##', this.variantData.size).replace('##colour##', this.variantData.colour);
		this.setVariantFunction(link, radio.value, radio.id);	

		// Create image for the swatch
		var img			= document.createElement('img');
		img.className	= 'form-replacement';
		img.alt			= this.variantText.replace('##name##', this.variantData.name).replace('##size##', this.variantData.size).replace('##colour##', this.variantData.colour);
		img.src			= (radio.checked) ?  this.imagePath + this.variantData.colour + '-o.gif' : this.imagePath + this.variantData.colour + '.gif';
		img.onerror		= function() {
		
		this.src = UrlUtils.absoluteWebPath() + '/images/default/en/catalogue/noimage/swatch.gif';
		
		};

		// Add hidden class and add the swatch to the item
		variant.className = 'form-replacement';
		link.appendChild(img);
		variant.appendChild(link);

		// Set the information for the pre-selected variant
		if (radio.checked) {
			Debug.w('This item is checked', 2);
			this.setInfo();
		}
	},
	setVariant : function(e, variantValue, variantId) {
		Debug.w('Set variant');

		// Clean the selection
		this.clearProduct();

		// Set the radio button
		document.getElementById(variantId).checked = true;

		// Change the image state
		if (e.firstChild.nodeName.toLowerCase() == 'img') {
			var img = e.firstChild;
			img.src = img.src.replace(/.gif/gi, '-o.gif');
		}

		// Set new Json array to correct variant
		this.variantData = eval('ProductData.' + this.cleanVariantValue(variantValue));

		// Refresh the spec
		this.setInfo();

		return false;
	},
	setVariantFunction : function(e, variantValue, variantId) { 
		// Apply lexical variables correctly
		e.onclick = function() {
			return VariantMatrix.setVariant(this, variantValue, variantId);
		};
	},
	setInfo : function() {
		this.specSelection.innerHTML	= this.specSelectionText.replace('##name##', this.variantData.name).replace('##size##', this.variantData.size).replace('##colour##', this.variantData.colour);
	},
	clearProduct : function() {
		// Remove checked radio buttons
		var radio = this.product.getElementsByTagName('input');
		for (var i = 0, c = radio.length; i < c; i++) {
			var item = radio[i];
			if (item.name == this.groupName && item.type == "radio") {
				radio[i].checked = false;
			}
		}

		// Remove selected graphics
		var img = this.product.getElementsByTagName('img');
		for (var i = 0, c = img.length; i < c; i++) {
			var item = img[i];
			if (item.className == 'form-replacement') {
				item.src = item.src.replace(/-o.gif/gi, '.gif');
			}
		}
	}
};

/* General
------------------------------*/
function flickerFix() {
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch(e) {}
}

/* MiniNewsLetterSignUp
------------------------------*/
var MiniNewsLetterSignUp = {
	signup			: null,
	field			: null,
	defaultValue	: 'newsletter signup...',
	submit			: null,
	init : function() {
		if (!document.getElementById) { return true; }
		this.signup = document.getElementById('mini-newslettersignup');
		if (!this.signup) { return; }
		this.field = this.signup.getElementsByTagName('input')[0];
		this.submit = this.signup.getElementsByTagName('input')[1];
		if (this.field) {
			this.field.onkeydown = function(e) {
			if (!e) e = window.event;
			FormUtils.assignButton(e, MiniNewsLetterSignUp.submit.id);
			};
			this.field.value = this.defaultValue;
			this.field.onfocus = function() {
				if (this.value === MiniNewsLetterSignUp.defaultValue) {
					this.value = '';
				}
			};
		}
	}
};

var MiniSearch = {
	search			: null,
	field			: null,
	defaultValue	: 'Search for...',
	submit			: null,
	init : function() {
		if (!document.getElementById) { return true; }
		this.search = document.getElementById('mini-search');
		if (!this.search) { return; }
		this.field = this.search.getElementsByTagName('input')[0];
		this.submit = this.search.getElementsByTagName('input')[1];
/*		if (this.submit) {
			this.submit.onmouseover = function() {
				this.src = this.src.replace('.gif', '-o.gif');
			};
			this.submit.onmouseout = function() {
				this.src = this.src.replace('-o.gif', '.gif');
			};
		}*/
		if (this.field) {
		
			this.field.onkeydown = function(e) {
			if (!e) e = window.event;
				FormUtils.assignButton(e, MiniSearch.submit.id);
			};
			this.field.value = this.defaultValue;
			this.field.onfocus = function() {
				if (this.value === MiniSearch.defaultValue) {
					this.value = '';
				}
			};
			/*this.field.onblur = function() {
				if (this.value === '') {
					this.value = MiniSearch.defaultValue;
				}
			};*/
		}
	}
};

var MiniBasket = {
	basket : null,
	slider : null,
	cookie : null,
	output : null,
	basketURL : null,
	basketLink : null,
	productCount : 0,
	total : 0,
	init : function(update) {
		if (!document.getElementById) { return true; }
		this.basket = document.getElementById("mini-basket");
		
		if (this.basket) {
			if (!update) {
				var basket = document.getElementById("mini-basket");
				this.basketLink = basket.getElementsByTagName("a")[0];
				this.basketURL = this.basketLink.href;
				this.render();
			}
		}
		this.updateView();
	},
	update : function() {
		this.render();
		this.init(true);
		this.updateView();
	},
	render : function() {
		var json = Cookie.get("MiniBasket");
	
		if (!json) { return; }
		var cookie = eval("(" + json + ")");
		this.productCount = 0;
		var products = cookie.products;

		for (var i in products) {
			if (products.propertyIsEnumerable(i)) {
				this.productCount = this.productCount + parseFloat(products[i].itemquantity);
			}
		}
		this.total = cookie.totals.total;	
		this.updateView();
	},
	updateView : function() {
		var t = this.productCount + " item(s) " + this.total;
		if (this.productCount < 1)
		{
			var currency = this.total.substring(0,1) + "0.00";
			t = this.productCount + " item(s) " + currency;		
		}
		
		if (this.basketLink)
			this.basketLink.innerHTML = t;
	}
};

/* Basket
------------------------------*/
var Basket = {
	ajax : new Ajax(),
	submit : null,
	add : function(e, args, qtyId) {
		if (!document.getElementById) { return }
		
		this.clear();
		
		this.submit = document.getElementById("add-to-basket");
		
		if (document.getElementById("variant-matrix")) {
			var vid = FormUtils.getOption('variant-id', 'variant-matrix');	
			this.ajax.set(e, args, "content");
			this.ajax.addParam("vid", vid);
			if (document.getElementById(qtyId)) {
				this.ajax.addParam("qty", document.getElementById(qtyId).value);
			}
			this.ajax.complete = function() {
				var t = document.createTextNode(this.req.responseText);
				if (Config.debug) {
					Debug.w(this.response);
				}
				var json = this.toJson();
				var product = eval("ProductData." + Product.cleanVariantValue(json.products[0].vid)); 
				if(json.products && json.products[0].addToBasket) {
					Basket.submit.src = Basket.submit.src.replace("-o.gif", ".gif");
					Basket.submit.disabled = false;
					if (typeof(Omniture) != "undefined")
						Omniture.basketAdd(args.cid, args.pid, json.products[0].vid, new Boolean(json.products[0].scOpen));
					Basket.message("<p>You have added " + product.name + ", Size " + product.size + " in " + product.colour + " to your <span>Shopping Bag.</span></p>");
				}
				else {
					Basket.message("<p>There is insufficient stock of  " + product.name + ", Size " + product.size + " in " + product.colour + ".</p>");
				}
				MiniBasket.render();
			};
			this.ajax.busy = function() {			
				if (Basket.submit) {
					Basket.submit.src = Basket.submit.src.replace(".gif", "-o.gif");
					Basket.submit.disabled = true;
				}
			};
			this.ajax.get();
		}
		else
		{
			this.ajax.set(e, args, "content");
			if (Voucher.querystring.length > 0) {
				
				this.ajax.addParam("vid", Voucher.querystring);
				this.ajax.complete = function() {
					var t = document.createTextNode(this.req.responseText);
					if (Config.debug) {
						Debug.w(this.response);
					}
					var json = this.toJson();
					var product = json.products;
					var addedMessage = 0;
					var stockMessage = 0;
					
					if(product) {
						Basket.submit.src = Basket.submit.src.replace("-o.gif", ".gif");
						Basket.submit.disabled = false;
						
						for (var i = 0, ix = product.length; i < ix; i++) {
							if (product[i].addToBasket) {
								if (typeof Omniture !== "undefined") {
									Omniture.basketAdd(args.cid, args.pid, json.products[0].vid, (i === 0) ? new Boolean(json.products[0].scOpen) : false);
								}
								addedMessage++;
							} else {
								stockMessage++;
							}
						}
						if (stockMessage === 0) {
							Basket.message("<p>Your have added vouchers to your <span>Shopping Bag.</span></p>");
						} else {
							Basket.message("<p>There is insufficient stock of vouchers, some were not added to your <span>Shopping Bag.</span></p>");
						}
						MiniBasket.render();
					} else {
						Basket.message("<p>There is insufficient stock of vouchers.</p>");
					}
				};
		
				this.ajax.busy = function() {			
					if (Basket.submit) {
						Basket.submit.src = Basket.submit.src.replace(".gif", "-o.gif");
						Basket.submit.disabled = true;
					}
				};
				this.ajax.get();
			} else {
				Basket.message("<p>Please select the number of vouchers you would like to purchase.</p>");
			}
		}
		return false;
	},
	wardrobeBasketAdded: false,
	addToBasketFromWardrobe : function(e, args, vid, i) {
		// Flag that sets the toggle of the layer
		this.wardrobeBasketAdded = false;
		this.ajax.set(e, args, "content");
		this.ajax.addParam("vid", vid);
		this.ajax.addParam("qty", 1);
		this.submit = document.getElementById("add-to-basket-" + vid);
		this.submit.style.display = "inline";

		this.ajax.complete = function() {
			var t = document.createTextNode(this.req.responseText);
			if (Config.debug) {
				Debug.w(this.response);
			}
			var json = this.toJson();

			MiniBasket.render();
			var product = json.products[0]; 
			var message = document.createElement("div");
			message.id = "wardrobe-message-" + i;
			message.className = "message";
			
			if((product.qty != "undefined") && (product.qty != "0"))
			{
				message.innerHTML = "<strong>You have added " + product.name + ", " + product.size + ", in " + product.color + " to your shopping bag</strong>";
			} else {
				message.innerHTML = "<strong>Sorry, this item is currently out of stock.</strong>";
			}
			
			var info = document.getElementById("wardrobe-item-" + i);
			var link = info.getElementsByTagName("a")[0];
			info.insertBefore(message, link);
			
			// Set the flag to NOT hide the inner text of the message
			this.wardrobeBasketAdded = true;
			
			//message.style.visibility = 'visible';
			if (typeof(Omniture) != "undefined") {
				Omniture.basketAdd(args.cid, args.pid, new Boolean(product.scOpen));
			}
			if (Basket.submit) {
				Basket.submit.src = Basket.submit.src.replace("-o.gif", ".gif");
				Basket.submit.style.display = "none";
			}
		}
		this.ajax.busy = function() {			
			if (Basket.submit) {
				Basket.submit.src = Basket.submit.src.replace(".gif", "-o.gif");
				Basket.submit.disabled = true;
			}
		}
		this.ajax.get();
		return false;
	},
	message : function(content) {
		var message = document.getElementById("basket-message");
		if (message) {
			// Update existing message
		} else {
			// Create a new one	
			message = document.createElement("div");
			message.id = "basket-message";
			message.className = "basket-message";
			
			// The element that holds the body of the message
			var messageBody = document.createElement("div");
			messageBody.className = "basket-message-body";

			// The close link
			var messageClear = document.createElement("p");
			messageClear.innerHTML = "<a href=\"#content\" onclick=\"Basket.clear(); return false;\">Close</a>";
			
			// The element that holds the message
			var messageContent = document.createElement("div");
			messageContent.className = "basket-message-content";
			messageContent.innerHTML = content;
			
			// Shadow
			var shadow =  document.createElement("div");
			shadow.className = "basket-message-shadow";
			
			// Add the elements together
			messageBody.appendChild(messageClear);
			messageBody.appendChild(messageContent);
			message.appendChild(messageBody);
			message.appendChild(shadow);
			
			// Add the message to the page
			var product = document.getElementById("content");
			product.appendChild(message);
			
			// Position the message
			if (Config.isPlanet()){
				Position.anchor("basket-message","add-to-basket",{"offsetX": 200, "offsetY": -25, "position": "absolute"});
			}
			else if (Config.isWindsmoor()){
				Position.anchor("basket-message","add-to-basket",{"offsetX": 220, "offsetY": -30, "position": "absolute"});
			}
			else {
				Position.anchor("basket-message","add-to-basket",{"offsetX": 0, "offsetY": 31, "position": "absolute"});
			}
		}
	},
	// Delete the basket
	clear : function() {
		var message = document.getElementById("basket-message");
		if (message) {
			var product = document.getElementById("content");
			product.removeChild(message);
		}
	},
	removeItem : function(item) {
	
	},
	updateItemQuantity : function(item, qty) {
	
	},
	update : function(e) {
		
		var basketQty = FormUtils.collect("basket");
		
		this.ajax.method = "POST";
		this.ajax.set(e, basketQty, "content");
		this.ajax.addParam("ajax", "true");
		this.ajax.addParam("cmd", "update");
		
		this.ajax.complete = function() {
			alert(this.req.responseText);
		}
		
		this.ajax.get();
	}
};

/* Voucher - Update the price for the array of vouchers
--------------------------------------------------*/
var Voucher = {
	values: [],
	quantities: [],
	total: 0,
	price: null,
	currency: "",
	querystring: "",
	init: function() {
		var vid = $('vouchers-product-id');
		Voucher.update(this, vid?vid.value:null);
	},
	update: function(e, pid) {	
		// Reset the total
		this.total = 0;
		this.querystring = "";
		
		// Not sure why right now, but the values get defaulted when this function is called after the init call
		var container	= document.getElementById("gift-choice");
		this.values		= container.getElementsByTagName("input");
		this.quantities	= container.getElementsByTagName("select");
		
		var price		= document.getElementById("voucher-price");
		this.price		= price.getElementsByTagName("span")[0];
		this.currency	= this.price.innerHTML.substring(0, 1);
		
		// Use the checkboxes to find out info about the quantity
		for (var i = 0, ix = this.quantities.length; i < ix; i++) {
			var value	= this.values[i].value.split(":");
			var select	= this.quantities[i];
			
			if (select.value !== "0") {
				this.total += (parseInt(select.value) * parseFloat(value[0]));
				this.querystring += ";" + pid + ":" + select.value + ":" + value[1];
			}
		}
		
		// Store the querystring for use with the basket
		this.querystring = this.querystring.substring(1);
		
		// Create the total - with a proper formatting for the decimal price
		this.price.innerHTML = this.currency + this.total.toFixed(2);
	}
};

/* Wish List
------------------------------*/
var WishList = {
	ajax : new Ajax(),
	submit : null,
	add : function(e, args, qtyId) {
		if (!document.getElementById) { return }
		
		this.clear();
		
		this.submit = document.getElementById("add-to-wishlist");
		
		var vid = FormUtils.getOption('variant-id', 'variant-matrix');	

		this.ajax.set(e, args, "content");
		this.ajax.addParam("vid", vid);
		this.ajax.addParam("qty", document.getElementById(qtyId).value);
		
		this.ajax.complete = function() {
			var t = document.createTextNode(this.req.responseText);
			if (Config.debug) {
				Debug.w(this.response);
			}
			var json = this.toJson();
			if (json != undefined) {
				var product = eval("ProductData." + Product.cleanVariantValue(json.products[0].vid)); 
				if(json.products && json.products[0].addToWishList) {
					WishList.message("<p>You have added " + product.name + ", Size " + product.size + " in " + product.colour + " to your <span>Wardrobe.</span></p>");
				}
			} else {
				this.error();
			}
		}
		this.ajax.error = function() {
			//alert(this.req.responseText);
			self.location.href = this.req.responseText;
		}
			
		this.ajax.get();
		return false;
	},
	message : function(content) {
		var message = document.getElementById("wishlist-message");
		if (message) {
			// Update existing message
		} else {
			// Create a new one	
			message = document.createElement("div");
			message.id = "wishlist-message";
			message.className = "wishlist-message";
			
			// The element that holds the body of the message
			var messageBody = document.createElement("div");
			messageBody.className = "wishlist-message-body";

			// The close link
			var messageClear = document.createElement("p");
			messageClear.innerHTML = "<a href=\"#content\" onclick=\"WishList.clear(); return false;\">Close</a>";
			
			// The element that holds the message
			var messageContent = document.createElement("div");
			messageContent.className = "wishlist-message-content";
			messageContent.innerHTML = content;
			
			// Shadow
			var shadow =  document.createElement("div");
			shadow.className = "wishlist-message-shadow";
			
			// Add the elements together
			messageBody.appendChild(messageClear);
			messageBody.appendChild(messageContent);
			message.appendChild(messageBody);
			
			message.appendChild(shadow);
		
			// Add the message to the page
			var product = document.getElementById("content");
			product.appendChild(message);
			
			// Position the message
			if (Config.isPlanet()){
				Position.anchor("wishlist-message","link-to-my-wardrobe",{"offsetX": 7, "offsetY": 15, "position": "absolute"});
			}
			else {
				Position.anchor("wishlist-message","link-to-my-wardrobe",{"offsetX": 0, "offsetY": 21, "position": "absolute"});
			}
			
		}
	},
	// Delete the basket
	clear : function() {
		var message = document.getElementById("wishlist-message");
		if (message) {
			var product = document.getElementById("content");
			product.removeChild(message);
		}
	}
};
/* Address
------------------------------*/
var Address = {
	ajaxOutput : "dynamic-address",
	submit : null,
	init : function() {
		return;
		// Hide submit button
		var wrap = document.getElementById("profile-set-address");
		if (wrap) {
			var buttons = wrap.getElementsByTagName("input");
			for (var i = 0, c = buttons.length, n = 0; i < c; i++) {
				if (buttons[i].getAttribute("type") == "image") {
					n++;
					if (n == 2) {
						this.submit = buttons[i];
						this.submit.style.display = "none";
						break;
					}
				}
			}
		}
		
	},
	getAddress : function(e, url, houseNumber, postcode, countryDropDown, action, source) {
		var dd = document.getElementById(countryDropDown);
		if (dd) {
			var countryCode = dd.options[dd.selectedIndex].value;
			var country = document.getElementById("country-code");
			if (country) {
				country.setAttribute("value", countryCode);
			}
			else {
				var countryField = document.createElement("input");
				countryField.setAttribute("type", "hidden");
				countryField.setAttribute("id", "country-code");
				countryField.setAttribute("value", countryCode);
				document.body.appendChild(countryField);
			}
		}
		
		var postcodeValue = document.getElementById(postcode).value;
		var houseNumberValue = document.getElementById(houseNumber).value;
		
		var ajax = new Ajax(url, {"ajax": "true", "action": action, "source": source}, this.ajaxOutput);
		ajax.method = "POST";
		
		ajax.complete = function() { 
			this.output.innerHTML = unescape(this.response);
			AjaxUtils.freeze();
		};
		ajax.busy = function() {
			AjaxUtils.busy.button(e);
			AjaxUtils.unfreeze();
		};

		ajax.addParam(postcode + "=" + postcodeValue);
		ajax.addParam(houseNumber + "=" + houseNumberValue);

		ajax.get();
		return false;
	},
	selectAddress : function(url, selectAddressListBox, countryDropDown, action, source) {
		var ajax = new Ajax(url, {"ajax": "true", "action": action, "source": source}, this.ajaxOutput);
		ajax.method = "POST";
		
		ajax.complete = function() {
			this.output.innerHTML = unescape(this.req.responseText);
		};
		
		var country = document.getElementById("country-code")
		if (country) {
			ajax.addParam(countryDropDown + "=" + country.value);
		}
		
		var lb = document.getElementById(selectAddressListBox);
		var lbIdx = lb.selectedIndex;
		var selectAddressValue = lb.options[lbIdx].value;
		ajax.addParam(selectAddressListBox + '=' + selectAddressValue);
		
		ajax.get();
		return false;
	},
	selectAddressByTable : function(url, address, countryDropDown, action, source) {
		
		var ajax = new Ajax(url, {"ajax": "true", "action": action, "source": source}, this.ajaxOutput);
		ajax.method = "POST";
		
		ajax.complete = function() { 
			this.output.innerHTML = unescape(this.req.responseText);
			//Address.submit.style.display = "inline";
		};
		
		var country = document.getElementById("country-code")
		if (country) {
			ajax.addParam(countryDropDown + "=" + country.value);
		}

		ajax.addParam("Address=" + encodeURIComponent( address ) );
		ajax.get();
		return false;
	},
	selectCountry : function(url, countryDropDown, action, source) {
		
		var dd = document.getElementById(countryDropDown);
		var countryCode = dd.options[dd.selectedIndex].value;
		
		var ajax = new Ajax(url, {"ajax": "true", "action": action, "source": source}, this.ajaxOutput);
		ajax.method = "POST";
		
		ajax.complete = function() {
			this.output.innerHTML = unescape(this.response);
			//Address.ajaxOutput.innerHTML = unescape(this.response);
		};
		
		var inputs = document.getElementsByTagName("input");
		
		for (var i=0; i<inputs.length; i++) {
			var inputType = inputs[i].getAttribute('type');
			var inputId	= inputs[i].getAttribute('id');
			var inputValue = inputs[i].value;
			if (inputType != 'hidden'
					&& inputId != null && inputId.length > 0
					&& inputValue != null && inputValue.length > 0) {
				ajax.addParam(inputId + '=' + inputValue);
			}
		}
		
		var dropDowns = document.getElementsByTagName('select');
		
		for (var i=0; i<dropDowns.length; i++) {
			var dropDownId = dropDowns[i].getAttribute('id');
			if (dropDownId != countryDropDown) {
				var ddIdx = dropDowns[i].selectedIndex;
				var ddValue = dropDowns[i].options[ddIdx].value;
				var ddText = dropDowns[i].options[ddIdx].text;
				ajax.addParam(dropDownId + '=' + ddIdx + "|" + ddValue + "|" + ddText);
			}
		}

		ajax.addParam(countryDropDown + "=" + countryCode);

		ajax.get();
		return false;
	},
	manualEdit : function(url, countryDropDown, action, source) {
		
		var ajax = new Ajax(url, {"ajax": "true", "action": action, "source": source}, this.ajaxOutput);
		ajax.method = "POST";
		
		ajax.complete = function() {
			this.output.innerHTML = unescape(this.response);
		};

		var dd = document.getElementById(countryDropDown);
		if (dd != null)	{
			var ddIdx = dd.selectedIndex;
			var countryCode = dd.options[ddIdx].value;
			manualEdit.addParam(countryDropDown + '=' + countryCode);
		}

		ajax.get();
		return false;
	}
};



var ProductList = {
	init : function() {
		
		if (!document.getElementById) { return; }

		this.paging();

		list = document.getElementById('product-list');

		if (!list) { return; }

		var product = list.getElementsByTagName('li');

		for (var i = 0, c = product.length; i < c; i++) {

			var p = product[i].getElementsByTagName('p');

			for (var j = 0, d = p.length; j < d; j++) {
				if (p[j].className == 'more-info') {
					p[j].id = 'more-info-' + i;
				}
			}

			/*this.showFunction(product[i], i);
			this.hideFunction(product[i], i);*/
		}		
	},
	showFunction : function(e, i) {
		e.onmouseover = function() {
			ProductList.show(this, i);
		};
	},
	hideFunction : function(e, i) {
		e.onmouseout = function() {
			ProductList.hide(this, i);
		};
	},
	show : function(e, i) {
		document.getElementById('more-info-' + i).style.visibility = 'visible';
	},
	hide : function(e, i) {
		document.getElementById('more-info-' + i).style.visibility = 'hidden';
	},
	paging : function() {
		if (!document.getElementById('paging')) { return; }
		var content = document.getElementById('content');
		if (content) {
			content.className = 'paging-child';
		}
	}
}

/* Subnav 
------------------------------*/
var Navigation = {
	childNav : [],
	init : function() {
		if (!document.getElementById || !document.getElementsByTagName) { return; }
		var subNav = document.getElementById("static-nav");
		if (subNav) {
			var subNavItem = subNav.getElementsByTagName("li");
			for (var i = 0, childNav, childNavItems; i < subNavItem.length; i++) {
				// See if there is a sub nav
				childNav = subNavItem[i].getElementsByTagName("ul");
				if (childNav.length > 0) {
					// Hide the child nav if not selected class
					if (subNavItem[i].className != "selected") {
						childNav[0].style.display = "none";
					}
					// Add the nav to an array to loop through easily
					this.childNav.push(childNav[0]);
					// If the first child is a link, add the onclick
					if (subNavItem[i].firstChild) {
						this.toggleFunction(subNavItem[i].firstChild, childNav[0]);
					}
					// Count child items
					childNavItems = childNav[0].getElementsByTagName("li");
					// Increment to skip child items
					i += childNavItems.length;
				}	
			}
		}
	},
	// Collapse all the open children
	collapse : function() {
		for (var i = 0, c = this.childNav.length; i < c; i++) {
			this.childNav[i].style.display = "none";
		}
	},
	// JS Lexical 
	toggleFunction : function(e, el) {
		e.onclick = function() {
			return Navigation.toggle(this, el);
		}
	},
	// Toggle between in/visible
	toggle : function(e, el) {
		if (el.style.display == "none") {
			Navigation.collapse();
			el.style.display = "block";
		} else {
			Navigation.collapse();
			el.style.display = "none";
		}
		return false;
	}
};


// Flash Movie Control

function thisMovie(movieName) {
  // IE and Netscape refer to the movie object differently.
  // This function returns the appropriate syntax depending on the browser.
  if (window[movieName]) {
    return window[movieName];
  }	else {
    return document[movieName];
  }
}

// Checks if movie is completely loaded.
// Returns true if yes, false if no.
function movieIsLoaded (theMovie) {
  if (typeof(theMovie) != "undefined") {
    return theMovie.PercentLoaded() == 100;
  } else {
    return false;
  }
}

function playmovie(movieName) {
  if (movieIsLoaded(thisMovie(movieName))) {
    thisMovie(movieName).Play();
  }
}

function stopmovie(movieName) {
  if (movieIsLoaded(thisMovie(movieName))) {
    thisMovie(movieName).StopPlay();
  }
}
// End Flash Movie Control


/*
 * Function to automatically fire a form post for the form named 'documentForm'.
 * This is used in the 3DSecure processing to start the client interaction
 * direct with the bank.  The html contents of the banks pages are displayed
 * in an iframe named 'threedauthframe'.
 */
function OnLoadEvent()
{
	if (document.documentForm != null)
	{
		//alert('found doc form');
		document.documentForm.target='threedauthframe';
		document.documentForm.submit();
		document.documentForm.style.visibility='hidden';
	}
}

// Multiple onload function created by: Simon Willison
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

/* Wardrobe / Show-Hide 
------------------------------*/
var Wardrobe = {
	show: function(e) {
		this.toggle(e, true);
	},
	hide: function(e) {
		this.toggle(e, false);
	},
	// Toggle visible states
	toggle: function(e, show) {
		var info = document.getElementById("wardrobe-item-" + e);
		info.style.display = (show) ? "block" : "none";
		
		var infoShadow = document.getElementById("wardrobe-item-shadow-" + e);
		infoShadow.style.display = (show) ? "block" : "none";
		
		var infoMessage = document.getElementById("wardrobe-message-" + e);
		if (!show && Basket.wardrobeBasketAdded) {
			if (infoMessage) {
				infoMessage.parentNode.removeChild(infoMessage);
			}
		} else if (Basket.wardrobeBasketAdded) {
			if (infoMessage) {
				infoMessage.parentNode.removeChild(infoMessage);
			}
		}
	}
};
