/*--------------------------------------------------
BASE-1.0.3 contains UKISA, CONFIG, UTIL, MODAL, BASE, ORDER
Generated: 24/8/2010
--------------------------------------------------*/
/** 
 * @fileOverview Site configuration and localisation
 * @author Oliver Bishop / Tom McCourt
 * @version 1.12.0
 * @changeLog Added a method to create namespaces.
 */

/* This sets the global namespaces */
var UKISA = {locale: {}, widget: {}, util: {}, site: {}};

// Shorthand the YUI Selector method - ala jQuery.
var $ = $ || YAHOO.util.Selector.query;

/**
 * Code required to work with the configuration file. Contains a getter method for l10n, site code initialisation.
 */
(function() {
	/**
	 * This retrieves the localised value as specified by the key.
	 *
	 * @name get
	 * @memberOf UKISA.locale
	 * @param {String} key The variable that holds the localised data.
	 * @returns {?} Returns whatever is held against the key e.g. function, string, integer
	 */
	UKISA.locale.get = function(key) {
		var i, value;

		key = key.split(".");
		value = UKISA.locale[UKISA.env.SITE][key[0]];

		if (value) {
			for (i = 1, ix = key.length; i < ix; i++) {
				value = value[key[i]];
			}
			
			if (typeof value[UKISA.env.REGION] !== "undefined") {
				value = value[UKISA.env.REGION];
			}	
		}	

		return (value !== "undefined") ? value : null;
	};

	/**
	 * Create a namespace for the UKISA library.
	 *
	 * @example UKISA.namespace("UKISA.widget");
	 * @example UKISA.namespace("widget");
	 * @example UKISA.namespace("UKISA.widget", "UKISA.site");
	 * @example UKISA.namespace("UKISA.widget.Rollover");
	 */
	UKISA.namespace = function() {
		var a, o, i, j, d;

		a = arguments; 
		o = null;

		for (i = 0, ix = a.length;  i < ix; i++) {
			d = ("" + a[i]).split(".");
			o = UKISA;

			for (j = (d[0] == "UKISA") ? 1 : 0, jx = d.length; j < jx; j++) {
				o[d[j]] = o[d[j]] || {};
				o = o[d[j]];
			}
		}

		return o;
	};
	
	/**
	 * Manage Sitestat statistics.
	 */
	UKISA.Sitestat = {
		/**
		 * Make a call to the Sitestat server to register a page view.
		 */
		hit: function(qs) {
			var url, ns_0, ns_pixelUrl;

			// This checks that the site is "live" as is must have the sitestat function.
			// This stops polluting the stats with UAT data.

			if (typeof sitestat === "function") {
				
				if (typeof UKISA.env.SITESTAT !== "undefined") {
					url = "http://int.sitestat.com/ici-paints/" + UKISA.env.SITESTAT + "/s?" + qs;

					url += "&amp;ns__t=" + (new Date()).getTime();
					ns_pixelUrl = url;
					ns_0 = document.referrer;
					ns_0 = (ns_0.lastIndexOf("/") == ns_0.length - 1) ? ns_0.substring(ns_0.lastIndexOf("/"), 0) : ns_0;

					if(ns_0.length > 0) {
						url += "&amp;ns_referrer=" + escape(ns_0);
					}
					if(document.images){
						ns_1 = new Image();
						ns_1.src = url;
					} else {
						document.write('<img src="' + url + '" width="1" height="1" alt="" class="tracking" />');
					}
				} else {
					alert("Sitestat version or site name not known.");
				}
			}
		}
	};

	/**
	 * This is a periodic timer to test for the loading of the config file. Once it has been loaded, the timer is cancelled.
	 * This keeps the config file clean and will only be needed for uat as on production all the script is minified as one.
	 */
	UKISA.bootstrap = function() {
		// Assign the global code init as set in the config to YUI
		YAHOO.util.Event.onDOMReady(UKISA.env.onDOMReady);

		// Assign the global code init as set in the config to YUI
		YAHOO.util.Event.addListener(window, "load", UKISA.env.onLoad);

		// Create the site namespace
		UKISA[UKISA.env.SITE] = {};

	};

	// Look for the UKISA.env object which will be in scripts/config.js so this test to see if the page is loaded for example on UAT.
	// If it is available immediately then this script will be on production and all concatenated into one file.
	if (typeof UKISA.env !== "undefined") {
		UKISA.bootstrap();
	} else {
		// If the env object is not found then create a poll method to test for it until it is loaded.
		UKISA.loader = YAHOO.lang.later(
			10, 
			this, 
			function() {
				if (typeof UKISA.env !== "undefined") {
					UKISA.bootstrap();
					UKISA.loader.cancel();
				}
			},
			null,
			true
		);
	}

	/**
	 * A global message display for errors to the user or to us.
	 */
	 UKISA.notify = function(t) {
		alert("Message:" + t);
	 };

	/**
	 * Apply a new window.console incase Firebug is not loaded or IE is being used.
	 */
	if (!window.console) {
		window.console = {
			log: function(t) {
				var stack, item;

				stack = document.getElementById("window-console");
				
				if (!stack) {
					stack = document.createElement("ul");
					stack.id = "window-console";
					stack.setAttribute("style", "clear: both; font-weight: bold; font-size: 11px; border: dashed 1px red; border-bottom: none; list-style: none; width: 50%;");
					document.body.appendChild(stack);
				}

				item = document.createElement("li");
				item.setAttribute("style", "border-bottom: 1px dashed red; padding: 2px 5px;");
				item.innerHTML = t;
				stack.appendChild(item);
			},
			info: function() {}
		};
	}

})();/** 
 * @fileOverview Site configuration and localisation.
 * @author Oliver Bishop / Tom McCourt
 * @version 1.0.2
 * @changeLog Created.
 */

