catalogue={
	init: function() {
		var images = [];
			images[0] = '/images/loginBG.gif';
			images[1] = '/images/checkoutLoginBG.gif';
			images[2] = '/images/checkoutCreateAccountBG.gif';
			images[3] = '/images/cartAlert.gif';
			images[4] = '/images/bulletOn.gif';
			images[5] = '/images/update.gif';
		$A(images).each(function(image) {
			var src = image;
			image = document.createElement('img');
			image.src = src;
		});
		
		
		Ajax.Responders.register({
			onCreate: function() {
				document.body.appendChild(Builder.node('img', {id:'loader', src:'/images/interstitial_loading.gif'}));
			},
			onComplete: function() {
				if ($('loader')) {$('loader').parentNode.removeChild($('loader'))};
			}
		});
		
		if ($('shopnow')) {$('shopnow').observe('click', catalogue.switchOnProductList);}
		if ($('loginPopup')) {$('loginPopup').observe('click', function() {
			if ($('login')) {
				$('login').parentNode.removeChild($('login'));
			} else {
				catalogue.user.login.init();
			}
		});}
		if ($('logoutButton')) {$('logoutButton').observe('click', catalogue.user.logout);}
		if ($('searchForm')) {$('searchForm').observe('submit', catalogue.search.init);}
		if ($('search')) {
			$('search').observe('click', function() {inputResponder($('search'), $('searchLabel'))}.bind(this));
			$('search').observe('blur', function() {inputResponder($('search'), $('searchLabel'))}.bind(this));
		}
		if ($('contactForm')) {$('contactForm').observe('submit', catalogue.submitContactForm);}
		
		if ($('insertPageButton')) {$('insertPageButton').observe('click', catalogue.page.editForm.init);}
//		if ($('sortPagesButton')) {$('sortPagesButton').observe('click', catalogue.showPageSortInterface);}
		if ($('insertProductButton')) {$('insertProductButton').observe('click', catalogue.product.editForm.init);}
		if ($('insertCategoryButton')) {$('insertCategoryButton').observe('click', catalogue.category.editForm.init);}
//		if ($('sortCategoriesButton')) {$('sortCategoriesButton').observe('click', catalogue.showCategorySortInterface);}
		catalogue.cart.init();
		catalogue.initProductSelects();
		catalogue.initAddToCartButtons();
		if ($('logged_in_admin') && $F('logged_in_admin') == 'true') {
			catalogue.drawEditInterface();
		}
	},
	initProductSelects: function() {
		var selects = document.getElementsByTagName('select');
		for (var i = 0, j = selects.length; i < j; i++) {
			if (selects[i].id.indexOf('variation') != 0) {
				var productID = selects[i].id.substring('productID'.length, selects[i].id.indexOf('variation'));
				$(selects[i]).observe('change', function() {
					var productID = this.id.substring(this.id.indexOf(productID) + 'productID'.length + 1, this.id.indexOf('variation'));
					catalogue.product.id = productID;
					catalogue.product.populate();
					catalogue.product.setVariationPrice();
				});
			}
		}
	},
	initAddToCartButtons: function() {
		var buttons = document.getElementsByTagName('button');
		$A(buttons).each(function (button) {
			if ($(button).id.indexOf('AddToCart') != -1) {
				$(button).observe('click', function() {
					var productID = this.id.substring('AddToCart'.length, this.id.length);
					catalogue.product.id = productID;
					catalogue.product.populate();
					var productVariation = catalogue.product.isolateProductVariation();
//					alert(productVariation.id);
					catalogue.cart.updateItemCount(productVariation.id, 1);
				});
			}
		});
	},
	validate: {
		string: function(variable) {
			var string = String(variable);
			if (string == 'null') {
				return '';
			}
			return string;
		},
		field: function(field) {
			var errors = new Array();
			var warnings = new Array();
			if (field.className.indexOf('required') != -1) {
				if (field.value.length == 0) {
					errors.push("Sorry, we require that you complete this field.");
				}
			}
			if (field.maxLength && field.type != "submit") {
				if (field.value.length > field.maxLength) {
					errors.push('Please reduce this field to ' + field.maxLength + ' characters.');
				}
			}
			var type = field.name;
			switch (type) {
				case "url":
					var parent;
					if ($('parentCategory')) {
						parent= $F('parentCategory');
					}
					if ($('parentPage')) {parent=$F('parentPage');}
					field.value = field.value.toLowerCase();
					field.value = field.value.replace(/&/g, "and");
					field.value = field.value.replace(/[ !"£$%^&*()_=+{}\[\];:'@#~,<.>\/?\\|]/g, "-")
					warnings.push("Please review your validated url.");
					new Ajax.Request('/utilities/ajax.asp?action=SelectCountURL', {
						asynchronous: false,
						parameters: {
							url: field.value,
							parent:parent
						},
						onSuccess: function(request) {
							var response = request.responseText;
							if (response == 'error') {
								message.push("We were unable to verify your URL.");
							} else if (response != 0) {
								errors.push("This URL is already in use.");
							}
						},
						onFailure: function(request) {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We were unable to verify your URL.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
					break;
				case "email": 
					var regEx = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
					if (!regEx.test(field.value)) {
						errors.push("This doesn't appear to be a valid email address.");
					}
					break;
				case "password": 
					var regEx = /^[a-zA-Z]\w{3,14}$/i
					if (!regEx.test(field.value)) {
						errors.push("We need at least 4-15 characters, and you might want to also use a mix of upper and lower cases and digits.");
					}
					break;
				case "password2":
					var originalField = document.getElementById(field.id.substring(0, field.id.length-1));
					if (originalField.value != field.value) {
						errors.push("Your passwords do not match");
					}
					break;
				case "website":
					if (field.value.substring(0, "http://".length) != "http://") {
						errors.push("Please use the format 'http://www.mydomain.com'");
					}
					break;
				case "startTime":
				case "endTime":
					var regEx = /^([0-1][0-9]|[2][0-3]):([0-5][0-9])([ap]m){0,1}$/i
					if (!regEx.test(field.value)) {
						errors.push("Please use the format hh:mm, in the 24hr clock - am/pm is optional.");
					}
					break;
				case "date":
					// validates for dd/mm/yyyy and leap years
					var regEx = /^((((0?[1-9]|[12]\d|3[01])[\/](0?[13578]|1[02])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\/](0?[13456789]|1[012])[\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\/]0?2[\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\/]0?2[\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00))))$/
					if (!regEx.test(field.value)) {
						errors.push("Please use the format dd/mm/yyyy.");
					}
					break;
				case "description":
					tinyMCE.triggerSave(false,true);
					var escaped = escape(field.value);
					if (escaped.length > 5000) {
						errors.push("The description is longer than the maximum 5000 characters.");
					}
					break;
				case "categories":
					if (field.selectedIndex == -1) {
						errors.push("Please select at least one category");
					}
					break;
				case "suppliers":
					if (field.options[field.selectedIndex].innerHTML == "Suppliers...") {
						errors.push("Please select the product's supplier");
					}
					break;
				default:
					if (field.name.indexOf('cost') != -1) {
						var regEx = /^\d+(\.\d{2})?$/
						if (!regEx.test(field.value)) {
							errors.push("Please enter a valid cost.");
						}
					}
					if (field.name.indexOf('weight') != -1) {
						var regEx = /^\d+(\.\d{1,2})?$/
						if (!regEx.test(field.value)) {
							errors.push("Please enter a valid weight (up to 2 decimal places).");
						}
					}
			}
			catalogue.validate.hideFormMessage(field);
			if (warnings.length > 0) {
				catalogue.validate.showFormMessage(field, warnings);
			}
			if (errors.length > 0) {
				catalogue.validate.showFormMessage(field, errors);
				return false;
			}
			return true;
		},
		form: function(form) {
			var inputs = form.getElementsByTagName("input");
			var textareas = form.getElementsByTagName("textarea");	
			var selects = form.getElementsByTagName("select");
			var invalid = false;
			$A(inputs).each(function(input) {
				if (!catalogue.validate.field(input)) {
					if(!invalid) {$(input).scrollTo();}
					invalid = true;
				}
			});
			$A(textareas).each(function(textarea) {
				if (!catalogue.validate.field(textarea)) {
					if(!invalid) {$(textarea).scrollTo();}
					invalid = true;
				}
			});
			$A(selects).each(function(select) {
				if (!catalogue.validate.field(select)) {
					if(!invalid) {$(select).scrollTo();}
					invalid = true;
				}
			});
			return !invalid;
		},
		showFormMessage: function(field, messages) {
		    catalogue.validate.hideFormMessage(field);
			var div = document.createElement("div");
				div.id = field.id + "Error";
				div.className="error";
			var html = "";
			for (var i =0; i < messages.length; i++) {
				html += "<p>" + messages[i] + "</p>";
			}
			div.innerHTML = html;
			field.parentNode.appendChild(div);
		},
		hideFormMessage: function(field) {
			var message = document.getElementById(field.id + "Error");
			if (message) {
				message.parentNode.removeChild(message);
			}
		}
	},
	drawCategoryEditInterface: function() {
		// categories
		if ($('nav')) {
			var categories = $('nav').getElementsByTagName('li');
			var categories = $A(categories);
				categories.each(function(category){
					category.appendChild(Builder.node('a', {id:category.id + 'editButton', className:'editButton'}, 'edit'));
					$(category.id + 'editButton').observe('click', function(e) {
						var id = (e.srcElement) ? e.srcElement.id : e.target.id;
							id = id.substring('category_'.length, id.length-'editButton'.length);
						catalogue.category.id = id;
						catalogue.category.populate();
						catalogue.category.editForm.init();
					}.bind(this));
				});
		}
	},
	drawPageEditInterface: function(){
		if ($('pNav')) {
			var pages = $('pNav').getElementsByTagName('li');
			var pages = $A(pages);
				pages.each(function(page){
					page.appendChild(Builder.node('a', {id:page.id + 'editButton', className:'editButton'}, 'edit'));
					$(page.id + 'editButton').observe('click', function(e) {
						var id = (e.srcElement) ? e.srcElement.id : e.target.id;
							id = id.substring('page_'.length, id.length-'editButton'.length);
						catalogue.page.id = id;
						catalogue.page.populate();
						catalogue.page.editForm.init();
					}.bind(this));
				});
		}
		if ($('subPageNav')) {
			var pages = $('subPageNav').getElementsByTagName('li');
			var pages = $A(pages);
				pages.each(function(page){
					page.appendChild(Builder.node('a', {id:page.id + 'editButton', className:'editButton'}, 'edit'));
					$(page.id + 'editButton').observe('click', function(e) {
						var id = (e.srcElement) ? e.srcElement.id : e.target.id;
							id = id.substring('page_'.length, id.length-'editButton'.length);
						catalogue.page.id = id;
						catalogue.page.populate();
						catalogue.page.editForm.init();
					}.bind(this));
				});
		}
	},
	drawProductEditInterface: function() {
		if ($('productList')) {
			var products = $('productList').getElementsByTagName('li');
			var products = $A(products);
				products.each(function(product){
					product.appendChild(Builder.node('a', {id:product.id + 'editButton', className:'editButton'}, 'edit'));
					$(product.id + 'editButton').observe('click', function(e) {
						var id = (e.srcElement) ? e.srcElement.id : e.target.id;
							id = id.substring('product_'.length, id.length-'editButton'.length);
						catalogue.product.id = id;
						catalogue.product.populate();
						catalogue.product.editForm.init();
					}.bind(this));
				});
			Sortable.create('productList', {
				overlap:'horizontal', 
				constraint: false, 
				onUpdate:function() {
					catalogue.category.updateProductRanking(Sortable.serialize('productList'));
				}
			});
		}
	},
	showCategorySortInterface: function() {
		if ($('navLevel1')) {
			Sortable.create('navLevel1', {
				tree:true,
				constraint:false,
				onChange: function(element) {	
					catalogue.category.id = element.id.substring(element.id.indexOf('_')+1, element.id.length);
				},
				onUpdate: function() {
					// get the element, and it's parent, recording whether it's a child of that parent or a sibling
					var category = $('category_' + catalogue.category.id);
					var child = false;
					var newParent;
					if (category.previousSibling) {
//						child = confirm('Press OK to make move this item into a sublist, or cancel to make it a sibling.');
						newParent = category.previousSibling;
					} else {
						child = true;
						newParent = category.parentNode.parentNode;
					}
					var categoryID = category.id.substring('category_'.length, category.id.length);
					var newParentID = newParent.id.substring('category_'.length, newParent.id.length);
					catalogue.updateCategoryRanking(categoryID, newParentID, child);
				}
			});
		}
	},
	showPageSortInterface: function() {
		if ($('pNav')) {
			Sortable.create('pNav', {
				constraint: false,
//				containment: ['pNav', 'subPageNav'],
				onChange: function(element) {	
					catalogue.page.id = element.id.substring(element.id.indexOf('_')+1, element.id.length);
				},
				onUpdate: function() {
					// get the element, and it's parent, recording whether it's a child of that parent or a sibling
					var page = $('page_' + catalogue.page.id);
					var child = false;
					var newParent;
					if (page.previousSibling) {
//						child = confirm('Press OK to make move this item into a sublist, or cancel to make it a sibling.');
						newParent = page.previousSibling;
					} else {
						child = true;
						newParent = page.parentNode.parentNode;
					}
					var pageID = page.id.substring('page_'.length, page.id.length);
					var newParentID = newParent.id.substring('page_'.length, newParent.id.length);
					catalogue.updatePageRanking(pageID, newParentID, child);
				}
			});
		}
		if ($('subPageNav')) {
			Sortable.create('subPageNav', {
				constraint: false,
//				containment: ['pNav', 'subPageNav'],
				onChange: function(element) {	
					catalogue.page.id = element.id.substring(element.id.indexOf('_')+1, element.id.length);
				},
				onUpdate: function() {
					// get the element, and it's parent, recording whether it's a child of that parent or a sibling
					var page = $('page_' + catalogue.page.id);
					var child = false;
					var newParent;
					if (page.previousSibling) {
						child = confirm('Press OK to make move this item into a sublist, or cancel to make it a sibling.');
						newParent = page.previousSibling;
					} else {
						child = true;
						newParent = page.parentNode.parentNode;
					}
					var pageID = page.id.substring('page_'.length, page.id.length);
					var newParentID = newParent.id.substring('page_'.length, newParent.id.length);
					catalogue.updatePageRanking(pageID, newParentID, child);
				}
			});
		}
	},
	drawEditInterface: function() {
		document.body.className = 'admin';
/*		LOAD TinyMCE ON THE FLY
//		var script = document.createElement('script');
//			script.type = 'text/javascript';
//			script.src = '/utilities/tiny_mce/tiny_mcex.js';
//			document.getElementsByTagName('head')[0].appendChild(script);  

//		new Ajax.Request('/utilities/tiny_mce/tiny_mce.js', {
//			asynchronous: false,
//			onSuccess: function(request) {
//				alert(request.responseText);
//				window.eval(request.responseText);
//			},
//			onFailure: function(request) {
//				alert(request.responseText);
//			}
//		});
*/
/*		DO CATEGORIES & PRODUCTS AT ONCE
		var editables = $('nav').getElementsByTagName('li');
			editables.concat($('productList').getElementsByTagName('li'));
			editables = $A(editables);
			editables.each(function(editable) {
				editable.appendChild(Builder.node('a', {id:editable.id + 'editButton', className:'editButton'}, 'edit'));
				$(editable.id + 'editButton').observe('click', function(e) {
					var id = (e.srcElement) ? e.srcElement.id : e.target.id;
					var type = id.substring(0, id.indexOf('_'));
						id = id.substring(type.length+1, id.length-'editButton'.length);
					catalogue[type].id = id;
					catalogue[type].populate();
					catalogue[type].editForm.init();
				}.bind(this));
			});
*/		
		catalogue.drawCategoryEditInterface();
		catalogue.showCategorySortInterface();
		catalogue.drawPageEditInterface();
		catalogue.showPageSortInterface();
		catalogue.drawProductEditInterface();		
	},
	removeEditInterface: function() {
		document.body.className = '';
		if ($('pageManagement')) {Effect.Fade('pageManagement');}
		if ($('productManagement')) {Effect.Fade('productManagement');}
		if ($('categoryManagement')) {Effect.Fade('categoryManagement');}
		var buttons = document.getElementsByClassName('editButton');
			buttons = $A(buttons);
			buttons.each(function(button) {
				button.parentNode.removeChild(button);
			});
		if ($('nav')) {Sortable.destroy('nav');}
		if ($('pNav')) {Sortable.destroy('pNav');}
		if ($('productList')) {Sortable.destroy('productList');}
		Effect.Fade($('memberFunctions'), {duration:0.5});
//		setTimeout("$('login').style,display = 'none'; $('memberFunctions').style.display = 'none';", 500);
	},
	updateCategoryRanking: function(categoryID, newParentID, child) {
		child = (child) ? 1 : 0;
		newParentID = (newParentID) ? newParentID : 0;
		new Ajax.Request('/utilities/ajax.asp?action=UpdateCategoryRanking', {
			parameters: 'categoryID=' + categoryID + '&newParentID=' + newParentID + '&child=' + child,
			onSuccess: function (request) {
//				catalogue.drawCategoryList(window.location.href);
				catalogue.category.id = null;
			},
			onFailure: function (request) {
				var myAlert = catalogue.alerts.newAlert();
					myAlert.message = "We were unable to move your category.";
					myAlert.type = 'error';
					myAlert.show();
					myAlert.hide(4000);
			}
		});
	},
	updatePageRanking: function(pageID, newParentID, child) {
		child = (child) ? 1 : 0;
		newParentID = (newParentID) ? newParentID : 0;
		new Ajax.Request('/utilities/ajax.asp?action=UpdatePageRanking', {
			parameters: 'pageID=' + pageID + '&newParentID=' + newParentID + '&child=' + child,
			onSuccess: function (request) {
//				catalogue.drawPageList(window.location.href);
				catalogue.page.id = null;
			},
			onFailure: function (request) {
				var myAlert = catalogue.alerts.newAlert();
					myAlert.message = "We were unable to move your page.";
					myAlert.type = 'error';
					myAlert.show();
					myAlert.hide(4000);
			}
		});
	},
	switchOnProductList: function() {
		if ($('pageSubList')) {Effect.Fade('pageSubList', {duration: 0.3})};
		if ($('shopnow')) {Effect.Fade('shopnow', { duration: 0.3 })};
		if ($('key')) {Effect.Fade('key', { duration: 0.3 })};
		if ($('nav2')) {Effect.Appear('nav2', {duration:0.3, queue:'end'})};
	},
	createPageHierarchy: function(currentURL, array, start) {
		var newArray = [];
		for (var i = ((start) ? start : 0), j = array.length; i < j; i++) {
			if (currentURL.indexOf(array[i].url) != -1) {
				array[i].selected = true;
			}
			newArray.push(array[i]);
			var currentNodeLevel = array[i].NodeLevel
			if (array[i+1] && array[i+1].NodeLevel > currentNodeLevel) {
				newArray[newArray.length-1].sublist = catalogue.createPageHierarchy(currentURL, array, i+1)
				while (array[i+1] && array[i+1].NodeLevel != currentNodeLevel) {
					if (array[i+1].NodeLevel < currentNodeLevel) {
						return newArray;
					} else if (array[i+1].NodeLevel > currentNodeLevel) {
						i++;
					}
				}
			} else if ( (!(array[i+1])) || (array[i+1].NodeLevel < currentNodeLevel) ) {
				return newArray;
			}
		}
		return newArray;
	},
	drawList: function(id, prefix, array, parentLine, limit){
		var html = '<ul';
		if (id && id != '') {html += ' id="' + id + '"';}
		html += '>';
		for (var i = 0, j = array.length; i < j; i++) {
			html += array[i].selected ? '<li class="selected"' : '<li';
			html += ' id="' + prefix + array[i].id + '"><a href="' + parentLine + array[i].url + '/" title="' + array[i].linkTitle + '">' + array[i].linkText + '</a>';
			if (array[i].selected && array[i].sublist && ((!limit) || (limit > array[i].NodeLevel))) {
				html += catalogue.drawList((id=='nav') ? 'navLevel1' : '', prefix, array[i].sublist, parentLine + array[i].url + '/');
			}
			html += '</li>';
		}
		html += '</ul>';
		return html;
	},
	drawCategoryList: function(location) {
		new Ajax.Request('/utilities/ajax.asp?action=SelectCategoryNav', {
			onSuccess: function (request) {
				if (request.responseText != 'error') {
					var categories = (eval('(' + request.responseText + ');').records);
						categories = catalogue.createPageHierarchy(window.location.href, categories);
					if ($('nav')) {$('sNav').removeChild($('nav'));}
					$('sNav').innerHTML += catalogue.drawList('nav', 'category_', categories, '/');
					if ($('categoryID')) {
						catalogue.drawCategoryEditInterface();
					}
				}
			}
		});
	},
	drawPageList: function(location) {
		new Ajax.Request('/utilities/ajax.asp?action=SelectPageNav', {
			onSuccess: function (request) {
				if (request.responseText != 'error') {
					var pages = (eval('(' + request.responseText + ');').records);
						pages = catalogue.createPageHierarchy(window.location.href, pages)
					var pNav;
					if (pNav = $('pNav')) {
						var parent = pNav.parentNode;
							parent.removeChild(pNav);
						var div = document.createElement('div');
							div.innerHTML = catalogue.drawList('pNav', 'page_', pages, '/', 1);
						parent.appendChild(div);
					}
					var subPageNav;
					if (subPageNav = $('subPageNav')) {
						var parent = subPageNav.parentNode;
							parent.removeChild(subPageNav);
						var div = document.createElement('div');
						for (var i = 0, j = pages.length; i < j; i++) {
							if (pages[i].selected && pages[i].url != '/') {
								div.innerHTML = catalogue.drawList('subPageNav', 'page_', pages[i].sublist, '/' + pages[i].url + '/');
								parent.appendChild(div);
							}
						}
					}
					if ($('logged_in_admin') && $F('logged_in_admin') == 'true') {
						catalogue.drawPageEditInterface();
					}
				}
			}
		});
	},
	drawProductList: function() {
		new Ajax.Request('/utilities/ajax.asp?action=SelectProductsByCategoryId', {
			parameters: {
				categoryID: $F('categoryID')
			},
			onSuccess: function (request) {
				var ul = $('productList');
					ul.innerHTML = "";
				if (request.responseText != 'error') {
					var products = (eval('(' + request.responseText + ');').records);
					$A(products).each(function (product) {
						var li = Builder.node('li', {id:'product_' + product.id}, [
							Builder.node('h2', [
								Builder.node('a', {href:product.url + '/', title:product.longTitle}, product.shortTitle)
							])
						]);
						if (product.variations) {
							var variations = collapseVariations(product.variations);
							$A(variations).each(function(variation) {
								var select = Builder.node('select', {id:'productID' + product.id + 'variation' + variation.id})
								var values = variation.values;
								$A(values).each(function(value) {
									select.appendChild(Builder.node('option', {value:value.ValueID}, value.ValueName));
								});
								li.appendChild(select);
							});
						}
						li.appendChild(Builder.node('span', {id:'product' + product.id + 'cost', className:'cost'}, returnCurrency(product.variations[0].unitPrice)));
						li.appendChild(Builder.node('button', {id:'AddToCart' + product.id}, 'Add to Cart'));
						ul.appendChild(li);
					});
					catalogue.initProductSelects();
					catalogue.initAddToCartButtons();
					catalogue.drawProductEditInterface();
				}
			}
		});
	},
	drawAdminMenu: function() {
		var menu = ($('memberFunction').getElementsByTagName('ul'))[0];
//			menu.appendChild(Builder.node('li', [Builder.node('a', {id:'SortPagesButton'}, 'Move Page')]));
			menu.appendChild(Builder.node('li', [Builder.node('a', {id:'insertProductButton'}, 'Insert a Product')]));
			menu.appendChild(Builder.node('li', [Builder.node('a', {id:'insertCategoryButton'}, 'Insert a Category')]));
//			menu.appendChild(Builder.node('li', [Builder.node('a', {id:'SortCategoriesButton'}, 'Move a Category')]));
			menu.appendChild(Builder.node('li', [Builder.node('a', {id:'insertPageButton'}, 'Insert a Page')]));
		$('insertProductButton').observe('click', catalogue.product.editForm.init);
		$('insertCategoryButton').observe('click', catalogue.category.editForm.init);
		$('sortCategoriesButton').observe('click', catalogue.showCategorySortInterface);
		$('insertPageButton').observe('click', catalogue.page.editForm.init);
		$('sortPagesButton').observe('click', catalogue.showPageSortInterface);
	},
	hideEditButtons: function() {
		var buttons = $(document.body).getElementsByClassName('editButton');
		$A(buttons).each(function (button) {
			$(button).hide();
		});
	},
	showEditButtons: function() {
		var buttons = $(document.body).getElementsByClassName('editButton');
		$A(buttons).each(function (button) {
			$(button).show();
		});
	},
	confirmExit: function(e) {
		e.returnValue = '';
	},
	toggleLoader: function (direction, container) {
		container = (container) ? container : document.body;
		if (!$('loader') && (direction == 'on') ) {
			container.appendChild(Builder.node('img', {id:'loader', src:'/images/interstitial_loading.gif'}));
		}
		if ($('loader') && (direction == 'off') ) {
			$('loader').remove();
		}
	},
	fadeDestroy: function(IDs, duration) {
		$A(IDs).each(function(id) {
			if ($(id)) {
				Effect.Fade(id, {duration: (duration) ? duration : 0, afterFinish:function() {
					$(id).remove();
				}});
			}
		});
	},
	
	alerts: {
		alertCount:0,
		newAlert: function() {
			this.alertCount++;
			return {
				id: 'alert' + this.alertCount,
				type: false,
				message: false,
				
				show: function() {
					document.body.appendChild(Builder.node('div', {id:this.id, style:'display:none;', className:'alert ' + this.type}, this.message));
					$(this.id).appendChild(Builder.node('a', {id:'close' + this.id, className:'close'}, 'Close'));
					$('close' + this.id).observe('click', function() {this.hide();}.bind(this));
					var dimensions = $(this.id).getDimensions();
					var top = document.viewport.getScrollOffsets().top + (document.viewport.getHeight()/2) - (dimensions.height/2);
					var left = (document.viewport.getWidth()/2) - (dimensions.width/2);
					$(this.id).setStyle({
						position:'absolute',
						left: left + 'px',
						top: top + 'px'
					});
					Effect.Appear(this.id, {duration:0.3});
				},
				hide: function(delay) {
					// if still exists, hide it, then destroy it
					setTimeout('if ($(\'' + this.id + '\')) {Effect.Fade("' + this.id + '", {duration:0.3}); setTimeout(\'if ($(\"' + this.id + '\")) {$(\"' + this.id + '\").parentNode.removeChild($(\"' + this.id + '\"));}\', 300);}', delay ? delay : 0);
					catalogue.alerts.alertCount--;
				}
			}
		}
	},
	
	user: {
		registration: {
			init:function () {
				if ($('login')) {$('login').parentNode.removeChild($('login'));}
				catalogue.cart.checkout.init();
			}, 
			form: function() {
				return Builder.node('form', {id:'checkoutNewAccountForm', style:'display:none;'}, [
					Builder.node('ul', [
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerName'}, 'Your name:'),
							Builder.node('input', {id:'customerName', type:'text', name:'name', maxlength:'20', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerOrganisation'}, 'Your company:'),
							Builder.node('input', {id:'customerOrganisation', type:'text', name:'organisation', maxlength:'20', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerEmail'}, 'Your email:'),
							Builder.node('input', {id:'customerEmail', type:'text', name:'email', maxlength:'50', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerPassword'}, 'Your password:'),
							Builder.node('input', {id:'customerPassword', type:'text', name:'password', maxlength:'50', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerPassword2'}, 'Confirm Password:'),
							Builder.node('input', {id:'customerPassword2', type:'text', name:'password2', maxlength:'50', className:'required'})
						])
					]),
					Builder.node('h3', 'Shipping Address'),
					Builder.node('ul', [										
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerStreet'}, 'Street:'),
							Builder.node('input', {id:'customerStreet', type:'text', name:'street', maxlength:'20', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerCity'}, 'City:'),
							Builder.node('input', {id:'customerCity', type:'text', name:'city', maxlength:'20', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerPostalCode'}, 'Postal Code:'),
							Builder.node('input', {id:'customerPostalCode', type:'text', name:'postal_code', maxlength:'10', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'customerCountry'}, 'County:'),
							Builder.node('input', {id:'customerCountry', type:'text', name:'country', maxlength:'20', className:'required'})
						])
					]),
					Builder.node('input', {id:'createNewAccountSubmit', type:'submit', className:'button', value:'Submit'})
				])
			},
			submit:   function(e) {
				Event.stop(e);
				if (catalogue.validate.form($('checkoutNewAccountForm'))) {
					new Ajax.Request('/utilities/ajax.asp?action=register', {
						parameters: {
							name: $F('customerName'),
							organisation: $F('customerOrganisation'),
							email: $F('customerEmail'),
							password: $F('customerPassword'),
							customerStreet: $F('customerStreet'),
							customerCity: $F('customerCity'),
							customerPostalCode: $F('customerPostalCode'),
							customerCountry: $F('customerCountry')
						},
						onSuccess: function(request) {
							if (request.responseText == 'error') {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "We were unable to register your details - why not give us a call?";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							} else {
								if (request.responseText) {
									var json = eval('(' + request.responseText + ');');
									Effect.Fade($('loginPopup'), {duration:0.5});
									var div = Builder.node('div', {id:'memberFunctions', style:'display:none'}, [
										Builder.node('ul', [
											Builder.node('li', [
												Builder.node('a', {id:'logoutButton'}, 'Logout')
											])
										])
									]);
									$('loginPopup').parentNode.insertBefore(div, $('loginPopup').parentNode.firstChild);
									$('logoutButton').observe('click', catalogue.user.logout);
									Effect.Appear($('memberFunctions'), {queue:'end'});
									
									$('existingCustomer').parentNode.removeChild($('existingCustomer'));
									$('newCustomer').parentNode.removeChild($('newCustomer'));
									catalogue.cart.checkout.drawOrderSummary();
								} else {
									var myAlert = catalogue.alerts.newAlert();
										myAlert.message = "Your details were not recognised - please try again, or give us a call.";
										myAlert.type = 'error';
										myAlert.show();
										myAlert.hide(4000);
								}
							}
						},
						onFailure: function() {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We were unable to register your details - why not give us a call?";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
				}
			}
		},
		login: {
			init: function () {
				$('header').appendChild(Builder.node('form', {id:'login', method:'post', action:'index.asp?action=login'}, [
					Builder.node('ul', {className:'inputs'}, [
						Builder.node('li', [
							Builder.node('label', {id:'login_email_label'}, 'username...'),
							Builder.node('input', {type:'text', id:'login_email', name:'email', value:'username...', maxlength:'50'})
						]),
						Builder.node('li', [
							Builder.node('label', {id:'login_password_label'}, 'password'),
							Builder.node('input', {type:'password', id:'login_password', name:'password', value:'password', maxlength:'15'})
						]),
					]), 
					Builder.node('ul', {className:'links'}, [
						Builder.node('li', [
							Builder.node('a', {id:'register'}, 'Register')
						]),
						Builder.node('li', [
							Builder.node('a', {id:'forgotPassword'}, 'Forgotten your password?')
						]),
					]),
					Builder.node('input', {type:'submit', className:'button', value:'Login'})
				]));
				$('login_email').observe('focus', function() {inputResponder($('login_email'), $('login_email_label'));});
				$('login_email').observe('blur', function() {inputResponder($('login_email'), $('login_email_label'));});
				$('login_password').observe('focus', function() {inputResponder($('login_password'), $('login_password_label'));});
				$('login_password').observe('blur', function() {inputResponder($('login_password'), $('login_password_label'));});
				$('register').observe('click', function() {
					catalogue.user.registration.init();
					Effect.toggle('checkoutNewAccountForm', 'blind', { duration: 0.3 });
				});
				$('forgotPassword').observe('click', function() {
					catalogue.user.registration.init();
					Effect.toggle('checkoutPasswordRecoveryForm', 'blind', { duration: 0.3 });
				});
				$('login').observe('submit', catalogue.user.login.submit);
			},
			submit: function (e) {
				Event.stop(e);
//				if (catalogue.validate.form($('login'))) {
					new Ajax.Request('/utilities/ajax.asp?action=login', {
						parameters: 'email=' + $F('login_email') + '&password=' + $F('login_password'),
						onSuccess: function(request) {
							if (request.responseText == 'error') {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "We were unable to log you in - why not give us a call?";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							} else {
								if (request.responseText) {
									var user = eval('(' + request.responseText + ');').records[0];
									if (user.Administrator == 'true') {
										window.location = window.location;
										document.body.appendChild(Builder.node('input', {id:'logged_in_admin', type:'hidden', value:'true'}));
//										catalogue.drawAdminMenu();
//										catalogue.drawEditInterface();
									}
									document.body.appendChild(Builder.node('input', {id:'logged_in', type:'hidden', value:'true'}));
									var div = Builder.node('div', {id:'memberFunctions', style:'display:none'}, [
										Builder.node('ul', [
											Builder.node('li', [
												Builder.node('a', {id:'logoutButton'}, 'Logout')
											])
										])
									]);
									document.body.appendChild(Builder.node('input', {type:'hidden', id:'logged_in', value:'true'}));
									$('login').parentNode.insertBefore(div, $('login').parentNode.firstChild);
									$('logoutButton').observe('click', catalogue.user.logout);
									Effect.Fade($('login'), {duration:0.5});
									Effect.Fade($('loginPopup'), {duration:0.5});
									Effect.Appear($('memberFunctions'), {queue:'end'});
								} else {
									var myAlert = catalogue.alerts.newAlert();
										myAlert.message = "We couldn't match your details to any of our accounts - do you need to register?";
										myAlert.type = 'error';
										myAlert.show();
										myAlert.hide(4000);
								}
							}
						},
						onFailure: function() {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We couldn't log you in - why not give us a call?";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
//				}
			}
		},
		logout: function() {
			new Ajax.Request('/utilities/ajax.asp?action=logout', {
				onSuccess: function() {
					if ($('logged_in')) {$('logged_in').parentNode.removeChild($('logged_in'));}
					if ($('logged_in_admin')) {$('logged_in_admin').parentNode.removeChild($('logged_in_admin'));}
					if ($('checkout')) {$('checkout').parentNode.removeChild($('checkout'));}
					catalogue.removeEditInterface();
					Effect.Appear('loginPopup', {queue:'end'});
				},
				onFailure: function() {
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "We were unable to log you out - if you are on a public computer, please close the browser window before leaving.";
						myAlert.type = 'error';
						myAlert.show();
						myAlert.hide(4000);
				}
			});
		},
		recoverPassword: function(e) {
			Event.stop(e);
			if (catalogue.validate.form($('checkoutPasswordRecoveryForm'))) {
				new Ajax.Request('/utilities/ajax.asp?action=RecoverPassword', {
					parameters: {
						email: $F('checkoutPasswordRecoveryEmail')
					},
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We were unable to send you your details - why not give us a call?";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							Effect.toggle('PasswordRecovery', 'blind', {duration: 0.3 });
							$('checkoutLoginForm').insertBefore(Builder.node('p', 'Please check your email and login with the password provided'), $('checkoutLoginForm').firstChild);
							Effect.toggle('checkoutLoginForm', 'blind', {duration: 0.3, queue:'end'})
						}
					},
					onFailure: function() {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We were unable to send you your details - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					}
				});
			}
		},
		profile: {}
	},
	
	cart: {
		total: false,
		user: false,
		products: [],
		init: function() {
			new Ajax.Request('/utilities/ajax.asp?action=SelectOrderTotal', {
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						handleError("We could not initialise your cart.");
					} else {
						$('header').appendChild(Builder.node('div', {id:'cartTotal'}, [
							Builder.node('span', returnCurrency(request.responseText, '£'))
						]));
						$('header').appendChild(Builder.node('div', {id:'cart', style:'display:none'}));
						catalogue.cart.draw();
						$('cartTotal').observe('click', catalogue.cart.toggle);
					}
				}
			});	
		},
		toggle: function() {
			Effect.toggle('cart', 'blind', {duration:0.3});
		},
		draw: function() {
			$('cart').innerHTML = "";
			new Ajax.Request('/utilities/ajax.asp?action=SelectProductsByOrderID', {
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						handleError("We were unable to list the products in your order at this time.");
					} else {
						if (request.responseText == "") {
							$('cart').appendChild(Builder.node('p', 'Your cart is currently empty.'));
						} else {
							catalogue.cart.products = eval('(' + request.responseText + ');');
							catalogue.cart.total = 0;
						
							var list = Builder.node('ul');
							$A(catalogue.cart.products).each(function(product) {
								var item = Builder.node('li', {id:'cartItem' + product.VariationID}, [
									Builder.node('strong', product.shortTitle),
									Builder.node('span', returnCurrency(product.unitPrice * product.quantity, '£')),
									Builder.node('a', {id:'cartDelete' + product.VariationID, className:'delete'}, 'Delete'),
									Builder.node('input', {id:'cartQuantity' + product.VariationID, className:'quantity', value:product.quantity}),

								]);
								$A(product.variationValues).each(function (variationValue) {
									item.appendChild(Builder.node('small', variationValue.ValueName));
								});
								list.appendChild(item);
								catalogue.cart.total = catalogue.cart.total + product.unitPrice * product.quantity;
							});
							$('cart').appendChild(list);
							$('cart').appendChild(Builder.node('div', {id:'cartFooter'}, [
								'Subtotal:',
								Builder.node('span', returnCurrency(catalogue.cart.total, '£')),
								Builder.node('a', {id:'checkoutBtn'}, 'Checkout')
							]));
							$('checkoutBtn').observe('click', function() {
								catalogue.cart.toggle();
								catalogue.cart.checkout.init();
							});
							$A($('cart').getElementsByClassName('delete')).each(function(deleteButton) {
								$(deleteButton).observe('click', function() {
									var productVariationID = this.id.substring('cartDelete'.length, this.id.length);
									catalogue.cart.removeItem(productVariationID);
								});
							});
							$A(catalogue.cart.products).each(function(product) {
								$('cartQuantity' + product.VariationID).observe('change', function() {
									if (this.value < 0) {
										var update = product.quantity-1;
									} else {
										var update = this.value - product.quantity;
									}
									catalogue.cart.updateItemCount(product.VariationID, update);
								});
							});
							
							if ($('checkout')) {
								catalogue.cart.checkout.init();
							}
						}
					}
				}
			});		
		},
		updateItemCount: function(productVariationID, update) {
			new Ajax.Request('/utilities/ajax.asp?action=UpdateOrderProductQuantity', {
				parameters: {
					productVariationID: productVariationID,
					update: update
				},
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We were unable to update your cart - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						catalogue.cart.updateTotal();
						catalogue.cart.draw();
						$('header').appendChild(Builder.node('div', {id:'cartAlert', className:'cartAlert', style:'display:none;'}, 'Your cart has been updated - click above to open.'));
						Effect.Appear('cartAlert', {duration:0.3});
						setTimeout("Effect.Fade('cartAlert', {duration:0.3});", 3000);
					}
				}
			});
		},
		updateTotal: function() {
			new Ajax.Request('/utilities/ajax.asp?action=SelectOrderTotal', {
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We're having difficulty working with your cart - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						$('cartTotal').firstChild.innerHTML = returnCurrency(request.responseText, '£');
					}
				}
			});
		},
		removeItem: function(productVariationID) {
			new Ajax.Request('/utilities/ajax.asp?action=DeleteOrderProductVariation', {
				parameters: {
					productVariationID: productVariationID
				},
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We're having difficulty working with your cart - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						catalogue.cart.updateTotal();
						catalogue.cart.draw();
						catalogue.checkout.draw();
//						$('cartItem' + productVariationID).parentElement.removeChild($('cartItem' + productVariationID));
					}
				}
			});
		},
		checkout: {
			init: 	function() {
				if ($('checkout')) {
					$('checkout').parentNode.removeChild($('checkout'));
				}
				if ($('logged_in') && $F('logged_in') == 'true') {
					$('header').appendChild(Builder.node('form', {id:'checkout', className:'popup', action:'https://www.paypal.com/cgi-bin/webscr', method:'post'}, [Builder.node('a', {id:'checkoutClose', className:'close'}, 'Close')]));
//					$('header').appendChild(Builder.node('form', {id:'checkout', className:'popup', action:'https://www.sandbox.paypal.com/cgi-bin/webscr', method:'post'}, [Builder.node('a', {id:'checkoutClose', className:'close'}, 'Close')]));
					$('checkoutClose').observe('click', catalogue.cart.checkout.close);
					catalogue.cart.checkout.drawOrderSummary();
				} else {
					$('header').appendChild(Builder.node('form', {id:'checkout', className:'popup', action:'https://www.paypal.com/cgi-bin/webscr', method:'post'}, [
//					$('header').appendChild(Builder.node('form', {id:'checkout', className:'popup', action:'https://www.sandbox.paypal.com/cgi-bin/webscr', method:'post'}, [
						Builder.node('a', {id:'checkoutClose', className:'close'}, 'Close'),
						Builder.node('div', {id:'existingCustomer', className:'existingCustomer'}, [
							Builder.node('h2', 'Shopped with us before?'),
							Builder.node('p', 'If you already have an account with us, please login.'),
							Builder.node('a', {id:'checkoutLogin'}, 'Login Now »'),
							Builder.node('form', {id:'checkoutLoginForm', style:'display:none'}, [
								Builder.node('ul', [
									Builder.node('li', [
										Builder.node('label', {htmlFor:'checkoutLoginEmail'}, 'Your email:'),
										Builder.node('input', {id:'checkoutLoginEmail', type:'text', name:'email', maxlength:'50', className:'required'})
									]),
									Builder.node('li', [
										Builder.node('label', {htmlFor:'checkoutLoginPassword'}, 'Your Password:'),
										Builder.node('input', {id:'checkoutLoginPassword', type:'password', name:'password', maxlength:'50', className:'required'})
									])
								]),
								Builder.node('input', {id:'checkoutLoginSubmit', type:'submit', className:'button', value:'Login'})
							]),
							Builder.node('div', {id:'PasswordRecovery'}, [
								Builder.node('p', 'If you have forgotten your account password, please use our password recovery facility.'),
								Builder.node('a', {id:'checkoutPasswordRecovery'}, 'Password Recovery Facility »'),
								Builder.node('form', {id:'checkoutPasswordRecoveryForm', style:'display:none'}, [
									Builder.node('p', 'Please enter your email address, and we will send you your password'),
									Builder.node('ul', [
										Builder.node('li', [
											Builder.node('label', {htmlFor:'checkoutPasswordRecoveryEmail'}, 'Your email:'),
											Builder.node('input', {id:'checkoutPasswordRecoveryEmail', type:'text', name:'email', maxlength:'50', className:'required'})
										])
									]),
									Builder.node('input', {id:'checkoutPasswordRecoverySubmit', type:'submit', className:'button', value:'Send'})
								])
							])
						]),
						Builder.node('div', {id:'newCustomer', className:'newCustomer'}, [
							Builder.node('h2', 'Shopping with us for the first time?'),
							Builder.node('p', 'If you don\'t have an acount with us, pleaes create one now.'),
							Builder.node('a', {id:'checkoutNewAccount'}, 'Create an Account »')
						]),
					]));
					$('newCustomer').appendChild(catalogue.user.registration.form());
					$('customerEmail').observe('blur', function() {catalogue.validate.field($('customerEmail'));});
					$('customerPassword').observe('blur', function() {catalogue.validate.field($('customerPassword'));});
					$('customerPassword2').observe('blur', function() {catalogue.validate.field($('customerPassword2'));});
					$('checkoutClose').observe('click', catalogue.cart.checkout.close);
					
					$('checkoutLogin').observe('click', function() {
						Effect.toggle('checkoutLoginForm', 'blind', { duration: 0.3 })
					});
					$('checkoutLoginSubmit').observe('click', catalogue.cart.checkout.login);
					$('checkoutPasswordRecovery').observe('click', function() {
						Effect.toggle('checkoutPasswordRecoveryForm', 'blind', { duration: 0.3 })
					});
					$('checkoutPasswordRecoverySubmit').observe('click', catalogue.user.recoverPassword);
					$('checkoutNewAccount').observe('click', function() {
						Effect.toggle('checkoutNewAccountForm', 'blind', { duration: 0.3 })
					});
					$('createNewAccountSubmit').observe('click', catalogue.user.registration.submit);
				}
			},
			close:  function() {
				Effect.Fade($('checkout'), { duration: 0.3 });
				if ($('checkoutLoginForm')) {Effect.BlindUp($('checkoutLoginForm'), { duration: 0.3 })};
				if ($('checkoutPasswordRecoveryForm')) {Effect.BlindUp($('checkoutPasswordRecoveryForm'), { duration: 0.3 })};
				if ($('checkoutNewAccountForm')) {Effect.BlindUp($('checkoutNewAccountForm'), { duration: 0.3 })};
				setTimeout('if ($("checkout")) {$("checkout").parentNode.removeChild($("checkout"));}', 500);
			},
			login: function(e) {
				Event.stop(e);
				new Ajax.Request('/utilities/ajax.asp?action=login', {
					parameters: {
						email: $F('checkoutLoginEmail'),
						password: $F('checkoutLoginPassword')
					},
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We were unable to log you in - why not give us a call?";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var json = eval('(' + request.responseText + ');');
								if (json.records) {catalogue.cart.user = json.records[0];}
								// Need to do regular login stuff, and then send the UserID back to server to test if admin, and act accordingly
								Effect.Fade($('loginPopup'), {duration:0.5});
								var div = Builder.node('div', {id:'memberFunctions', style:'display:none'}, [
									Builder.node('ul', [
										Builder.node('li', [
											Builder.node('a', {id:'logoutButton'}, 'Logout')
										])
									])
								]);
								$('loginPopup').parentNode.insertBefore(div, $('loginPopup').parentNode.firstChild);
								$('logoutButton').observe('click', catalogue.user.logout);
								Effect.Appear($('memberFunctions'), {queue:'end'});
								document.body.appendChild(Builder.node('input', {type:'hidden', id:'logged_in', value:'true'}));
								$('existingCustomer').parentNode.removeChild($('existingCustomer'));
								$('newCustomer').parentNode.removeChild($('newCustomer'));
								catalogue.cart.checkout.drawOrderSummary();
							} else {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "We couldn't match your details to any of our accounts - do you need to register?.";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							}
						}
					},
					onFailure: function() {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We were unable to log you in - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					}
				});
			},
			drawOrderSummary: function() {
				$('checkout').appendChild(Builder.node('div', {className:'existingCustomer'}, [
					Builder.node('h2', 'Checkout'),
				]));
				$('checkout').appendChild(Builder.node('p', 'Thank you.  Please confirm your order and continue to PayPal.'));
				catalogue.cart.checkout.listProducts();
			},
			listProducts: function() {
				var weight = 0;
				var table = Builder.node('table');
				table.appendChild(
					Builder.node('thead', [
						Builder.node('tr', [
							Builder.node('td', {className:'name'}, 'Item'),
							Builder.node('td', 'Unit Price'),
							Builder.node('td', 'Quantity'),
							Builder.node('td', 'Subtotal'),
							Builder.node('td', 'Tax'),
							Builder.node('td', 'Total'),
							Builder.node('td')
						])
					])
				);
				var tbody = Builder.node('tbody');
				$A(catalogue.cart.products).each(function(product) {
					weight += product.quantity * product.weight;
					var item = Builder.node('tr', {id:'cartItem' + product.VariationID}, [
						Builder.node('td', product.shortTitle),
						Builder.node('td', returnCurrency(product.unitPrice)),
						Builder.node('td', [
							Builder.node('input', {id:'quantity' + product.VariationID, value:product.quantity}),
							Builder.node('a', {className:'update'}, 'Update'),
						]),
						Builder.node('td', returnCurrency(product.quantity * product.unitPrice, '£')),
						Builder.node('td', returnCurrency(product.quantity * product.unitPrice * 0.175, '£')),
						Builder.node('td', returnCurrency(product.quantity * product.unitPrice * 1.175, '£')),
						Builder.node('td', [
							Builder.node('a', {id:'checkoutDelete' + product.VariationID, className:'delete'}, 'Delete')
						])
					]);
					if (product.variationValues) {
						var variations = Builder.node('small');
						$A(product.variationValues).each(function (variationValue) {
							variations.innerHTML = variations.innerHTML + variationValue.ValueName + ", ";
						});
						variations.innerHTML = variations.innerHTML.substring(0, variations.innerHTML.length-2);
						item.firstChild.appendChild(variations);
					}
					tbody.appendChild(item);
				});
				
				var shippingFee = weight * 0.6;
					shippingFee = (shippingFee < 10)? 10 : shippingFee;
				var shipping = Builder.node('tr', {className:'shipping'}, [
					Builder.node('td', 'Shipping'),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', returnCurrency(shippingFee, '£')),
					Builder.node('td', '')
				]);
				var total = Builder.node('tr', {className:'total'}, [
					Builder.node('td', 'Grand Total'),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', ''),
					Builder.node('td', returnCurrency((catalogue.cart.total  * 1.175) + shippingFee, '£')),
					Builder.node('td', '')
				]);
				tbody.appendChild(shipping);
				tbody.appendChild(total);
				table.appendChild(tbody);
				$('checkout').appendChild(table);
				$A(catalogue.cart.products).each(function(product) {
					$('quantity' + product.VariationID).observe('change', function() {
						if (this.value < 0) {
							var update = product.quantity-1;
						} else {
							var update = this.value - product.quantity;
						}
						catalogue.cart.updateItemCount(product.VariationID, update);
					});
					$('checkoutDelete' + product.VariationID).observe('click', function() {
						catalogue.cart.removeItem(product.VariationID);
					});
				});
				$('checkout').appendChild(Builder.node('a', {id:'paypalBtn'}, 'Proceed to PayPal »'));
				$('checkout').appendChild(Builder.node('p', {className:'footer'}, [
					'All orders are processed securely by ',
					Builder.node('strong', 'PayPal'),
					' using 256 bit, high grade SSL encryption certified by ',
					Builder.node('strong', 'Verisign'),
					' to ensure your privacy and security.'
				]));
				
				$('paypalBtn').observe('click', catalogue.cart.checkout.submit);
			},
			submit: function(e) {
				new Ajax.Request('/utilities/ajax.asp?action=SelectUserById', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "We were unable to get your personal details automatically - please complete the checkout form.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var user = eval('(' + request.responseText + ');').records[0];
								catalogue.cart.user = user;
							}
						}
					}
				});
				$('checkout').appendChild(Builder.node('div', [
					Builder.node('input', {type:'hidden', name:'cmd', value:'_cart'}),
					Builder.node('input', {type:'hidden', name:'upload', value:'1'}),
					Builder.node('input', {type:'hidden', name:'business', value:'scottpaints@aol.com'}),
					Builder.node('input', {type:'hidden', name:'currency_code', value:'GBP'}),
					Builder.node('input', {type:'hidden', name:'cancel_return', value:'http://www.scottpaints.co.uk/contact.asp'}),
					Builder.node('input', {type:'hidden', name:'return', value:'http://www.scottpaints.co.uk/thankyou.asp'}),
					Builder.node('input', {type:'hidden', name:'rm', value:'2'}),	// to get the data back to the above success page
					
					Builder.node('input', {type:'hidden', name:'first_name', value:catalogue.validate.string(catalogue.cart.user.name)}),
					Builder.node('input', {type:'hidden', name:'last_name', value:catalogue.validate.string(catalogue.cart.user.name)}),
					Builder.node('input', {type:'hidden', name:'email', value:catalogue.validate.string(catalogue.cart.user.email)}),
					Builder.node('input', {type:'hidden', name:'address1', value:catalogue.validate.string(catalogue.cart.user.shippingStreet)}),
					Builder.node('input', {type:'hidden', name:'city', value:catalogue.validate.string(catalogue.cart.user.shippingCity)}),
					Builder.node('input', {type:'hidden', name:'zip', value:catalogue.validate.string(catalogue.cart.user.shippingPostalCode)}),
					Builder.node('input', {type:'hidden', name:'country', value:catalogue.validate.string(catalogue.cart.user.shippingCountry)})
				]));
//				var shippingFee = 0;
				var weight = 0;
				var shippingDiv = Builder.node('div');
				$A(catalogue.cart.products).each(function(product, index) {
					var num = index+1;
					
					$('checkout').appendChild(Builder.node('div', [
						Builder.node('input', {type:'hidden', name:'item_number_' + num, value:product.id}),
						Builder.node('input', {type:'hidden', name:'item_name_' + num, value:product.shortTitle}),
						Builder.node('input', {type:'hidden', name:'amount_' + num, value:product.unitPrice}),
						Builder.node('input', {type:'hidden', name:'quantity_' + num, value:product.quantity}),
						Builder.node('input', {type:'hidden', name:'tax_' + num, value:Math.round((product.unitPrice * 0.175)*100)/100}),
					]));
					
					shippingDiv.appendChild(Builder.node('input', {type:'hidden', name:'shipping_' + num, value:Math.round((product.weight * 0.6)*100)/100}));
					shippingDiv.appendChild(Builder.node('input', {type:'hidden', name:'shipping2_' + num, value:Math.round((product.weight * 0.6)*100)/100}));
					
//					shippingFee += Math.round((product.weight * 0.6)*100)/100;
					weight += product.weight*product.quantity;
					if (product.variationValues) {
						var variationsStr = "";
						$A(product.variationValues).each(function (variationValue, count) {
							variationsStr += variationValue.VariationName + ': ' + variationValue.ValueName + ' | ';
						});
						$('checkout').appendChild(Builder.node('input', {type:'hidden', name:'on0_'+num, value:'Options'}));
						$('checkout').appendChild(Builder.node('input', {type:'hidden', name:'os0_'+num, value:variationsStr}));
					}
				});
//				if (shippingFee < 10) {
				if ((weight*0.6) < 10) {
					$('checkout').appendChild(Builder.node('input', {type:'hidden', name:'handling_cart', value:'10.00'}));
//					$('checkout').appendChild(Builder.node('input', {type:'hidden', name:'shipping2', value:'5.00'}));
				} else {
					$('checkout').appendChild(shippingDiv);
				}
				$('checkout').submit();
			}
		}
	},
	
	submitContactForm: function(e) {
		Event.stop(e);
		if (catalogue.validate.form($('contactForm'))) {
			$('contactForm').appendChild(Builder.node('img', {id:'loader', src:'/images/interstitial_loading.gif'}));
			if (catalogue.validate.form($('contactForm'))) {
				new Ajax.Request('/utilities/ajax.asp?action=SendContactForm', {
					parameters: {
						name: escape($F('contactName')),
						emailAddress: escape($F('contactEmail')),
						phone: escape($F('contactPhone')),
						message: escape($F('contactMessage'))
					},
					onSuccess: function (request) {
						$('loader').remove();
						$('content').appendChild(Builder.node('p', 'Thank you, your message has been sent, and we shall get back to you shortly.'));
					},
					onFailure: function(request) {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "We were unable to send your message at this time - why not give us a call?";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					}
				});
			}
		}
	},
	
	search:{
		init:function(e) {
			Event.stop(e);
			if ($('SERP')) {
				var SERP = $('SERP');
				if (results = SERP.getElementsByTagName('ul')[0]) {
					results.remove();
				} else {
					SERP.getElementsByTagName('p')[1].remove();
				}
			} else {
				var SERP = Builder.node('div', {id:'SERP', className:'popup'}, [
					Builder.node('a', {id:'SERPClose', className:'close'}, 'Close'),
					Builder.node('h5', 'Search Results'),
					Builder.node('p', 'Please select from the following search results:'),
				]);
			}
			SERP.appendChild(Builder.node('p', {id:'SERPloader'}, [
				Builder.node('img', {src:'/images/interstitial_loading.gif'})
			]));
			var query = $F('search');
			if (query.indexOf(' ') != -1) {
				if (query.charAt(0) != '"') query = '"' + query;
				if (query.charAt(query.length-1) != '"') query = query + '"';
			}
			new Ajax.Request('/utilities/ajax.asp?action=Search', {
				parameters: {
					query: escape(query)
				},
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "Our apologies, we couldn't complete your search - why not give us a call, and we can help you in person.";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						if (request.responseText) {
							var results = eval('(' + request.responseText + ');');
							if (results = results.records) {
								var ul = Builder.node('ul', {className:'productList'});
								$A(results).each(function(item, index) {
									if ( (index == 0) || ((index > 0) && (item.shortTitle != results[index-1].shortTitle)) ) {
										ul.appendChild(Builder.node('li', [
//											Builder.node('img', {src:'/pictures/' + item.id + '-thumb.jpg'}),
											Builder.node('a', {href:'/' + item.url + '/', title:item.shortTitle}, item.longTitle)
										]));
									}
								});
								SERP.appendChild(ul);
								$A($('SERP').getElementsByTagName('img')).each(function(img) {
									$(img).observe('click', function() {
										catalogue.imgZoom.init(this);
									});
								});
							} else {
								var noResults = true;
							}
						} else {
							var noResults = true;
						}
					}
					if (noResults) {
						var message = Builder.node('div', [
							Builder.node('p', 'We were unable to find any matches for your search - please refine your search or give us a call.'),
						]);
						SERP.appendChild(message);
					}
					$('SERPloader').remove();
				}
			});
			$('container').appendChild(SERP);
			$('SERPClose').observe('click', catalogue.search.close);
		},
		close: function() {
			catalogue.fadeDestroy(['SERP'], 0.3);

		}
	},
	
	product: {
		relatedProducts: [],
		categories: [],
		variations: [],
		suppliers: [],
		pictures:[],
		
		populate: function() {
			new Ajax.Request('/utilities/ajax.asp?action=SelectProductById', {
				asynchronous: false,
				parameters: 'id=' + this.id,
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						if (request.responseText) {
							var product = eval('(' + request.responseText + ');');
							if (product = product.records[0]) {
								catalogue.product.code = product.code;
								catalogue.product.supplierID = product.supplierID;
								catalogue.product.url = product.url;
								catalogue.product.seoTitle = product.seoTitle;
								catalogue.product.seoDesc = product.seoDesc;
								catalogue.product.seoKeywords = product.seoKeywords;
								catalogue.product.longTitle = product.longTitle;
								catalogue.product.shortTitle = product.shortTitle;
								catalogue.product.description = product.description;
								catalogue.product.relatedProducts = (product.relatedProducts) ? product.relatedProducts: [];
								catalogue.product.categories = (product.categories) ? product.categories : [];
								catalogue.product.variations = (product.variations) ? product.variations : [];
							}
						}
					}
				}
			});
		},
		dePopulate:function() {
			catalogue.product.id = null;
			catalogue.product.code = null;
			catalogue.product.url = null;
			catalogue.product.seoTitle = null;
			catalogue.product.seoDesc = null;
			catalogue.product.seoKeywords = null;
			catalogue.product.longTitle = null;
			catalogue.product.shortTitle = null;
			catalogue.product.description = null;
			catalogue.product.relatedProducts = [];
			catalogue.product.categories = [];
			catalogue.product.variations = [];
			catalogue.product.pictures = [];
		},
		deleteMe: function() {
			new Ajax.Request('/utilities/ajax.asp?action=DeleteProduct', {
				parameters:'productID=' + catalogue.product.id,
				onSuccess: function (request) {
					tinyMCE.execCommand('mceRemoveControl', false, 'productDescription');
					catalogue.product.editForm.close();
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "Thank you - we have successfully removed this product.";
						myAlert.type = 'confirmation';
						myAlert.show();
						myAlert.hide(4000);
				},
				onFailure: function(request) {
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
						myAlert.type = 'error';
						myAlert.show();
						myAlert.hide(4000);
				}
			});
		},
		editForm: {
			products: [],
			categories: [],
			variations: [],
			productVariations: [],
			productPictures: [],
			
			init: function() {
				catalogue.toggleLoader('on');
				catalogue.hideEditButtons();
				new Ajax.Request('/utilities/ajax.asp?action=SelectProducts', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var products = eval('(' + request.responseText + ');');
								catalogue.product.editForm.products = products.records;
							}
						}
					}
				});
				new Ajax.Request('/utilities/ajax.asp?action=SelectCategoryNav', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var categories = eval('(' + request.responseText + ');');
								catalogue.product.editForm.categories = categories.records;
							}
						}
					}
				});
				new Ajax.Request('/utilities/ajax.asp?action=SelectVariations', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var variations = eval('(' + request.responseText + ')');
								catalogue.product.editForm.variations = variations.records;
							}
						}
					}
				});
				new Ajax.Request('/utilities/ajax.asp?action=SelectSuppliers', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var suppliers = eval('(' + request.responseText + ');');
								catalogue.product.editForm.suppliers = suppliers.records;
							}
						}
					}
				});
				var productManagementInterface = Builder.node('form', {id:'productManagement', className:'interface', style:'display:none'}, [
					Builder.node('a', {id:'productManagementClose', className:'close'}, 'Close'),
					Builder.node('h1', 'Product Management:'),
					Builder.node('p', 'Please complete the form below:'),
					Builder.node('p', [
						Builder.node('a', {id:'deleteProduct'}, 'Delete'),
					]),
					Builder.node('ul', [
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productURL'}, 'URL:'),
							Builder.node('input', {id:'productURL', type:'text', name:'url', maxlength:'50', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productSEOTitle'}, 'SEO Title:'),
							Builder.node('input', {id:'productSEOTitle', type:'text', name:'seoTitle', maxlength:'80', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productSEODesc'}, 'SEO Description:'),
							Builder.node('input', {id:'productSEODesc', type:'text', name:'seoDesc', maxlength:'180'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productSEOKeywords'}, 'SEO Keywords:'),
							Builder.node('input', {id:'productSEOKeywords', type:'text', name:'seoKeywords', maxlength:'180'})
						]),
//						Builder.node('li', [
//							Builder.node('label', {htmlFor:'productCode'}, 'Code:'),
//							Builder.node('input', {id:'productCode', type:'text', name:'code', maxlength:'20', className:'required'})
//						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productSuppliers'}, 'Supplier:'),
							Builder.node('select', {id:'productSuppliers', name:'suppliers'}, [
								Builder.node('option', 'Suppliers...')
							]),
							Builder.node('input', {id:'newSupplier', name:'newSupplier', className:'newValue', maxlength:'30'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productShortTitle'}, 'Gallery Title:'),
							Builder.node('input', {id:'productShortTitle', type:'text', name:'shortTitle', maxlength:'30', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'productLongTitle'}, 'Page Title:'),
							Builder.node('input', {id:'productLongTitle', type:'text', name:'longTitle', maxlength:'120', className:'required'})
						]),
						Builder.node('li', {className:'tinyMCE'}, [
							Builder.node('label', {htmlFor:'productDescription'}, 'Description:'),
							Builder.node('textarea', {id:'productDescription', name:'description', maxlength:'5000'})
						]),
						Builder.node('li', [
							Builder.node('input', {id:'productID', type:'hidden', name:'productID'})
						]),
						Builder.node('li', {className:'col first'}, [
							Builder.node('label', {htmlFor:'productCategories'}, 'Categories:'),
							Builder.node('select', {id:'productCategories', name:'categories', className:'multiple', multiple:true}),
							Builder.node('select', {id:'productPrimaryCategory', name:'primaryCategory'}, [
								Builder.node('option', 'Primary category...')
							])
						]),
						Builder.node('li', {className:'col'}, [
							Builder.node('label', {htmlFor:'relatedProducts'}, 'Related Products:'),
							Builder.node('select', {id:'relatedProducts', name:'relatedProducts', className:'multiple', multiple:true})
						]),
						Builder.node('li', [
							Builder.node('div', {id:'productVariations'})
						]),
						Builder.node('li', [
							Builder.node('div', {id:'newProductVariation'}, [
								Builder.node('h4', 'Add a New Variation'),
								Builder.node('ul', [
									Builder.node('li', {className:'col'}, [
										Builder.node('label', {htmlFor:'productVariationTypes'}, 'Variations:'),
										Builder.node('select', {id:'productVariationTypes', name:'variationTypes', className:'multiple', multiple:true}),
										Builder.node('input', {id:'newVariation', name:'newVariation', className:'newValue', maxlength:'20'})
									]),
									Builder.node('li', {className:'col'}, [
										Builder.node('ul', {id:'newVariationValues'}),
										Builder.node('ul', [
											Builder.node('li', [
												Builder.node('label', {htmlFor:'newProductVariationCode'}, 'Code:'),
												Builder.node('input', {id:'newProductVariationCode', name:'newProductVariationCode', maxlength:'10'})
											]),
											Builder.node('li', [
												Builder.node('label', {htmlFor:'newProductVariationUnitPrice'}, 'Unit Price:'),
												Builder.node('input', {id:'newProductVariationUnitPrice', name:'newProductVariationUnitPrice', maxlength:'10'})
											]),
											Builder.node('li', [
												Builder.node('label', {htmlFor:'newProductVariationWeight'}, 'Weight:'),
												Builder.node('input', {id:'newProductVariationWeight', name:'newProductVariationWeight', maxlength:'10'}),
											])
										]),
										Builder.node('input', {id:'addProductVariationBtn', className:'button', value:'Add Variation'})
									])
								])
							])
						])
					]),
					Builder.node('input', {id:'submit', type:'submit', className:'button', value:'Save'})
				]);
				$('container').appendChild(productManagementInterface);			
				
				// populate the suppliers, products, categories and variations selects
				$A(catalogue.product.editForm.suppliers).each(function(supplier) {
					var option = Builder.node('option', {value:supplier.id}, supplier.name);
					if (catalogue.product.supplierID && catalogue.product.supplierID == supplier.id) {
						option.selected = true;
					}
					$('productSuppliers').appendChild(option);
				});
				$A(catalogue.product.editForm.products).each(function(product) {
					if (product.id != catalogue.product.id) {
						var option = Builder.node('option', {value:product.id}, product.shortTitle);
						if (catalogue.product.relatedProducts) {
							$A(catalogue.product.relatedProducts).each(function(relatedProduct) {
								if (product.id == relatedProduct.id) {
									option.selected = 'selected';
								}
							});
						}
						$('relatedProducts').appendChild(option);
					}
				});
				$A(catalogue.product.editForm.categories).each(function(category) {
					var string = "";
					for (var i = 1, j=category.NodeLevel; i < j; i++) {
						string += "   ";
					}
					var option = Builder.node('option', {value:category.id}, string + category.linkText);	// makes all options selected in Firefox
					var optionPrimary = Builder.node('option', {value:category.id}, category.linkText);	// makes all options selected in Firefox
					if (catalogue.product.categories) {
						$A(catalogue.product.categories).each(function(productCategory) {
							if (category.id == productCategory.id) {
								option.selected = true;
								if (productCategory.primary == 'true') {
									optionPrimary.selected = true;
								}
								$('productPrimaryCategory').appendChild(optionPrimary);
							}
						});
					}
					$('productCategories').appendChild(option);
				});
				$A(catalogue.product.editForm.variations).each(function(variation) {
					var option = Builder.node('option', {value:variation.id}, variation.name);
					if (catalogue.product.variations[0]) {
						if (catalogue.product.variations[0].values) {
							$A(catalogue.product.variations[0].values).each(function(variationValue) {
								if (variation.id == variationValue.VariationID) {
									option.selected = true;
									catalogue.product.editForm.drawNewVariationValue(variation)								
								}
							});
						}
					}
					$('productVariationTypes').appendChild(option);
				});
				
				// Behaviours
				$('productManagementClose').observe('click', function() {catalogue.product.editForm.close(0.3)});
				$('deleteProduct').observe('click', catalogue.product.deleteMe);
				if ($('productURL')) {$('productURL').observe('blur', function() {
					catalogue.product.editForm.autocomplete();
					catalogue.validate.field($('productURL'));
				});}
				$('productSEOTitle').observe('blur', function() {catalogue.validate.field($('productSEOTitle'));});
				$('productSEODesc').observe('blur', function() {catalogue.validate.field($('productSEODesc'));});
				$('productSEOKeywords').observe('blur', function() {catalogue.validate.field($('productSEOKeywords'));});
				$('newSupplier').observe('blur', catalogue.product.editForm.addSupplier);
//				$('productCode').observe('blur', function() {catalogue.validate.field($('productCode'));});
				$('productShortTitle').observe('blur', function() {catalogue.validate.field($('productShortTitle'));});
				$('productLongTitle').observe('blur', function() {catalogue.validate.field($('productLongTitle'));});
				$('productDescription').observe('blur', function() {catalogue.validate.field($('productDescription'));});
//				$('addVariation').observe('click', function() {catalogue.product.editForm.addProductVariation(catalogue.product.editForm.productVariations.length);});
//				$('productVariationTypes').observe('change', catalogue.product.editForm.redrawProductVariations);
				$('productCategories').observe('change', catalogue.product.editForm.redrawPrimaryCategorySelect);
				$('productVariationTypes').observe('change', catalogue.product.editForm.redrawNewVariationValues);
				$('newVariation').observe('blur', catalogue.product.editForm.addVariation);
				$('productManagement').observe('submit', catalogue.product.editForm.submit);
				$('addProductVariationBtn').observe('click', function() {
					catalogue.product.editForm.saveNewProductVariation();
					catalogue.product.editForm.listProductVariations();
				});
				catalogue.confirmExitBound = catalogue.confirmExit.bind(this);
				Event.observe(window, 'beforeunload', catalogue.confirmExitBound);
				
				// Populate
				catalogue.product.editForm.populate();
				tinyMCE.execCommand('mceAddControl', false, 'productDescription');
				Effect.Appear($('productManagement'), { duration: 0.3 });
				catalogue.toggleLoader('off');
			},
			populate: function() {
//				$('productCode').value = (catalogue.product.code) ? catalogue.product.code : '';
				if (catalogue.product.url) {
					$('productURL').parentNode.appendChild(Builder.node('span', {id:'productURL'}, catalogue.product.url));
					$('productURL').parentNode.removeChild($('productURL'));
				}
				$('productSEOTitle').value = (catalogue.product.seoTitle) ? catalogue.product.seoTitle : '';
				$('productSEODesc').value = (catalogue.product.seoDesc) ? catalogue.product.seoDesc : '';
				$('productSEOKeywords').value = (catalogue.product.seoKeywords) ? catalogue.product.seoKeywords : '';
				$('productLongTitle').value = (catalogue.product.longTitle) ? catalogue.product.longTitle : '';
				$('productShortTitle').value = (catalogue.product.shortTitle) ? catalogue.product.shortTitle : '';
				$('productDescription').value = (catalogue.product.description) ? unescape(catalogue.product.description) : '';
				$('productID').value = (catalogue.product.id) ? catalogue.product.id : '';
				catalogue.product.editForm.listProductVariations();
			},
			listProductVariations: function (productVariationArrayPos) {
				$('productVariations').innerHTML = "";
				$('productVariations').appendChild(Builder.node('table', [
					Builder.node('thead', [
						Builder.node('tr', [
							Builder.node('td', 'Product Variation'),
							Builder.node('td', 'Code'),
							Builder.node('td', 'Unit Price'),
							Builder.node('td', 'Weight'),
							Builder.node('td', 'Available'),
							Builder.node('td')
						])
					]),
					Builder.node('tbody', {id:'productVariationsTBody'})
				]));
			
				if (catalogue.product.variations) {
					catalogue.product.editForm.productVariations = catalogue.product.variations;
					$A(catalogue.product.variations).each(function(variation, index) {
						if (variation && variation != "null") {
							// collate values into a string
							var variationValues = "";
							if (variation.values) {
								$A(variation.values).each(function(value) {
									variationValues += value.ValueName + ', ';
								});
							}
							variationValues = variationValues.substring(0, variationValues.length-2);
							
							// Creation
							$('productVariationsTBody').appendChild(Builder.node('tr', {id:'productVariationRow' + index}, [
								Builder.node('td', variationValues),
								Builder.node('td', [
									Builder.node('input', {id:'productVariation'+index+'code', name:'variation'+index+'code'})
								]),
								Builder.node('td', [
									Builder.node('input', {id:'productVariation'+index+'cost', name:'variation'+index+'cost'})
								]),
								Builder.node('td', [
									Builder.node('input', {id:'productVariation'+index+'weight', name:'variation'+index+'weight'})
								]),
								Builder.node('td', [
									Builder.node('input', {type:'checkbox', className:'checkbox', id:'productVariation'+index+'available', name:'variation'+index+'available'})
								]),
								Builder.node('td', [
									Builder.node('a', {className:'delete', id:'productVariation'+index+'delete', name:'variation'+index+'delete'}, 'Delete')
								])
							]));
										
							// Behaviour
							$('productVariation'+index+'code').observe('blur', function(e) {
								var elem = (e.srcElement) ? e.srcElement : e.target;
								var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('code'));	
								catalogue.product.editForm.productVariations[productVariationArrayPos].code = elem.value;
							}.bind(this));
							$('productVariation'+index+'cost').observe('blur', function(e) {
								var elem = (e.srcElement) ? e.srcElement : e.target;
								var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('cost'));	
								catalogue.product.editForm.productVariations[productVariationArrayPos].unitPrice = elem.value;
							}.bind(this));
							$('productVariation'+index+'weight').observe('blur', function(e) {
								var elem = (e.srcElement) ? e.srcElement : e.target;
								var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('weight'));	
								catalogue.product.editForm.productVariations[productVariationArrayPos].weight = elem.value;
							}.bind(this));
							$('productVariation'+index+'available').observe('blur', function(e) {
								var elem = (e.srcElement) ? e.srcElement : e.target;
								var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('available'));	
								catalogue.product.editForm.productVariations[productVariationArrayPos].available = elem.checked;
							}.bind(this));
							$('productVariation'+index+'delete').observe('click', function(e) {
								var elem = (e.srcElement) ? e.srcElement : e.target;
								var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('delete'));	
								catalogue.product.editForm.productVariations[productVariationArrayPos] = "null";
//								catalogue.product.editForm.productVariations.splice(productVariationArrayPos, 1);
								$('productVariationRow' + index).remove();
							}.bind(this));
							
							// Population
							$('productVariation'+index+'code').value = (variation.code && variation.code != 'null') ? variation.code : '';
							$('productVariation'+index+'cost').value = variation.unitPrice ? returnCurrency(variation.unitPrice) : '';
							$('productVariation'+index+'weight').value = (variation.weight && variation.weight != 'null') ? variation.weight : '';
							$('productVariation'+index+'available').checked = (variation.available == "true") ? true: false;
						}
					});
				}
			},
			saveNewProductVariation: function() {				
				var variation = {
					productID: catalogue.product.id,
					code: $F('newProductVariationCode'),
					unitPrice: $F('newProductVariationUnitPrice'),
					weight: $F('newProductVariationWeight'),
					available: 'true',
					values: []
				}
				var selects = $('newVariationValues').getElementsByTagName('select');
				$A(selects).each(function(select) {
					var value = {
						VariationID: select.id.substring(select.id.indexOf('variationType') + 'variationType'.length, select.id.length), 
						ValueID: select.options[select.selectedIndex].value, 
						ValueName: select.options[select.selectedIndex].innerHTML
					}
					variation.values.push(value);
				});
				catalogue.product.editForm.productVariations.push(variation);
				catalogue.product.editForm.listProductVariations();
			},
			/* OLD ADD VARIATION SCRIPT
			addProductVariation: function(productVariationArrayPos) {
				$('productVariations').appendChild(Builder.node('div', {id:'productVariation'+productVariationArrayPos, className:'productVariation'}, [
					Builder.node('h4', ['Variation ' + (productVariationArrayPos + 1)]),
					Builder.node('ul', [
						Builder.node('li', [
							Builder.node('label', 'available: '),
							Builder.node('checkbox', {type:'checkbox', id:'productVariation'+productVariationArrayPos+'available', name:'variation'+productVariationArrayPos+'available'})
						]),
						Builder.node('li', [
							Builder.node('label', 'Cost: '),
							Builder.node('input', {id:'productVariation'+productVariationArrayPos+'cost', name:'variation'+productVariationArrayPos+'cost'})
						]),
						Builder.node('li', [
							Builder.node('label', 'Weight: '),
							Builder.node('input', {id:'productVariation'+productVariationArrayPos+'weight', name:'variation'+productVariationArrayPos+'weight'})
						])
					])
				]));
				
				if (catalogue.product.variations && catalogue.product.variations[productVariationArrayPos]) {
					cost = catalogue.product.variations[productVariationArrayPos].unitPrice;
					weight = catalogue.product.variations[productVariationArrayPos].weight;
					available = catalogue.product.variations[productVariationArrayPos].available;
					$('productVariation'+productVariationArrayPos+'cost').value = cost ? returnCurrency(cost) : '';
					$('productVariation'+productVariationArrayPos+'weight').value = (weight && weight != 'null') ? weight : '';
					$('productVariation'+productVariationArrayPos+'available').checked = (available) ? true: false;
				}
				$('productVariation'+productVariationArrayPos+'cost').observe('blur', function(e) {
					var elem = (e.srcElement) ? e.srcElement : e.target;
					var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('cost'));	
					catalogue.product.editForm.productVariations[productVariationArrayPos].unitPrice = elem.value;
				}.bind(this));
				$('productVariation'+productVariationArrayPos+'weight').observe('blur', function(e) {
					var elem = (e.srcElement) ? e.srcElement : e.target;
					var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('weight'));	
					catalogue.product.editForm.productVariations[productVariationArrayPos].weight = elem.value;
				}.bind(this));
				$('productVariation'+productVariationArrayPos+'available').observe('blur', function(e) {
					var elem = (e.srcElement) ? e.srcElement : e.target;
					var productVariationArrayPos = elem.id.substring(elem.id.indexOf('productVariation') + 'productVariation'.length, elem.id.indexOf('available'));	
					catalogue.product.editForm.productVariations[productVariationArrayPos].available = elem.checked;
				}.bind(this));

				// for each option in the variation types select (above in the form), if selected, draw a select
				for (var m=0, n=$('productVariationTypes').options.length; m < n; m++) {
					if ($('productVariationTypes').options[m].selected) {
						var variationID = $('productVariationTypes').options[m].value;
						$('productVariation'+productVariationArrayPos).appendChild(Builder.node('div', {id:'productVariation'+productVariationArrayPos+'variationType'+variationID+'div', className:'variationValues'}));
						$('productVariation'+productVariationArrayPos+'variationType'+variationID+'div').appendChild(Builder.node('select', {id:'productVariation'+productVariationArrayPos+'variationType'+variationID, className:'col'}));
						$('productVariation'+productVariationArrayPos+'variationType'+variationID).observe('change', function(e) {
							var select = (e.srcElement) ? e.srcElement : e.target;
							var productVariationArrayPos = select.id.substring(select.id.indexOf('productVariation') + 'productVariation'.length, select.id.indexOf('variationType'));
							var variationID = select.id.substring(select.id.indexOf('variationType') + 'variationType'.length, select.id.length);
							catalogue.product.editForm.updateProductVariationValues(productVariationArrayPos, variationID, select);
						}.bind(this));
						$('productVariation'+productVariationArrayPos+'variationType'+variationID+'div').appendChild(Builder.node('input', {id:'productVariation'+productVariationArrayPos+'variationType'+variationID+'newValue', className:'newValue'}));
						$('productVariation'+productVariationArrayPos+'variationType'+variationID+'newValue').observe('blur', function(e) {
							var input = (e.srcElement) ? e.srcElement : e.target;
							var select = $(input.id.substring(0, input.id.indexOf('newValue')));
							var productVariationArrayPos = select.id.substring(select.id.indexOf('productVariation') + 'productVariation'.length, select.id.indexOf('variationType'));
							var variationID = select.id.substring(select.id.indexOf('variationType') + 'variationType'.length, select.id.length);
							catalogue.product.editForm.addVariationValue(productVariationArrayPos, variationID, input, select);
						}.bind(this));
						// loop through the editForm's variations to find the right one, and for each of it's values, draw an option
						for (var p=0, q=catalogue.product.editForm.variations.length; p<q; p++) {
							if (catalogue.product.editForm.variations[p].id == $('productVariationTypes').options[m].value) {
								if (catalogue.product.editForm.variations[p].values) {
									$('productVariation'+productVariationArrayPos+'variationType'+variationID).appendChild(Builder.node('option', {}, catalogue.product.editForm.variations[p].name + '...'));
									for (var y=0, z=catalogue.product.editForm.variations[p].values.length; y<z; y++) {
										var option = Builder.node('option', {value:catalogue.product.editForm.variations[p].values[y].id}, catalogue.product.editForm.variations[p].values[y].name);
										// for each value in the value set of the productVariation, if it matches the value being drawn
										if (catalogue.product.variations[productVariationArrayPos]) {
											if (catalogue.product.variations[productVariationArrayPos].values) {
												for (var a = 0, b=catalogue.product.variations[productVariationArrayPos].values.length; a < b; a++) {
													// if the type matches
													if ( catalogue.product.variations[productVariationArrayPos].values[a].VariationID == catalogue.product.editForm.variations[p].id) {
														// if the value matches
														if (catalogue.product.editForm.variations[p].values[y].id == catalogue.product.variations[productVariationArrayPos].values[a].ValueID) {
															option.selected = 'selected';
														}
													}
												}
											}
										}
										$('productVariation'+productVariationArrayPos+'variationType'+variationID).appendChild(option);
									}
								}
							}
						}
					}
				}
				$('productVariation' + productVariationArrayPos).appendChild(Builder.node('a', {id:'productVariation' + productVariationArrayPos + 'Close', className:'close'}, 'Close'));
				$('productVariation' + productVariationArrayPos + 'Close').observe('click', function() {catalogue.product.editForm.removeProductVariation(productVariationArrayPos);});
				if (!catalogue.product.editForm.productVariations[productVariationArrayPos]) {
					var variation = {
						id: false,
						productID: catalogue.product.id,
						unitPrice: false,
						values: []
					}
					catalogue.product.editForm.productVariations.push(variation);
				}
			},
			*/
			/* OLD REDRAW PRODUCT VARIATIONS SCRIPT
			redrawProductVariations: function() {
				$('productVariations').innerHTML = "";
				for (var i=0, j=catalogue.product.editForm.productVariations.length; i < j; i++) {
					catalogue.product.editForm.addProductVariation(i);
				}
			},
			*/
			autocomplete: function() {
				var keyword = $F('productURL');
				if (keyword != "") {
					$('productSEOTitle').value = keyword  + ' | Scott Paints | Glasgow';
					$('productSEODesc').value = keyword + ' from Scott Paints, Scotland\'s leading authority on Paint, Coatings, Finishes and Paint Colour Matching.';
					$('productSEOKeywords').value = keyword.replace(/ /g, ',').toLowerCase() + ',paint,glasgow,scotland,uk';
					$('productLongTitle').value = keyword;
					$('productShortTitle').value = keyword;
				}
			},
			removeProductVariation: function(productVariationArrayPos) {
				$('productVariation' + productVariationArrayPos).parentNode.removeChild($('productVariation' + productVariationArrayPos));
				catalogue.product.editForm.productVariations.splice(productVariationArrayPos, 1);
				catalogue.product.editForm.redrawProductVariations();
			},
			drawNewVariationValue: function(variation) {
				$('newVariationValues').appendChild(Builder.node('li', [
					Builder.node('select', {id:'variationType'+variation.id}, [
						Builder.node('option', variation.name + '...')
					]),
					Builder.node('input', {id:'variationType'+variation.id+'newValue', className:'newValue'})
				]));
				
				
				$('variationType'+variation.id+'newValue').observe('blur', function(e) {
					var select = $(this.id.substring(0, this.id.indexOf('newValue')));
					var variationID = select.id.substring(select.id.indexOf('variationType') + 'variationType'.length, select.id.length);
					catalogue.product.editForm.addVariationValue(variationID, this, select);
				});
				$A(variation.values).each(function(variationValue2) {
					$('variationType'+variation.id).appendChild(Builder.node('option', {value:variationValue2.id}, variationValue2.name));
				});
			},
			redrawNewVariationValues: function() {
				$('newVariationValues').innerHTML = "";
				$A($('productVariationTypes').options).each(function(option) {
					if (option.selected) {
						var count = 0;
						while (option.value != catalogue.product.editForm.variations[count].id && count != catalogue.product.editForm.variations.length) {
							count++;
						}
						catalogue.product.editForm.drawNewVariationValue(catalogue.product.editForm.variations[count]);
					}
				});
				
			},
			redrawPrimaryCategorySelect: function() {
				$A($('productCategories').options).each(function (option) {
					if (option.selected) {
						var found = false;
						$A($('primaryCategory').options).each(function(primaryOption) {
							if (option.value == primaryOption.value) {
								found = true;
							}			
						});
						if (!found) {
							$('primaryCategory').appendChild(Builder.node('option', {value:option.value}, option.innerText));
							if ($('primaryCategory').options.length == 2) {	// 2, to include the label 'Primary Category...'
								$('primaryCategory').selectedIndex = 1;
							}
						}
					} else {
						$A($('primaryCategory').options).each(function(primaryOption) {
							if (option.value == primaryOption.value) {
								primaryOption.parentNode.removeChild(primaryOption);
							}			
						});
					}
				});
			},
			updateProductVariationValues: function(productVariationArrayPos, variationID, select) {
				// for each of this product variations' values, if it's type matches the this select's type, delete it
				if (catalogue.product.editForm.productVariations[productVariationArrayPos].values) {
					for (var i = 0, j = catalogue.product.editForm.productVariations[productVariationArrayPos].values.length; i < j; i++) {
						if (catalogue.product.editForm.productVariations[productVariationArrayPos].values[i].VariationID == variationID) {
							catalogue.product.editForm.productVariations[productVariationArrayPos].values.splice(i, 1);
							i--; j--;
						}
					}
				}
				// for each of this select's values, if it's selected, add it to this Variation's value set
				for (var i = 0, j = select.options.length; i < j; i++) {
					if (select.options[i].selected) {
						var value = {
							VariationID: variationID, 
							ValueID: select.options[i].value, 
							ValueName: select.options[i].innerHTML
						}
						if (!catalogue.product.editForm.productVariations[productVariationArrayPos].values) {
							catalogue.product.editForm.productVariations[productVariationArrayPos].values = [];
						}
						catalogue.product.editForm.productVariations[productVariationArrayPos].values.push(value);
					}
				}
			},
			finaliseProductVariations: function() {
				// for each select option, if it's not selected, search each productVariation Value and remove any matching the select option's value
				$A($('productVariationTypes').options).each(function(variationOption) {
					if (!variationOption.selected) {
						$A(catalogue.product.editForm.productVariations).each(function (productVariation) {
							if (productVariation && productVariation != "null") {
								$A(productVariation.values).each(function(value, i) {
									if (value.VariationID == variationOption.value) {
										productVariation.values.splice(i, 1);
									}
								});
							}
						});
					}
				});
			},
			addVariation: function() {
				if ($F('newVariation') != "") {
					for (var i = 0, j=$('productVariationTypes').options.length; i < j; i++) {
						if ($('productVariationTypes').options[i].innerHTML.toLowerCase() == $F('newVariation').toLowerCase()) {
							var exists = true;
						}
					}
					if (!exists) {
						new Ajax.Request('/utilities/ajax.asp?action=InsertVariation', {
							parameters:'variation=' + escape($F('newVariation')),
							onSuccess: function (request) {
								var variation = {
									id: request.responseText,
									name: $F('newVariation'),
									values: []
								}
								catalogue.product.editForm.variations.push(variation);
								var option = Builder.node('option', {value:variation.id}, variation.name);
								$('productVariationTypes').appendChild(option);
								$('newVariation').value = "";
							},
							onFailure: function(request) {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							}
						});
					} else {
						$A($('productVariationTypes').options).each(function (option, index) {
							if (option.innerHTML.toLowerCase() == $('newVariation').value.toLowerCase()) {
								$('productVariationTypes').options[i].selected = true;
							}
						});
						$('newVariation').value = "";
					}
				}
			},
			addSupplier: function() {
				var select = $('productSuppliers');
				var input = $('newSupplier');
				var newValue = $F('newSupplier');
				if (newValue != "") {
					for (var i = 0, j=select.options.length; i < j; i++) {
						if (select.options[i].innerHTML.toLowerCase() == newValue.toLowerCase()) {
							var exists = true;
						}
					}
					if (!exists) {
						new Ajax.Request('/utilities/ajax.asp?action=InsertSupplier', {
							parameters:'supplier=' + newValue,
							onSuccess: function (request) {
								var supplier = {
									id: request.responseText,
									name: newValue
								}
								catalogue.product.editForm.suppliers.push(supplier);
								var option = Builder.node('option', {value:supplier.id, selected:'selected'}, supplier.name);
								select.appendChild(option);
								input.value = "";
							},
							onFailure: function(request) {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							}
						});
					} else {
						$A(select.options).each(function (option, index) {
							if (option.innerHTML.toLowerCase() == newValue.toLowerCase()) {
								select.selectedIndex = index;
							}
						});
						input.value = "";
					}
				}
			},
			addVariationValue: function (variationID, input, select) {
				if (input.value != "") {
					for (var i = 0, j=select.options.length; i < j; i++) {
						if (select.options[i].innerHTML.toLowerCase() == input.value.toLowerCase()) {
							var exists = true;
						}
					}
					if (!exists) {
						new Ajax.Request('/utilities/ajax.asp?action=InsertVariationValue', {
							parameters:'variationID=' + variationID + '&valueName=' + escape(input.value),
							onSuccess: function (request) {
								var value={
									id: request.responseText,
									name: input.value
								}
								
								for (var i=0, j=catalogue.product.editForm.variations.length; i < j; i++) {
									if (catalogue.product.editForm.variations[i].id == variationID) {
										catalogue.product.editForm.variations[i].values.push(value);
										// add to productVariation
										value = {
											VariationID: variationID,
											VariationName: catalogue.product.editForm.variations[i].name,
											ValueID: value.id,
											ValueName: value.name
										}
//										catalogue.product.editForm.productVariations[productVariationArrayPos].values.push(value);
										break;
									}
								}
								select.appendChild(Builder.node('option', {value:value.ValueID, selected:'selected'}, value.ValueName));
								input.value = '';
								// redraw variations (to ensure option is in the list of other variations)
//								catalogue.product.editForm.redrawProductVariations();
							},
							onFailure: function(request) {
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
									myAlert.type = 'error';
									myAlert.show();
									myAlert.hide(4000);
							}
						});
					} else {
						$A($(select).options).each(function (option, index) {
							if (option.innerHTML.toLowerCase() == input.value.toLowerCase()) {
								select.selectedIndex = index;
							}
						});
						input.value = "";
					}
				}
			},
			close: function(duration) {
				catalogue.product.dePopulate();
				catalogue.fadeDestroy(['productManagement'], 0.3);
				catalogue.showEditButtons();
				Event.stopObserving(window, 'beforeunload', catalogue.confirmExitBound);
			},
			submit: function(e) {
				Event.stop(e);
				tinyMCE.triggerSave();
				if (catalogue.validate.form($('productManagement'))) {
					catalogue.toggleLoader('on', $('productManagement'));
					catalogue.product.editForm.finaliseProductVariations();
					var url = ($('productURL').value) ? $F('productURL') : $('productURL').innerHTML;
					var relatedProducts = "";
					$A($('relatedProducts').options).each(function(relatedProduct) {
						if (relatedProduct.selected) {
							relatedProducts += relatedProduct.value + '|';
						}
					});
					if (relatedProducts.length > 0) {
						relatedProducts = relatedProducts.substring(0, relatedProducts.length-'|'.length);
					}
					var categories = "";
					$A($('productCategories').options).each(function(category) {
						categories += category.value + '|' + ((category.selected) ? '1' : '0') + '||';
					});
					if (categories.length > 0) {
						categories = categories.substring(0, categories.length-2);
					}
					
					var variationsExist = false;
					$A(catalogue.product.editForm.productVariations).each(function(variation) {
						if (variation != "null") {
							variationsExist = true;
						}
					});
					if ( (catalogue.product.editForm.productVariations.length < 1) || (!variationsExist) ) {
						var errorMessage = Builder.node('p', {id:'variationError', className:'error'}, 'Please insert at least one variation, providing a price for the product.  No variables are required.');
						$('newProductVariation').parentNode.insertBefore(errorMessage, $('newProductVariation'));
						return false;
					} else {
						if ($('variationError')) {$('variationError').parentNode.removeChild($('variationError'))};
					}
//					$A(catalogue.product.editForm.productVariations).each (function (variation) {
//						if (variation.cost
//					});
					
					JSONstring.compactOutput = true;
					var productVariations = escape(JSONstring.make(catalogue.product.editForm.productVariations));

					new Ajax.Request('/utilities/ajax.asp?action=ManageProduct', {
						parameters: {
							code: '',
							supplierID: $F('productSuppliers'),
							url: url,
							seoTitle: escape($F('productSEOTitle')),
							seoDesc: escape($F('productSEODesc')),
							seoKeywords: escape($F('productSEOKeywords')),
							longTitle: escape($F('productlongTitle')),
							shortTitle: escape($F('productShortTitle')),
							description: escape($F('productDescription')),
							relatedProducts: relatedProducts,
							categories: categories,
							primaryCategory: $('primaryCategory').options[$('primaryCategory').selectedIndex].value,
							productVariationsJSON: productVariations,
							productID: ((catalogue.product.id) ? catalogue.product.id : null)
						},
						onSuccess: function (request) {
							if (request.responseText != "error") {
								if ($('productList')) {catalogue.drawProductList();}
								tinyMCE.execCommand('mceRemoveControl', false, 'productDescription');
								catalogue.product.editForm.close();
								catalogue.toggleLoader('off', $('productManagement'));
								var myAlert = catalogue.alerts.newAlert();
									myAlert.message = "Thank you - your product has been successfully saved.";
									myAlert.type = "confirmation";
									myAlert.show();
									myAlert.hide(4000);
							} else {
								$('productManagement').appendChild(Builder.node('p', 'An error has occurred - an email has been sent to your technicians.'));
							}
						},
						onFailure: function(request) {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
				}
			}
		},
		isolateProductVariation: function() {
			// get the seleted Variation Values
			var selects = document.getElementsByTagName('select');
			var selectedVariationValues = []
			for (var i = 0, j = selects.length; i < j; i++) {
				if ((selects[i].id.indexOf('variation') != -1) && (selects[i].id.indexOf('productID' + catalogue.product.id) != -1)) {
					var variationValue = {
						VariationID: selects[i].id.substring(selects[i].id.indexOf('variation') + 'variation'.length, selects[i].id.length),
						ValueID: selects[i].options[selects[i].selectedIndex].value
					}
					selectedVariationValues.push(variationValue);
				}
			}
			
			// get the matching product variations
			var productVariationFound = false;
			var productVariationArrayPos = 0
			while (!productVariationFound && productVariationArrayPos != catalogue.product.variations.length) {
				// initialise the selectedVariations Array
				for (var i = 0, j = selectedVariationValues.length; i < j; i++) {
					selectedVariationValues[i].found = false;
				}
				// set the current productVariation
				var productVariation = catalogue.product.variations[productVariationArrayPos];
				
				// for each selectedVariationValue
				var selectedVariationValueFound = false;
				var selectedVariationValuesArrayPos = 0;
				while (!selectedVariationValueFound && selectedVariationValuesArrayPos != selectedVariationValues.length) {
					var selectedVariationValue = selectedVariationValues[selectedVariationValuesArrayPos];
					var valueArrayPos = 0;
					while (!selectedVariationValue.found && valueArrayPos != productVariation.values.length) {
						var value = productVariation.values[valueArrayPos];
						if ( (selectedVariationValue.VariationID == value.VariationID) && (selectedVariationValue.ValueID == value.ValueID) ) {
							selectedVariationValue.found = true;
						}
						valueArrayPos++;
					}
					selectedVariationValuesArrayPos++;
				}
				// test whether all are found or not
				productVariationFound = true;
				selectedVariationValuesArrayPos = 0;
				while(productVariationFound && selectedVariationValuesArrayPos != selectedVariationValues.length) {
					if (!selectedVariationValues[selectedVariationValuesArrayPos].found) {
						productVariationFound = false;
					}
					selectedVariationValuesArrayPos++;
				}
				
				productVariationArrayPos++;
			}
			productVariationArrayPos--;
			if (productVariationFound) {
				return catalogue.product.variations[productVariationArrayPos];
			} else {
				return null;
			}
		},
		setVariationPrice: function() {
			var productVariation = catalogue.product.isolateProductVariation();
			if (productVariation && (!(productVariation.available == 'false'))) {
				$('product' + catalogue.product.id + 'cost').innerHTML = returnCurrency(productVariation.unitPrice, '£');
				$('AddToCart' + catalogue.product.id).style.backgroundPosition = 'top';
				$('AddToCart' + catalogue.product.id).disabled = false;
			} else {
				$('product' + catalogue.product.id + 'cost').innerHTML = '-';
				$('AddToCart' + catalogue.product.id).style.backgroundPosition = 'bottom';
				$('AddToCart' + catalogue.product.id).disabled = true;
			}
//			$('product' + catalogue.product.id + 'cost').innerHTML = returnCurrency(catalogue.product.variations[productVariationArrayPos].unitPrice, '£');
		}
	},
	
	category: {
		id:null,
		pictures: [],
		
		populate: function() {
			new Ajax.Request('/utilities/ajax.asp?action=SelectCategoryById', {
				asynchronous: false,
				parameters: 'id=' + this.id,
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						if (request.responseText) {
							var category = eval('(' + request.responseText + ');');
							if (category = category.records[0]) {
								catalogue.category.url = category.url;
								catalogue.category.seoTitle = category.seoTitle;
								catalogue.category.seoDesc = category.seoDesc;
								catalogue.category.seoKeywords = category.seoKeywords;
								catalogue.category.pageTitle = category.pageTitle;
								catalogue.category.description = category.description;
								catalogue.category.linkText = category.linkText;
								catalogue.category.linkTitle = category.linkTitle;
							}
						}
					}
				}
			});
		},
		dePopulate:function() {
			catalogue.category.id = null;
			catalogue.category.url = null;
			catalogue.category.seoTitle = null;
			catalogue.category.seoDesc = null;
			catalogue.category.seoKeywords = null;
			catalogue.category.pageTitle = null;
			catalogue.category.description = null;
			catalogue.category.linkText = null;
			catalogue.category.linkTitle = null;
		},
		deleteMe: function() {
			new Ajax.Request('/utilities/ajax.asp?action=DeleteCategory', {
				parameters:'categoryID=' + catalogue.category.id,
				onSuccess: function (request) {
					tinyMCE.execCommand('mceRemoveControl', false, 'categoryDescription');
					catalogue.drawCategoryList(window.location.href);
					catalogue.category.editForm.close();
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "Thank you - we have successfully removed this category.";
						myAlert.type = 'confirmation';
						myAlert.show();
						myAlert.hide(4000);
				},
				onFailure: function(request) {
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
						myAlert.type = 'error';
						myAlert.show();
						myAlert.hide(4000);
				}
			});
		},
		editForm: {
			categories: [],
			init: function() {
				catalogue.toggleLoader('on');
				catalogue.hideEditButtons();
				new Ajax.Request('/utilities/ajax.asp?action=SelectCategoryNav', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var categories = eval('(' + request.responseText + ');');
								catalogue.category.editForm.categories = categories.records;
							}
						}
					}
				});
				
				var categoryManagementInterface = Builder.node('form', {id:'categoryManagement', className:'interface', style:'display:none'}, [
					Builder.node('a', {id:'categoryManagementClose', className:'close'}, 'Close'),
					Builder.node('h1', 'Category Management:'),
					Builder.node('p', 'Please complete the form below:'),
					Builder.node('p', [
						Builder.node('a', {id:'deleteProduct'}, 'Delete'),
					]),
					Builder.node('ul', [
						Builder.node('li', [
							Builder.node('label', {htmlFor:'parentCategory'}, 'Parent Category:'),
							Builder.node('select', {id:'parentCategory', name:'parentCategory'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categoryURL'}, 'URL:'),
							Builder.node('input', {id:'categoryURL', type:'text', name:'url', maxlength:'50', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categorySEOTitle'}, 'SEO Title:'),
							Builder.node('input', {id:'categorySEOTitle', type:'text', name:'seoTitle', maxlength:'80', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categorySEODesc'}, 'SEO Description:'),
							Builder.node('input', {id:'categorySEODesc', type:'text', name:'seoDesc', maxlength:'180'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categorySEOKeywords'}, 'SEO Keywords:'),
							Builder.node('input', {id:'categorySEOKeywords', type:'text', name:'seoKeywords', maxlength:'180'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categoryLinkText'}, 'Navigation Text:'),
							Builder.node('input', {id:'categoryLinkText', type:'text', name:'linkText', maxlength:'30', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categoryLinkTitle'}, 'Navigation Tip:'),
							Builder.node('input', {id:'categoryLinkTitle', type:'text', name:'linkTitle', maxlength:'50'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categoryPageTitle'}, 'Page Title:'),
							Builder.node('input', {id:'categoryPageTitle', type:'text', name:'pageTitle', maxlength:'120', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'categoryDescription'}, 'Description:'),
							Builder.node('textarea', {id:'categoryDescription', name:'description', maxlength:'5000'})
						]),
						Builder.node('li', [
							Builder.node('input', {id:'categoryID', type:'hidden', name:'categoryID'})
						]),
						Builder.node('li', [
							Builder.node('input', {id:'submit', type:'submit', className:'button', value:'Save'})
						]),
					])
				]);
				$('container').appendChild(categoryManagementInterface);
				$('parentCategory').appendChild(Builder.node('option', {value:0}, 'None'));
				$A(catalogue.category.editForm.categories).each(function(category) {
					var string = "";
					for (var i = 1, j=category.NodeLevel; i < j; i++) {
						string += "   ";
					}
					$('parentCategory').appendChild(Builder.node('option', {value: category.id}, string + category.linkText));
				});
				Effect.Appear($('categoryManagement'), { duration: 0.3 });
				catalogue.category.editForm.populate();
				tinyMCE.execCommand('mceAddControl', false, 'categoryDescription');
				$('categoryManagementClose').observe('click', function() {catalogue.category.editForm.close(0.3)});
				$('deleteProduct').observe('click', catalogue.category.deleteMe);
				if ($('parentCategory')) {$('parentCategory').observe('change', function() {catalogue.validate.field($('categoryURL'));});}
				if ($('categoryURL')) {$('categoryURL').observe('blur', function() {
					catalogue.category.editForm.autocomplete();
					catalogue.validate.field($('categoryURL'));
				});}
				$('categorySEOTitle').observe('blur', function() {catalogue.validate.field($('categorySEOTitle'));});
				$('categorySEODesc').observe('blur', function() {catalogue.validate.field($('categorySEODesc'));});
				$('categorySEOKeywords').observe('blur', function() {catalogue.validate.field($('categorySEOKeywords'));});
				$('categoryPageTitle').observe('blur', function() {catalogue.validate.field($('categoryPageTitle'));});
				$('categoryDescription').observe('blur', function() {catalogue.validate.field($('categoryDescription'));});
				$('categoryLinkText').observe('blur', function() {catalogue.validate.field($('categoryLinkText'));});
				$('categoryLinkTitle').observe('blur', function() {catalogue.validate.field($('categoryLinkTitle'));});
				$('categoryManagement').observe('submit', catalogue.category.editForm.submit);
				catalogue.confirmExitBound = catalogue.confirmExit.bind(this);
				Event.observe(window, 'beforeunload', catalogue.confirmExitBound);
				catalogue.toggleLoader('off');
			},
			populate: function() {
				if (catalogue.category.url) {
					$('categoryURL').parentNode.appendChild(Builder.node('span', {id:'categoryURL'}, catalogue.category.url));
					$('categoryURL').parentNode.removeChild($('categoryURL'));
					$('parentCategory').parentNode.parentNode.removeChild($('parentCategory').parentNode);
				}
				$('categorySEOTitle').value = (catalogue.category.seoTitle) ? catalogue.category.seoTitle : '';
				$('categorySEODesc').value = (catalogue.category.seoDesc) ? catalogue.category.seoDesc : '';
				$('categorySEOKeywords').value = (catalogue.category.seoKeywords) ? catalogue.category.seoKeywords : '';
				$('categoryPageTitle').value = (catalogue.category.pageTitle) ? catalogue.category.pageTitle : '';
				$('categoryDescription').value = (catalogue.category.description) ? unescape(catalogue.category.description) : '';
				$('categoryLinkText').value = (catalogue.category.linkText) ? catalogue.category.linkText : '';
				$('categoryLinkTitle').value = (catalogue.category.linkTitle) ? catalogue.category.linkTitle : '';
				$('categoryID').value = (catalogue.category.id) ? catalogue.category.id : '';
			},
			autocomplete: function() {
				var keyword = $F('categoryURL');
				if (keyword != "") {
					$('categorySEOTitle').value = keyword  + ' | Scott Paints | Glasgow';
					$('categorySEODesc').value = keyword + ' from Scott Paints, Scotland\'s leading authority on Paint, Coatings, Finishes and Paint Colour Matching.';
					$('categorySEOKeywords').value = keyword.replace(/ /g, ',').toLowerCase() + ',paint,glasgow,scotland,uk';
					$('categoryPageTitle').value = keyword;
					$('categoryLinkText').value = keyword;
					$('categoryLinkTitle').value = keyword + ' from Scott Paints';
				}
			},
			close: function(duration) {
				catalogue.category.dePopulate();
				catalogue.fadeDestroy(['categoryManagement'], 0.3);
				catalogue.showEditButtons();
				Event.stopObserving(window, 'beforeunload', catalogue.confirmExitBound);
			},
			submit: function(e) {
				Event.stop(e);
				tinyMCE.triggerSave();
				if (catalogue.validate.form($('categoryManagement'))) {
					var url = ($('categoryURL').value) ? $F('categoryURL') : $('categoryURL').innerHTML;
					var parentID = ($('parentCategory')) ? $F('parentCategory') : null;
					new Ajax.Request('/utilities/ajax.asp?action=ManageCategory', {
						parameters: {
							url: url,
							seoTitle: escape($F('categorySEOTitle')),
							seoDesc: escape($F('categorySEODesc')),
							seoKeywords: escape($F('categorySEOKeywords')),
							pageTitle: escape($F('categoryPageTitle')),
							description: escape($F('categoryDescription')),
							linkText: escape($F('categoryLinkText')),
							linkTitle: escape($F('categoryLinkTitle')),
							seoDesc: escape($F('categorySEODesc')),
							categoryID: catalogue.category.id,
							parentID: parentID
						},
						onSuccess: function (request) {
							tinyMCE.execCommand('mceRemoveControl', false, 'categoryDescription');
							catalogue.drawCategoryList(window.location.href);
							catalogue.category.editForm.close();
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "Thank you - your category has been successfully saved.";
								myAlert.type = 'confirmation';
								myAlert.show();
								myAlert.hide(4000);
						},
						onFailure: function(request) {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
				}
			}
		},
		updateProductRanking: function(productsSerial) {
			new Ajax.Request('/utilities/ajax.asp?action=UpdateProductCategoryRanking', {
				parameters: 'categoryID=' + $F('categoryID') + '&' + productsSerial,
				onFailure: function (request) {
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
						myAlert.type = 'error';
						myAlert.show();
						myAlert.hide(4000);
				}
			});
		}
	},

	page: {
		id:null,
		
		populate: function() {
			new Ajax.Request('/utilities/ajax.asp?action=SelectPageById', {
				asynchronous: false,
				parameters: 'id=' + this.id,
				onSuccess: function(request) {
					if (request.responseText == 'error') {
						var myAlert = catalogue.alerts.newAlert();
							myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
							myAlert.type = 'error';
							myAlert.show();
							myAlert.hide(4000);
					} else {
						if (request.responseText) {
							var page = eval('(' + request.responseText + ');');
							if (page = page.records[0]) {
								catalogue.page.url = page.url;
								catalogue.page.seoTitle = page.seoTitle;
								catalogue.page.seoDesc = page.seoDesc;
								catalogue.page.seoKeywords = page.seoKeywords;
								catalogue.page.pageTitle = page.pageTitle;
								catalogue.page.description = page.description;
								catalogue.page.linkText = page.linkText;
								catalogue.page.linkTitle = page.linkTitle;
							}
						}
					}
				}
			});
		},
		dePopulate:function() {
			catalogue.page.id = null;
			catalogue.page.url = null;
			catalogue.page.seoTitle = null;
			catalogue.page.seoDesc = null;
			catalogue.page.seoKeywords = null;
			catalogue.page.pageTitle = null;
			catalogue.page.description = null;
			catalogue.page.linkText = null;
			catalogue.page.linkTitle = null;
		},
		deleteMe: function() {
			new Ajax.Request('/utilities/ajax.asp?action=DeletePage', {
				parameters:'pageID=' + catalogue.page.id,
				onSuccess: function (request) {
					tinyMCE.execCommand('mceRemoveControl', false, 'pageDescription');
					catalogue.drawPageList(window.location.href);
					catalogue.page.editForm.close();
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "Thank you - we have successfully removed this page.";
						myAlert.type = 'confirmation';
						myAlert.show();
						myAlert.hide(4000);
				},
				onFailure: function(request) {
					var myAlert = catalogue.alerts.newAlert();
						myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
						myAlert.type = 'error';
						myAlert.show();
						myAlert.hide(4000);
				}
			});
		},
		editForm: {
			pages: [],
			init: function() {
				catalogue.toggleLoader('on');
				catalogue.hideEditButtons();
				new Ajax.Request('/utilities/ajax.asp?action=SelectPageNav', {
					asynchronous: false,
					onSuccess: function(request) {
						if (request.responseText == 'error') {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						} else {
							if (request.responseText) {
								var pages = eval('(' + request.responseText + ');');
								catalogue.page.editForm.pages = pages.records;
							}
						}
					}
				});
				
				var pageManagementInterface = Builder.node('form', {id:'pageManagement', className:'interface', style:'display:none'}, [
					Builder.node('a', {id:'pageManagementClose', className:'close'}, 'Close'),
					Builder.node('h1', 'Page Management:'),
					Builder.node('p', 'Please complete the form below:'),
					Builder.node('p', [
						Builder.node('a', {id:'deletePage'}, 'Delete'),
					]),
					Builder.node('ul', [
						Builder.node('li', [
							Builder.node('label', {htmlFor:'parentPage'}, 'Parent Page:'),
							Builder.node('select', {id:'parentPage', name:'parentPage'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageURL'}, 'URL:'),
							Builder.node('input', {id:'pageURL', type:'text', name:'url', maxlength:'50', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageSEOTitle'}, 'SEO Title:'),
							Builder.node('input', {id:'pageSEOTitle', type:'text', name:'seoTitle', maxlength:'80', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageSEODesc'}, 'SEO Description:'),
							Builder.node('input', {id:'pageSEODesc', type:'text', name:'seoDesc', maxlength:'180'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageSEOKeywords'}, 'SEO Keywords:'),
							Builder.node('input', {id:'pageSEOKeywords', type:'text', name:'seoKeywords', maxlength:'180'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageLinkText'}, 'Navigation Text:'),
							Builder.node('input', {id:'pageLinkText', type:'text', name:'linkText', maxlength:'30', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageLinkTitle'}, 'Navigation Tip:'),
							Builder.node('input', {id:'pageLinkTitle', type:'text', name:'linkTitle', maxlength:'50'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pagePageTitle'}, 'Page Title:'),
							Builder.node('input', {id:'pagePageTitle', type:'text', name:'pageTitle', maxlength:'120', className:'required'})
						]),
						Builder.node('li', [
							Builder.node('label', {htmlFor:'pageDescription'}, 'Description:'),
							Builder.node('textarea', {id:'pageDescription', name:'description', maxlength:'5000'})
						]),
						Builder.node('li', [
							Builder.node('input', {id:'pageID', type:'hidden', name:'pageID'})
						]),
						Builder.node('li', [
							Builder.node('input', {id:'submit', type:'submit', className:'button', value:'Save'})
						]),
					])
				]);
				$('container').appendChild(pageManagementInterface);
				$('parentPage').appendChild(Builder.node('option', {value:0}, 'None'));
				$A(catalogue.page.editForm.pages).each(function(page) {
					var string = "";
					for (var i = 1, j=page.NodeLevel; i < j; i++) {
						string += "   ";
					}
					$('parentPage').appendChild(Builder.node('option', {value: page.id}, string + page.linkText));
				});
				Effect.Appear($('pageManagement'), { duration: 0.3 });
				catalogue.page.editForm.populate();
				tinyMCE.execCommand('mceAddControl', false, 'pageDescription');
				$('pageManagementClose').observe('click', function() {catalogue.page.editForm.close(0.3)});
				$('deletePage').observe('click', catalogue.page.deleteMe);
				if ($('parentPage')) {$('parentPage').observe('change', function() {catalogue.validate.field($('pageURL'));});}
				if ($('pageURL')) {$('pageURL').observe('blur', function() {
					catalogue.page.editForm.autocomplete();
					catalogue.validate.field($('pageURL'));
				});}
				$('pageSEOTitle').observe('blur', function() {catalogue.validate.field($('pageSEOTitle'));});
				$('pageSEODesc').observe('blur', function() {catalogue.validate.field($('pageSEODesc'));});
				$('pageSEOKeywords').observe('blur', function() {catalogue.validate.field($('pageSEOKeywords'));});
				$('pagePageTitle').observe('blur', function() {catalogue.validate.field($('pagePageTitle'));});
				$('pageDescription').observe('blur', function() {catalogue.validate.field($('pageDescription'));});
				$('pageLinkText').observe('blur', function() {catalogue.validate.field($('pageLinkText'));});
				$('pageLinkTitle').observe('blur', function() {catalogue.validate.field($('pageLinkTitle'));});
				$('pageManagement').observe('submit', catalogue.page.editForm.submit);
				catalogue.confirmExitBound = catalogue.confirmExit.bind(this);
				Event.observe(window, 'beforeunload', catalogue.confirmExitBound);
				catalogue.toggleLoader('off');
			},
			populate: function() {
				if (catalogue.page.url) {
					$('pageURL').parentNode.appendChild(Builder.node('span', {id:'pageURL'}, catalogue.page.url));
					$('pageURL').parentNode.removeChild($('pageURL'));
					$('parentPage').parentNode.parentNode.removeChild($('parentPage').parentNode);
				}
				$('pageSEOTitle').value = (catalogue.page.seoTitle) ? catalogue.page.seoTitle : '';
				$('pageSEODesc').value = (catalogue.page.seoDesc) ? catalogue.page.seoDesc : '';
				$('pageSEOKeywords').value = (catalogue.page.seoKeywords) ? catalogue.page.seoKeywords : '';
				$('pagePageTitle').value = (catalogue.page.pageTitle) ? catalogue.page.pageTitle : '';
				$('pageDescription').value = (catalogue.page.description) ? unescape(catalogue.page.description) : '';
				$('pageLinkText').value = (catalogue.page.linkText) ? catalogue.page.linkText : '';
				$('pageLinkTitle').value = (catalogue.page.linkTitle) ? catalogue.page.linkTitle : '';
				$('pageID').value = (catalogue.page.id) ? catalogue.page.id : '';
			},
			autocomplete: function() {
				var keyword = $F('pageURL');
				if (keyword != "") {
					$('pageSEOTitle').value = keyword  + ' | Scott Paints | Glasgow';
					$('pageSEODesc').value = keyword + ' from Scott Paints, Scotland\'s leading authority on Paint, Coatings, Finishes and Paint Colour Matching.';
					$('pageSEOKeywords').value = keyword.replace(/ /g, ',').toLowerCase() + ',paint,glasgow,scotland,uk';
					$('pagePageTitle').value = keyword;
					$('pageLinkText').value = keyword;
					$('pageLinkTitle').value = keyword + ' from Scott Paints';
				}
			},
			close: function(duration) {
				catalogue.page.dePopulate();
				catalogue.fadeDestroy(['pageManagement'], 0.3);
				catalogue.showEditButtons();
				Event.stopObserving(window, 'beforeunload', catalogue.confirmExitBound);
			},
			submit: function(e) {
				Event.stop(e);
				tinyMCE.triggerSave();
				if (catalogue.validate.form($('pageManagement'))) {
					var url = ($('pageURL').value) ? $F('pageURL') : $('pageURL').innerHTML;
					var parentID = ($('parentPage')) ? $F('parentPage') : null;
					new Ajax.Request('/utilities/ajax.asp?action=ManagePage', {
						parameters: {
							url: url,
							seoTitle: escape($F('pageSEOTitle')),
							seoDesc: escape($F('pageSEODesc')),
							seoKeywords: escape($F('pageSEOKeywords')),
							pageTitle: escape($F('pagePageTitle')),
							description: escape($F('pageDescription')),
							linkText: escape($F('pageLinkText')),
							linkTitle: escape($F('pageLinkTitle')),
							seoDesc: escape($F('pageSEODesc')),
							pageID: catalogue.page.id,
							parentID: parentID
						},
						onSuccess: function (request) {
							tinyMCE.execCommand('mceRemoveControl', false, 'pageDescription');
							catalogue.drawPageList(window.location.href);
							catalogue.page.editForm.close();
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "Thank you - your page has been successfully saved.";
								myAlert.type = 'confirmation';
								myAlert.show();
								myAlert.hide(4000);
						},
						onFailure: function(request) {
							var myAlert = catalogue.alerts.newAlert();
								myAlert.message = "An error has occurred, but your technical support has been notified of the problem.";
								myAlert.type = 'error';
								myAlert.show();
								myAlert.hide(4000);
						}
					});
				}
			}
		}
	}

}

Event.observe(window, 'load', catalogue.init);


function returnCurrency(number, currency) {
	number = String(number);
	if (number || number == 0) {
		if (number == "")										number = '0.00';
		if (number.indexOf(".") == -1)							number += ".00";
		if (number.charAt(number.toString().length-2) == ".")	number += "0";
		if (number.charAt(number.length-2) != ".") 				number = number.substring(0, number.indexOf(".") + 3);
		if (number != "0.00") 									number = Math.round(number*100)/100;
		
		if (currency) 	number = currency + number;
	} else {
		number = "Call for Price";
	}
	return number;
}

function inputResponder (input, label) {
	if (input.value == label.innerHTML) {
		input.value = '';
		input.style.color = '#333'
		input.style.fontStyle = 'normal'
	} else if (input.value == '') {
		input.value = label.innerHTML;
		input.style.color = '#999';
		input.style.fontStyle = 'italic'
	}
	
}

function collapseVariations (productVariations) {
	var variations = [];
	for (var i=0, j=productVariations.length; i<j; i++) {
		if (productVariations[i].values) {
			for (var k=0, l=productVariations[i].values.length; k<l; k++) {
				var value = productVariations[i].values[k];
				var variationExists = false;
				// find the variation
				if (variations.length > 0) {
					for (var m=0, n=variations.length; m<n; m++) {
						if (variations[m].id == value.VariationID) {
							variationExists = true;
							var variationArrayPos = m;
						}
					}
					if (variationExists) {
						var valueExists = false;
						for (var o=0, p = variations[variationArrayPos].values.length; o<p; o++) {
							if (variations[variationArrayPos].values[o].ValueID == value.ValueID) {
								valueExists = true;
							}
						}
						if (!valueExists) {
							variations[variationArrayPos].values.push(value);
						}
					} else {
						var variation = {
							id: value.VariationID,
							name: value.VariationName,
							values: [value]
						}
						variations.push(variation);
					}
				} else {
					var variation = {
						id: value.VariationID,
						name: value.VariationName,
						values: [value]
					}
					variations.push(variation);
				}
			}
		}
	}
	return variations;
}