/** 
 * Main configuration values 
 */
UKISA.env = {
	/**
	 * What region is this site based: EUK, IRE, EZA.
	 */
	REGION: "EUK",

	/**
	 * What is the site shortcode: CUP, DLX, HAM.
	 */
	CODE: "CUP",

	/**
	 * What is the name of the site: Cuprinol, Dulux, Polycell.
	 */
	SITE: "Cuprinol",
	
	/**
	 * What is the Sitestat site code? This is used for Ajax calls to Sitestat.
	 */
	SITESTAT: "cup-uk",

	/**
	 * Globally available onDOMReady function.
	 */
	onDOMReady: function() { // Run when the DOM has loaded

		/**
		 * Global fix to keep the footer to the bottom of the page.
		 */
		(function() {
			var Dom, Event, documentHeight, viewportHeight, footerHeight, headerHeight, adjustment, minHeight, ie;
	
			Dom = YAHOO.util.Dom;
			Event = YAHOO.util.Event;
			
			ie = YAHOO.env.ua.ie;

			// Set header and footer height.
			minHeight = 0;
			headerHeight = 193;
			footerHeight = 263;
			adjustment = 12; // Some space somewhere I can't find.

			resize = function() {
				// Get the viewport height.
				documentHeight = Dom.getDocumentHeight();
				viewportHeight = YAHOO.util.Dom.getViewportHeight();

				minHeight = viewportHeight - headerHeight - footerHeight - adjustment;

				if (minHeight > 0) {
					Dom.setStyle("body", "min-height", minHeight + "px");
			
					// Dirty.
					if (ie >= 6 && ie < 7) {
						Dom.setStyle("body", "height", minHeight + "px");
					}
				}
			};

			Event.addListener(window, "resize", resize);

			resize();
		})();

		/** 
		 * This adds on the header and footer divs to the section divs.
		 */
		(function() {
			var sections, i, header, content, footer, Dom, section, span;

			Dom = YAHOO.util.Dom;

			sections = YAHOO.util.Selector.query(".section .body", "body");

			span = document.createElement("span");

			header = document.createElement("div");
			header.className = "header";

			headerLeft = span.cloneNode(false);
			headerLeft.className = "cl";

			headerRight = span.cloneNode(false);
			headerRight.className = "cr";

			header.appendChild(headerLeft);
			header.appendChild(headerRight);

			footer = header.cloneNode(true);
			footer.className = "footer";

			i = sections.length;

			for (; i--;) {
				content = sections[i];
				
				section = Dom.getAncestorByClassName(content, "section");

				section.insertBefore(header.cloneNode(true), content);

				section.appendChild(footer.cloneNode(true));
			}
		})();

		(function() {
			return;
			YAHOO.lang.later(250, this, function() {
				var Dom, html, pos;

				Dom = YAHOO.util.Dom;

				html = document.getElementsByTagName("html")[0]

				pos = parseFloat(Dom.getStyle(html, "backgroundPosition").split(" ")[0]);
				
				pos = pos - .75;

				Dom.setStyle(html, "backgroundPosition", pos + "px 0"); 
			
			}, null, true);
		})();

		if (typeof UKISA.site.Order !== "undefined") {
			UKISA.site.Order.Basket.init();
		}

		// Add the clear default to the mini search.
		UKISA.util.clearDefault("mini-search-field");

		// Quick PNG fix.
		if (document.body.id === "ideas-page") {
			UKISA.util.PNGFix("img.get_ready");
		}

		if (document.body.id === "colour-page") {
			UKISA.util.PNGFix("img.shades-logo");
		}

		if (document.body.id === "shed-love") {
			UKISA.util.PNGFix("img.shed-love-polaroids");
		}

		if (YAHOO.util.Dom.hasClass(document.body, "ideas-page")) {
			UKISA.util.PNGFix("img.get_ready");
		}
		
		if (YAHOO.util.Dom.hasClass(document.body, "tester-page")) {
			UKISA.util.PNGFix("img.shades-logo");
		}

		if (YAHOO.util.Dom.hasClass(document.body, "wps-page")) {
			UKISA.util.PNGFix("img.society-logo");
		}
		UKISA.util.PNGFix(".article-image img");
		UKISA.util.PNGFix(".lozenge img");

		// Cufon font replacement goes here and makes use of YUI Selector to gather the elements to style.
		if (Cufon && $) {
			var replace = [
				"h1",
				"h2",
				"h3"
			];

			Cufon.replace($(replace.join(", ")));
		}
	},
	
	/**
	 * Globally available onLoad function.
	 */
	onLoad: function() { // Run when the content has loaded
		var i, el;

		// Find all the print buttons.
		el = $("a.print", "content");
		i = el.length;
		for (; i--;) { el[i].onclick = function() { UKISA.util.print(); return false; }; }

		// This adds a modal box for links e.g. terms & conditions.
		el = $("a.modal", "content");
		i = el.length;
		for (; i--;) { el[i].onclick = function() { UKISA.site.Navigation.terms(this); return false; }; }
	}
};

/**
 * Create the localisation namespace. Widgets may use settings specified here.
 */
UKISA.locale[UKISA.env.SITE] = {
	// L10n values here (strings, functions, etc.)
	widget: {
		FormValidation: {
			display: {
				xOffset: -15,
				yOffset: 0
			}
		},
		Flash: {
			supports: "8.0.0", // Default supported version.	
			width: 512,	// Default width.
			height: 288, // Default width.
			flashDir: "/web/flash/",
			movieDir: "/web/movies/",
			params: { // Default params.
				"quality": "high",
				"scale": "noscale",
				"pluginspage": "http://www.macromedia.com/go/getflashplayer",
				"wmode": "transparent"
			},
			vars: { // Default variables.
				"MM_ComponentVersion": "1",
				"skinName": "/web/flash/ukisa/flash/Halo_Skin_3",
				"autoPlay": "false",
				"autoRewind": true
			},
			skins: {
				"Halo_Skin_3": {
					top: 11,
					right: 11,
					bottom: 40,
					left: 11
				}
			},
			attributes: {},
			callback: null
		},
		Colour: {
			ToolBox: {
				
			}
		}
	},
	site: {
		Order: {
			Basket: {
				automaticAddToBasket: true
			}
		},
		Favourites: {
			automaticAddToFavourites: true
		}
	}
};
/** 
 * @fileOverview Helper methods to refactor code and make life easier.
 * @author Tom McCourt / Oliver Bishop
 * @version 1.0.14
 * @changeLog Renamed file to lowercase and used namespace.
 */

UKISA.namespace("util");

/**
 * @namespace Helper methods.
 * @memberOf UKISA.utils
 */
UKISA.util = {
	/**
	 * Cufon font replacement goes here and makes use of YUI Selector to gather the elements to style.
	 *
	 * @example UKISA.util.FR(); to re-apply the existing FR selectors defined in the config.js file.
	 * @example UKISA.util.FR("#new-element.odd h3"); to apply FR to a specific selectior.
	 * 
	 * @param {string} q		New font replacement query.
	 */
	FR: function(q) {
		if (Cufon && $) {
			if (q) {
				Cufon.replace($(q));
			} else {
				if (UKISA.env.FR.length) {
					Cufon.replace($(UKISA.env.FR.join(", ")));
				}
			}
		}
	},
	URL: {
		/**
		* Redirect or delayed redirect
		* 
		* @param {string} url		Url to redirect to
		* @param {int} [t]			Time in seconds
		*/
		redirect: function(url, t) {
			if (t) {
				self.setTimeout("self.location.href = '" + url + "';", t * 1000);
			} else {
				self.location.href = url;
			}
		},	
		/**
		* Remove a value in a URL
		* 
		* @param {string} p			Property you want change value of
		* @param {string} v			New value you want to replace with
		* @param {string} [url]		URL to search, defaults to current page
		*/
		removeParameter: function(p, url) {
			url			= url || "";
			var pos		= url.indexOf("?");
			var href	= (pos != -1) ? url.substring(0, pos + 1) : "";	
			var query	=  url.substring(pos + 1);
			var params	= query.split("&");
			query = "";

			// Create new list built on the values we DO want
			for (var i = 0, c = params.length; i < c; i++) {
				var param = params[i];
				if (param.substring(0, param.indexOf("=")) !== p) {
					query += "&" + param;
				}
			}

			// Assign new value and trim the first & character
			query = query.substring(1);
			return href + query;
		},
		/**
		* Replace a value in a URL
		* 
		* @example UKISA.util.URL.replaceParam("successURL", "/ajax/order/quantity_update.jsp", YAHOO.util.Connect);
		* 
		* @param {string} p			Property you want change value of
		* @param {string} v			New value you want to replace with
		* @param {string|object} [url]		URL to search, defaults to current page
		*/
		replaceParameter: function(p, v, source) {
			var url = source;

			if (typeof source === "object") {
				// Cheeky grab of the private property.
				url = source._sFormData;
			}

			url = url.replace(new RegExp(p + "=.*?(&|$)", "i"), p + "=" + v + "$1");

			// Now set the property with the changed value.
			if (typeof source === "object") {
				// Cheeky grab of the private property.
				source._sFormData = url;
			}

			return url;
		},
		/**
		* Add a parameter to a URL
		* 
		* @param {string} p			Property you want change value of
		* @param {string} v			new value you want to replace with
		* @param {string} [url]		URL to use instead of the current page URL
		* @return {string}			The updated URL
		*/
		addParameter: function(p, v, source) {
			var parts, url = source;

			if (typeof source === "object") {
				// Cheeky grab of the private property.
				url = source._sFormData;
			}

			parts = url.split("&");

			parts[parts.length] = p + "=" + v;
			
			url = parts.join("&");

			// Now set the property with the changed value.
			if (typeof source === "object") {
				// Cheeky grab of the private property.
				source._sFormData = url;
			}

			return url;
		}
	},
	/**
	 * Proxy for a PNG fix script. In this case BelatedPNGFix is used.
	 *
	 * @param {String} t Comma seperated list of element IDs to use to apply the PNG fix to.
	 * @param {String} url By default the URL to the png script is the new site standard /web/scripts/png_fix.js. If this is not the case, specify an alternative.
	 * @requires YAHOO.util.Get
	 */
	PNGFix: function(t, url) {
		var get, getURL;

		if (YAHOO && YAHOO.env.ua.ie === 6) {
			getURL = url || "/web/scripts/png_fix.js";

			get = YAHOO.util.Get.script(getURL, { 
				onSuccess: function() { 
					if (typeof DD_belatedPNG !== "undefined") {
						UKISA.util.PNGFix = DD_belatedPNG;
						UKISA.util.PNGFix.fix(t);
					} else {
						alert("Missing PNG handler: " + getURL);
					}
				}
			});
		}
	},
	/** 
	 * Opens a system print dialogue box.
	 *
	 * @param {String} [w] Id of the IFRAME or window to print.
	 * @returns {Boolean} Returns false;
	 */
	print: function(w) {
		var doc;
		if (w) {
			if (document[w]) {
				document[w].focus(); 
				document[w].print(); 
			} else {
				if (window.frames[w]) {
					window.frames[w].focus(); 
					window.frames[w].print(); 
				}
			}
		} else {
			if (window.print) {
				window.print();
			}
		}
		return false;
	},
	/**
	 * Apply a class of "nth-child" to a frequency of a collection of items.
	 *
	 * @memberOf UKISA.utils
	 * @param {Object} list Collection of enumerable objects.
	 * @param {Integer} freq The nth item in the list to apply the class to.
	 * @param {String} [className] Optional class name to apply (default is "nth-child").
	 */
	nthChild: function(list, freq, className) {
		var i, ix, classToName;

		classToName = className || "nth-child";
		for (i = 0, ix = list.length; i < ix; i++) {
			if ((i + 1) % freq == 0) {
				YAHOO.util.Dom.addClass(list[i], classToName); 
			} else {
				YAHOO.util.Dom.removeClass(list[i], classToName); 
			}
		}
	},
	/**
	 * Clear the default text on a textbox when focus is gained.
	 *
	 * @memberOf UKISA.utils
	 * @param {String} Unlimited list of arguments for inputs to apply this to.
	 */
	clearDefault: function () {
		var action = function(el) {
			if (!el) { return; }

			var defaultValue = el.value;

			el.onfocus = function() {
				var old = defaultValue;
				if (this.value === defaultValue) {
					this.value = "";
				}
			};

			el.onblur = function() {
				var old = defaultValue;
				if (this.value === "" || this.value === defaultValue) {
					this.value = old;
				}
			};
		};

		for (var i = 0, ix = arguments.length; i < ix; i++) {
			action(document.getElementById(arguments[i]));
		}
	},
	/**
	 * Gets the real parent node of an element, skipping inapporpriate node types e.g. whitespace as used in IE.
	 *
	 * @memberOf UKISA.utils
	 * @param {String|HTMLObject} el Element to find the parent node of.
	 * @returns {HTMLObject} The real parent node of the element.
	 */
	parentNode: function(el) {
		var e = (typeof el == "string") ? document.getElementById(el) : el;
		var node = null;
		if (e && e.parentNode) {
			while (e.parentNode.nodeType != 1) {
				e = e.parentNode;
				node = e;
			}
			return (!node) ? e.parentNode : node;
		}
	},
	/**
	 * Remove white space before or after a string
	 *
	 * @memberOf UKISA.utils
	 * @param {String} s String to trim white space from
	 * @return {String}	 Returns a clean string with white space removed
	 */
	trim: function(s) {
		return s.replace(/^\s+|\s+$/g, "");
	},

	/**
	 * Get the scroll position of the document.
	 *
	 * @memberOf UKISA.utils
	 * @deprecated Use the YAHOO.util.Dom.getDocumentScrollLeft(), YAHOO.util.Dom.getDocumentScrollTop() instead.
	 * @return {Array}	 Array [0] is the left scroll in pixels, [1] is the top scroll in pixels.
	 */
	getScrollXY: function() { // Get scroll position of page
		var scrOfX = 0, scrOfY = 0;
		if(typeof(window.pageYOffset) === "number") {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		return [scrOfX, scrOfY];
	}
};/**
 * @namespace This contains generic methods to create a uniform style for modals.
 * @author Tom McCourt / Oliver Bishop
 * @version 0.0.2
 * @changeLog Add an ajax load page function.
 * @changeLog Added a check to make sure only same id containers are visible toggled. New id modals are created from scratch.
 * @changeLog Created.
 */

UKISA.namespace("UKISA.widget.Modal");

/**
 * Global dialog templates that use YUI Container widgets to allow a consistent look of the site.
 */
UKISA.widget.Container = null;

/**
 * Create a modal instance.
 *
 * @returns YAHOO.widget.Panel Returns a YAHOO.widget.Panel instance.
 * @example 
 * var modal = new UKISA.widget.Modal("my-id", "Some content");
 * modal.show();
 */
UKISA.widget.Modal = function(id, content, options) {
	var panel, hd, bd, ft, container, loader, body, ajax, container;

	panel = document.getElementById(id);

	container = UKISA.widget.Container;

	// This is a default content placeholder - simply has a "loading" message.
	loader = function() {
		var a = document.createElement("p");
		a.id = id + "-loading";
		a.className = "loading";
		a.innerHTML = "Please wait...";

		return a;
	};

	body = content || loader();

	if (panel && container && (id === container.id)) {
		container.setBody(body);

		return container;
	} else {
		// If the id's do not match then we may be dealing with a different style, so reset it.
		if (container && id !== container.id) {
			container.hide();
			container.destroy();
		}

		// This creates the custom shadow around the Panel box.
		panel = document.createElement("div");

		hd = panel.cloneNode(false);
		bd = panel.cloneNode(false);
		ft = panel.cloneNode(false);

		panel.id = id;
		panel.className = "yui-panel-container yui-dialog shadow";
		hd.className = "hd";
		bd.className = "bd";
		ft.className = "ft";

		panel.appendChild(hd);
		panel.appendChild(bd);
		panel.appendChild(ft);

		document.body.appendChild(panel);

		UKISA.widget.Container = new YAHOO.widget.Panel(id, { 
			fixedcenter: true,
			modal: true,
			visible : false,	
			close: true,
			underlay: "shadow",
			constraintoviewport: true,
			zIndex: 500,
			autofillheight: "body"
		});
		
		container = UKISA.widget.Container;

		container.setBody(body);

		container.render(document.body);

		// Add some extra functionality.
		container.load = function(type, url, callback, qs) {
			callback = callback || {
				success: function(o) {
					container.setBody(o.responseText);
				}, 
				failure: function(o) {
					container.setBody([
						'<p class="error">',
							'Sorry, there was a problem when trying to fetch something. Please close this down and try again.',
						'</p>'
					].join(""));
				}, 
				timeout: 5000
			};

			this.ajax = YAHOO.util.Connect.asyncRequest(type, url, callback, qs);
		};

		return container;
	}
};/** 
 * @fileOverview Main site code that should follow the namespace UKISA.site.*
 * @version 1.0.3
 * @changeLog Created.
 */

UKISA.namespace("site");

/**
 * Create a message to appear at the top of the page. Typically used for Ajax response.
 */ 
UKISA.site.Message = function(text, type) {
	var canvas, message, anim;

	if (text === "") {
		UKISA.site.Message.destroy();
	} else {

		type = type || "error";
		
		canvas = $("h1", "body", true);

		if (canvas) {

			message = document.getElementById("global-message-" + type);

			if (!message) {
				message = document.getElementById("global-message");
			}

			if (!message) {
				message = document.createElement("p");
				message.id = "global-message";
				YAHOO.util.Dom.insertAfter(message, canvas);
			}
			message.className = type;
			message.innerHTML = text;
		}

		//window.scrollTo(0, 0);
	}
};

UKISA.site.Message.destroy = function(destroyAllMessages) {
	var message, i, ix;
	
	message = document.getElementById("global-message");

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

	if (destroyAllMessages) {
		message = $(".success, .error", "body");

		for (i = 0, ix = message.length; i < ix; i++) {
			message[i].parentNode.removeChild(message[i]);
		}
	}
};

UKISA.site.SocialApps = function() {

	var bookmarker = new UKISA.widget.Bookmarker();
	this.init();
};

UKISA.site.SocialApps.sendEmail = function(e) {
	var instance = this;
	var canvas = UKISA.site.SocialApps.parentNode(e);		
	
	// Change the button
	var submit = YAHOO.util.Dom.getElementsByClassName("submit", "input", e);
	if (submit.length) {
		submit[0].src = submit[0].src.replace(".gif", "_loader.gif");
	}

	var callback = {
		success: function(o) {
			canvas.innerHTML = o.responseText;
			UKISA.site.SocialApps.buttonDialog.update();
		},
		failure: function(o) {
			canvas.innerHTML = "<p class=\"error\">Sorry, there is a problem with www.dulux.co.uk. We apologise for any inconvenience caused. Please try again.</p>";
			UKISA.site.SocialApps.buttonDialog.update();
		},
		timeout: 8000
	};	
	
	YAHOO.util.Connect.setForm(e);	
	var transaction = YAHOO.util.Connect.asyncRequest("POST", e.getAttribute("action"), callback);

	return false;
};

UKISA.site.SocialApps.parentNode = function(el) {
	var e = (typeof el == "string") ? document.getElementById(el) : el;
	var node = null;
	if (e && e.parentNode) {
		while (e.parentNode.nodeType != 1) {
			e = e.parentNode;
			node = e;
		}
		return (!node) ? e.parentNode : node;
	}
};

UKISA.site.SocialApps.buttonDialog = null;

UKISA.site.SocialApps.prototype = {
	
	init: function() {
		UKISA.site.SocialApps.buttonDialog = new UKISA.widget.ButtonDialog({
			contentId: "email-friend",
			createDialog: true,
			createButton: false,
			buttonId: "emailer-button"
		});
	},

	email: function(e) {
		var instance = this;
		var canvas = parentNode(e);		
		
		// Change the button
		var submit = YAHOO.util.Dom.getElementsByClassName("submit", "input", e);
		if (submit.length) {
			submit[0].src = submit[0].src.replace(".gif", "_loader.gif");
		}

		var callback = {
			success: function(o) {
				canvas.innerHTML = o.responseText;
				UKISA.site.SocialApps.buttonDialog.update();
			},
			failure: function(o) {
				canvas.innerHTML = "<p class=\"error\">Sorry, there is a problem with www.dulux.co.uk. We apologise for any inconvenience caused. Please try again.</p>";
				UKISA.site.SocialApps.buttonDialog.update();
			},
			timeout: 8000
		};	
		
		YAHOO.util.Connect.setForm(e);	
		var transaction = YAHOO.util.Connect.asyncRequest("POST", e.getAttribute("action"), callback);

		return false;
	}
};

/**
 * Navigation related methods such as creating modals/dialogs or enhancing normal links.
 */
 UKISA.site.Navigation = {
	/**
	 * Create a modal box for the terms.
	 *
	 * @requires UKISA.site.Modal
	 */
	terms: function(o) {
		var modal, load, success, failure, callback, link;

		// Used for closures;
		link = o;

		load = function() {
			var a = document.createElement("div");
			a.id = "terms-modal";
			a.className = "busy";

			var b = document.createElement("p");
			b.innerHTML = "Please wait&hellip;";

			a.appendChild(b);

			return a;
		};

		success = function(text) {
			var a = document.createElement("div");
			a.id = "terms-modal";
			a.innerHTML = text;
		
			return a;
		};

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

			var b = document.createElement("p");
			b.className = "error";
			b.innerHTML = "Sorry, there was a problem and we could not fetch the page for you.";

			a.appendChild(b);

			return a;
		};
		
		modal = new UKISA.widget.Modal("modal", load());
		modal.show();
		
		callback = {
			success: function(o) {
				var q;

				var footer = [
					"<p class=\"print-modal\"",
						"<a class=\"print\" href=\"#\" onclick=\"return UKISA.util.print('modal-terms-print-reference');\">Print</a>",
					"</p>"
				];

				modal.setBody(success(o.responseText));
				modal.setFooter(footer.join(""));

				// Create an IFRAME to allow printing of the contents.
				var iframe = document.createElement("iframe");
				iframe.id = "modal-terms-print-reference";
				iframe.name = "modal-terms-print-reference";
				iframe.src = link.href;
				iframe.width = "1";
				iframe.height = "1";
				iframe.style.position = "absolute";
				iframe.style.left = "-999em";
				iframe.style.top = "-999em";
				document.body.appendChild(iframe);

				
				q = YAHOO.util.Selector.query("h1", "modal", true)
				if (q && typeof Cufon !== "undefined") {
					Cufon.replace(q);
				}
			},
			failure: function(o) {
				modal.setBody(failure());
			}
		};	

		// Send the Ajax request.
		ajax = YAHOO.util.Connect.asyncRequest("GET", o.href, callback);

		return false;
	}
};/** 
 * @fileOverview Order and basket methods.
 * @author Oliver Bishop / Tom McCourt
 * @version 1.0.6
 * @changeLog Added updates to line item price and qty.
 * @changeLog Removed "animated" class when empty basket.
 * @changeLog Created.
 */

UKISA.namespace("site.Order");

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, cellPrice, cellTotal, cellQuantity;

		cell = YAHOO.util.Selector.query("#quantity-" + id, "basket", true);

		if (parseInt(cell.value) === 0) {
			
			return this.remove(el, id);
		}

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

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

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

				UKISA.site.Message.destroy();

				if (!json.success) {
					UKISA.site.Message(json.message, "error");
					
					// Reset the quantity.
					cell.value = json.items[id].quantity;
				} else {
					
					UKISA.site.Message("Your basket has been updated.", "success");
					
					cellQuantity = YAHOO.util.Selector.query("td.t-quantity input.field", "basket-row-" + id, true);
					cellPrice = YAHOO.util.Selector.query("td.t-price", "basket-row-" + id, true);
					cellTotal = YAHOO.util.Selector.query("td.t-line-total", "basket-row-" + id, true);

					cellQuantity.innerHTML = json.items[id].quantity;
					cellPrice.innerHTML = json.items[id].priceCost;
					cellTotal.innerHTML = json.items[id].totalCost;

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

				}

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

		el.className = "submit-loading";
		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.replaceParameter("successURL", "/ajax/order/basket.jsp", YAHOO.util.Connect);
		qs = UKISA.util.URL.replaceParameter("failURL", "/ajax/order/basket.jsp", YAHOO.util.Connect);
		qs = UKISA.util.URL.addParameter("update", "true", 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 modal, canvas, content, callback, busy, ajax, qs, action, message, itemId, i, ix, modalFinish, modalError, el, quantity;

		// If the action was not from the button.
		if (bt.nodeName !== "FORM") {
			el = YAHOO.util.Dom.getAncestorByTagName(bt, "form");
		} else {
			el = bt;
		}

		// When there is an Ajax error.
		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;
		};

		// If the Ajax call was a success.
		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 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/order/view_basket.gif\" alt=\"View your basket\" />";
			e.href = "/servlet/ShoppingBasketHandler";

			f = document.createElement("input");
			f.className = "continue";
			f.alt = "Continue shopping"
			f.src = "/web/images/buttons/order/continue.gif";
			f.type = "image";
			YAHOO.util.Event.addListener(f, "click", function() {
				modal.destroy();
			});

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

			// Create an image if there is one in the HTML form.
			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.replace("thumb", "small");
				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;

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

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

					UKISA.site.Order.Basket.Mini.update();
				} else {
					modal.setBody(modalError());
				}
			},
			failure: function(o) {
				modal.setBody(modalError());
			},
			timeout: 8000
		};	

		// Get the ration button value.
		if (el !== null && 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 !== null && el["ItemID"]) {
			itemId = el["ItemID"].value;
		} else {
			UKISA.notify("No ItemId parameter");
			modal.setBody(modalError());
			return;
		}

		quantity = 1;

		// Sort out the quantity.
		if ((typeof el["Quantity"] !== "undefined" || el["Quantity"])) {
			if (el["Quantity"] !== "" && typeof el["Quantity"].value !== "undefined") {
				quantity = el["Quantity"].value;
			}
		}

		// Set up the query string.
		qs = [
			(el["ItemType"]) ? "ItemType=" + el["ItemType"].value : "ItemType=sku",
			"ItemID=" + itemId,
			(el["action"]) ? "action=" + el["action"].value : "action=add",
			"Quantity=" + quantity,
			"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;
		
		// Clean status message.
		UKISA.site.Message.destroy(true);

		// 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.className = "loading";
	
		// Make the Ajax call to remove the item from the basket.
		callback = {
			success: function(o) {
				var json, anim, fields, items, group, i, ix, animatedCell;

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

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

				// Expose to second animation.
				animatedCell = cell;

				// 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, basketNav, basketTotals, basketVoucher, basketHead;
					// 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>";
						animatedCell.className = "";

						// Hide the buttons
						basketNav = document.getElementById("basket-nav");
						if (basketNav) {
							basketNav.style.visibility = "hidden";
						}
	
						basketTotals = document.getElementById("basket-totals");
						if (basketTotals) {
							basketTotals.style.visibility = "hidden";
						}
	
						basketVoucher = document.getElementById("vouchers");
						if (basketVoucher) {
							basketVoucher.style.visibility = "hidden";
						}
	
						basketHead = $("thead", "basket", true);
						if (basketHead) {
							basketHead.style.visibility = "hidden";
						}

						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.updateTotals(json);
			},
			failure: function() {},
			timeout: 8000
		};	

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

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

	/**
	 * Update the totals with JSON.
	 */
	updateTotals: function(json) {
		var subtotal, postage, vat, grand, nav;

		subtotal = $("td.t-sub-total", "basket-totals", true);
		if (subtotal) {
			subtotal.innerHTML = (json.basketSize > 0) ? json.totals.subtotal.cost : json.currency + "0.00";
		}
		
		postage = $("td.t-delivery-total", "basket-totals", true);
		if (postage) {
			postage.innerHTML = (json.basketSize > 0) ? json.totals.postage.cost : json.currency + "0.00";
		}

		vat = $("td.t-vat-total", "basket-totals", true);
		if (vat) {
			vat.innerHTML = (json.basketSize > 0) ? json.totals.vat.cost : json.currency + "0.00";
		}

		grand = $("td.t-grand-total", "basket-totals", true);
		if (grand) {
			grand.innerHTML = (json.basketSize > 0) ? json.totals.grand.cost : json.currency + "0.00";
		}

		nav = $("#basket-nav", "basket-checkout", true);

		if (nav) {
			if (json.isMinOrderValue) {
				nav.className = "";
			} else {
				nav.className = "minimum-order";
			}
		}
	},

	/**
	 * Get the totals for the basket with Ajax.
	 */
	totals: function(params) {
		var canvas, callback, ajax, qs, qsParams;

		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"
		];

		qsParams = qs.join("&");

		if (params) {
			qsParams += "&" + params.join("&");
		}

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

		return false;
	},

	Delivery: {
		
		init: function() {
			var list, items, i, ix, radio, type, ff, re;

			list = document.getElementById("delivery-options");

			if (list) {
				items = $("li", list);

				for (i = 0, ix = items.length; i < ix; i++) {
				
					re = items[i].id.match(/^(delivery-options-)([\w]+)-([\d]+)$/);
					type = re[2];
					ff = re[3];

					radio = document.createElement("span");

					if (items[i].className === "selected") {
						radio.innerHTML = '<input type="radio" name="delivery" value="' + type + '-' + ff + '" id="delivery-option-' + type + '-' + ff + '" checked="checked" />';
					} else { 
						radio.innerHTML = '<input type="radio" name="delivery" value="' + type + '-' + ff + '" id="delivery-option-' + type + '-' + ff + '" />';
					}
					
					YAHOO.util.Dom.insertBefore(radio, items[i].firstChild);
				}

				YAHOO.util.Event.addListener("basket-delivery-options", "click", UKISA.site.Order.Basket.Delivery.update);
			}
		},

		update: function(e) {
			var el, canvas, deliveryType, qs, params, ff, re, callback, ajax, list, items, i, ix, Dom, item;

			Dom = YAHOO.util.Dom;

			deliveryType = "N";

			el = YAHOO.util.Event.getTarget(e);

			if (el.nodeName === "INPUT") {

				// Set the selected class on the list item.
				list = Dom.getAncestorByTagName(el, "ul");

				items = list.getElementsByTagName("li");

				for (i = 0, ix = items.length; i < ix; i++) {
					Dom.removeClass(items[i], "selected");
				}
				
				item = Dom.getAncestorByTagName(el, "li");
				Dom.addClass(items, "selected");

				re = el.value.split("-");	

				if (re[0] === "courier") { 
					deliveryType = "Y" 
				}
			
				params = [
					"action=setcourier",
					"ff=" + re[1],
					"courier=" + deliveryType
				];

				canvas = document.getElementById("delivery-options");

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

						if (response != "") {
							canvas.innerHTML = response;
						}

						UKISA.site.Order.Basket.totals(["ff=" + re[1]]);
						
					},
					failure: function() {},
					timeout: 8000
				};	

				qs = [
					"successURL=/ajax/order/basket_delivery_options.jsp",
					"failURL=/ajax/order/basket_delivery_options.jsp"
				];

				ajax = YAHOO.util.Connect.asyncRequest("POST", "/servlet/ShoppingBasketHandler", callback, qs.join("&") + "&" + params.join("&"));
			}
		}

	}
};

UKISA.site.Order.Payment = {
	toggleBillingAddress: function(ev) {
		if (!this.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("payment-address").value;
			document.getElementById("billingTown").disabled = true;
			document.getElementById("billingTown").value = document.getElementById("payment-town").value;
			document.getElementById("billingCounty").disabled = true;
			document.getElementById("billingCounty").value = document.getElementById("payment-county").value;
			document.getElementById("billingPostCode").disabled = true;
			document.getElementById("billingPostCode").value = document.getElementById("payment-postcode").value;
		}
	}
};
