catalogue={
	ajaxPath: '/utilities/ajax.asp?action=',
	informUser: function (message, type) {
		var div = new Element('div', {id:'informUser'})
			.setHTML(message)
			.injectTop(document.body);
		if (type)	div.addClass(type);
		
		var mySlider = new Fx.Slide('informUser', {duration: 500}).hide().slideIn();
		
		new Fx.Scroll(window, {
			wait: false,
			duration: 500
		}).toTop();
		
		(function () {
			mySlider.slideOut();
			(function () {
				this.getParent().remove();
			}).delay(3000, this);
		}).delay(5000, div);
	},
	handleError: function (message) {0
		if (!message)	var message = "Our apologies, an unexpected error has occurred - please call us on 0141 944 4443.";
		catalogue.informUser(message, 'error');
		return false;
	},
	FadeNav: new Fx.Style($('sNav'), 'opacity', {duration:0.3}),
	fadeDestroy: function(IDs, duration) {
		$A(IDs).each(function(id) {
			if ($(id)) {
				new Fx.Style(id, 'opacity', {
					duration: (duration? duration : 300),
					onComplete: function () {
						$(id).remove();
					}
				}).start(1, 0)
			}
		});
	},
	
	init: function() {
//		var match = new RegExp('^http://(www.)?foremostproducts.co.uk(.*)$');
//		if (!document.referrer.match("^http://(www.)?foremostproducts.co.uk")) {
//			catalogue.informUser("Prices are fluctuating often in the current climate - please call us <strong>(0141 944 4443)</strong> or submit your enquiry basket and we'll call you back to confirm prices.");
//		}
		if ($('cartRetrieval'))	{
			$('page').setStyle('top', '31px');
			$('cartRetrieval').addEvent('click', checkout.init);
			window.addEvent('scroll', function () {
				var top = window.pageYOffset || window.document.documentElement.scrollTop;
				$('cartRetrieval').setStyle('top', top);
			});
		}
		catalogue.initCustomerCategories();
		catalogue.initNavigationParents();

		if ($('searchForm')) {$('searchForm').addEvent('submit', catalogue.search.init);}
		if ($('contactForm')) {$('contactForm').addEvent('submit', catalogue.submitContactForm);}
		
		catalogue.imgZoom.init('.zoom');

		catalogue.initProductSelects();
		catalogue.initAddToCartButtons();
		catalogue.initHelpButtons();
		if ($(document.body).hasClass('product')) {
			catalogue.product.id = document.body.id.replace('product', '');
			catalogue.product.populate();
		}
		
		/*
		if ($('cart')) {
			$('commentLink').addEvent('click', function () {
				$('comments').setStyle('display', $('comments').getStyle('display') == 'none' ? '' : 'none');
			});
			$('cart').addEvent('submit', function (e) {
				new Event(e).stop();
				var regEx = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
				if (!regEx.test($('email').value)) 	return catalogue.handleError("This doesn't appear to be a valid email address.");
				if ($('upload').value != '')	catalogue.informUser('Please wait while we upload your artwork...');
				pageTracker._trackPageview('/order-submitted/');
				new Element('input', {type:'hidden', id:'nospam', name:'nospam', value:'nospam'}).injectInside($('cart'));
				this.submit();
			});
			$('cart_container').addEvent('click', function (e) {
				e = new Event(e);
				if ($(e.target).hasClass('delete')) {
					e.stop();
					var id = e.target.id.replace('delete', '');
					catalogue.addToCart(id, 0);
				}
			});
		}
		*/
//		$('checkout').addEvent('click', checkout);

		if ($('requestQuote')) {
			$$('#artwork input')[0].setStyle('opacity', 0); $$('#artwork input')[0].setStyle('visibility', 'visible');
//			$$('#requestQuote .button').setStyle('color', 'transparent');
			$$('#personalDetails input').each(function (input) {
				var cookie = Cookie.get(input.getProperty('name').toLowerCase());
				input.value = cookie ? cookie : '';
			});
			catalogue.setupQuoteRequestAnalytics();
			$('requestQuote').addEvent('submit', function (e) {
				var email = $$('#requestQuote input[name=Email]')[0];
				var regEx = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
				if (!regEx.test(email.getValue())) {
					new Event(e).stop();
					email.setStyle('border-color', 'red');
				} else {
					email.setStyle('border-color', '#ccc');
				}
				if ($('Total').value == '')	$('Total').value = $$('#totalPrice span')[0].getText();
				if ($('UnitPrice').value == '')	$('UnitPrice').value = $$('#unitPrice span')[0].getText();
				
				
				
			});
			$('nospam').value = 'nospam';
			
			$('rememberMe').addEvent('change', function () {
				if (!this.checked) {
					$$('#personalDetails input').each(function (input) {
						Cookie.remove(input.getProperty('name').toLowerCase(), {path:'/'});
					});
				}
				Cookie.set('rememberMe', this.checked, {path:'/'});
			});
			if (rememberMe = Cookie.get('rememberMe')) {
				$('rememberMe').checked = rememberMe == 'false' ? false : true;
			}
		}

	},
	initProductSelects: function() {
		var selects = document.getElementsByTagName('select');
		$A(selects).each(function(select) {
			if (select.id.indexOf('variation') != 0) {
				var productID = select.id.substring('productID'.length, select.id.indexOf('variation'));
				$(select).addEvent('change', function() {
					var productID = this.id.substring(this.id.indexOf(productID) + 'productID'.length + 1, this.id.indexOf('variation'));
					catalogue.product.id = productID;
					if (!catalogue.product.variations)	catalogue.product.populate();
					catalogue.product.setVariationPrice();
				});
			}
		});
		if ($('customQuantity')) {
			$('customQuantity').addEvent('change', function() {
				var quantity = $('customQuantity').getValue();
				var select = $$('#variationSelection2 li.hidden select')[0];
				if (select) {
					var options = select.options;
					options[0].selected = true;	// default to smallest most expensive quantity
					// select the appropriate option in the hidden quantity dropdown
					$A(options).each(function (option) {
						if (parseInt(option.text) <= parseInt(quantity))	option.selected = true;
					});
				}
				
				if (!catalogue.product.variations) {
					catalogue.product.id = $('productID').value;
					catalogue.product.populate();
				}
				catalogue.product.setVariationPrice();
			});
		}
	},
	initAddToCartButtons: function() {
		var buttons = document.getElementsByTagName('button');
		$A(buttons).each(function (button) {
			if ($(button).hasClass('AddToCart') != -1) {
				$(button).addEvent('click', function() {
					// GOOGLE
					pageTracker._trackPageview('/added-to-cart/');
					// get product parameters
					var elemID = this.getProperty('id');
					var productID = elemID.substring('AddToCart'.length, elemID.length);
					if (!catalogue.product.variations) {
						catalogue.product.id = productID;
						catalogue.product.populate();
					}
/*|					
					var selects = $$('.variations select');
					
					
					if ($('pricingTable') && selects.length > 1) {
						var colours = $('colours').value.split(',');
						var colourControl = new Element('ul').addClass('colours');
						colours.each(function (colour) {
							new Element('li')
								.setStyle('background', colour.replace(' ', ''))
								.addClass(colour.replace(' ', ''))
								.setProperty('title', colour)
								.addEvent('click', function () {
									colourControl.getElements('li').each(function(colour) {colour.removeClass('on');});
									selectedColour = this.addClass('on');
								})
								.injectInside(colourControl);
						});
						var selectedColour = colourControl.getFirst().addClass('on');
					}
					
					var popup;
					var quantityField = new Element('input', {value:1});
					var btn = new Element('button')
						.addClass('add')
						.addEvent('click', function () {
							var quantity = quantityField.value;
							if (quantity == '')	return catalogue.handleError('Please enter a quantity.');
							if (selectedColour) {
								// update selects to match specifications
								// colour
								var colour = selectedColour.getProperty('title');
								selects.each(function (select) {
									$A(select.options).each(function (option) {
										if (option.text == colour)	option.selected = true;
									})
								});
								// quantity
								selects.each(function (select) {
									$A(select.options).each(function (option) {
										if (parseInt(option.text) < parseInt(quantity))	option.selected = true;
									})
								});
							}
							var productVariation = catalogue.product.isolateProductVariation();
							catalogue.addToCart(productVariation.id, quantity);
							// GOOGLE
							pageTracker._trackPageview('/added-to-cart-complete/');
							
							popup.remove();
						});
						
					var coords = this.getPosition();
						
					popup = new Element('div')
						.addClass('quantity')
						.adopt(new Element('div')
							.adopt(new Element('label').setText('How many would you like?'))
							.adopt(quantityField)
						)
						.adopt(btn)
						.adopt(new Element('button', {value:'Cancel'}).setText('Cancel').addClass('cancel').addEvent('click', function () {popup.remove();}))
						.setStyles({
							left:coords.x -150,
							top:coords.y + 27
						})
						.injectInside(document.body);
					
					if (colourControl) {
						popup.addClass('colour');
						new Element('div')
							.adopt(new Element('label').setText('Which colour would you like?'))
							.adopt(colourControl)
							.injectTop(popup);
					}
					
*/					
					var productVariation = catalogue.product.isolateProductVariation();
					var quantity = $('customQuantity') ? $('customQuantity').getValue() : 1;
					catalogue.addToCart(productVariation.id, quantity);
				});
			}
		});
	},
	initHelpButtons: function () {
		var buttons  = $$('.help');
		buttons.each(function (button) {
			button.addEvent('mouseover', function (e) {
				var popup = new Element('div')
					.addClass('helpWindow')
					.adopt(new Element('h3').setText('How this site works'))
					.adopt(new Element('p').setHTML("This site allows you to collect products in an enquiry that you can then send to us with any order-specific details.  We then call you back to firm up the details and <strong>settle up by telephone</strong>."))
					.adopt(new Element('p').setHTML("Click 'Add to Enquiry' on product pages to add that product to your enquiry.  Click 'Review & Send Enquiry' (top right) and provide your contact details to submit your enquiry."))
					.adopt(new Element('p').setHTML("If you've any problems, or would just prefer the personal touch, call us on <em>0141 944 4443</em>."))					
					.addEvent('mouseout', function () {if (popup && popup.parentNode) this.remove();});
					
				var coords = button.getCoordinates();
				popup.setStyles({
					left:	coords.left - 316,
					top:	coords.top - 18,
					display: 'block'
				});
				popup.injectInside(document.body);
			});
		});
	},
	initCustomerCategories: function () {
		$$('#customers li').each(function (category, i) {
			category.getFirst().setHTML(category.getText().replace(' Products', 's'));
			$$('#customers li.on')[0].on = true;
			category.addEvents({
				mouseover:function () {
					$$('#customers li').removeClass('on');
					this.addClass('on');
				},
				mouseout: function () {
					$$('#customers li').each(function (li) {
						li.removeClass('on');
						if (li.on)	li.addClass('on');
					});
				},
				click: function (e) {
					new Event(e).stop();
					$$('#customers li').each(function (li) {li.on = false;});
					this.on = true;
					var categoryID = this.id.substring('category_'.length, this.id.length);
					var pathname = this.getFirst().pathname;
					catalogue.redrawSubCategoryList(categoryID, pathname);
				}
			});
		});
	},
	initNavigationParents: function () {
		$$('#menu .parent').each(function (parent) {
			var link = parent.getFirst();
			var effect = new Fx.Slide(link.getNext());
			if (!$(link).getParent().hasClass('on')) 	effect.hide();
				$(link).addEvent('click', function(e) {
					new Event(e).stop();
					effect.toggle();		
				});
		});
/*	
		if (!$('menu')) {
			var id = $('shoppingFor').getFirst().getFirst().id.replace('radio', '');
			catalogue.redrawSubCategoryList(id, true);
		} else {
			var parents = $('menu').getElementsByClassName('parent');
			$A(parents).each(function(parent) {
				var link = parent.getElementsByTagName('a')[0];
				var list = $(parent.getElementsByTagName('ul')[0]);
				var effect = new Fx.Slide(list)
				if (!$(link).getParent().hasClass('on')) 	effect.hide();
				$(link).addEvent('click', function(e) {
					new Event(e).stop();
					effect.toggle();		
				});
			});
		}
*/
	},
	setupQuoteRequestAnalytics: function () {
		if ($('customQuantity')) {
			$('customQuantity').addEvent('change', function () {
				pageTracker._trackPageview('/custom-quantity-changed/');
			});
		}
		var selects = $$('#variationSelection2 select');
			selects.addEvent('change', function () {
				pageTracker._trackPageview('/variation-selected/');
			});
		var inputs = $$('#personalDetails input');
			inputs.addEvent('change', function () {
				var name = this.getProperty('name').toLowerCase();
				pageTracker._trackPageview('/'+name+'-set/');
				if ($('rememberMe').checked)	Cookie.set(name, this.value, {path:'/'});
			});
	},
	
	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.maxLength != -1 && 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 "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;
			}
			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).remove();
			}
		}
	},
	
	redrawSubCategoryList: function(categoryID, location) {
		new Ajax(catalogue.ajaxPath + 'GetCategoryNav', {
			data:{
				productGroup: categoryID,
				location: location
			},
			onSuccess: function (response) {
				if (response != 'error') {
					$('menu').innerHTML = response;
					catalogue.initNavigationParents();
				}
			}
		}).request();
	},
	
	imgZoom:{
		init: function(selector) {
			$$(selector).each(function (thumb) {
				thumb.addEvent('click', function() {
					var ThumbPos = thumb.getPosition();
					var ThumbSize = thumb.getSize().size;
					
					var div = new Element('div')
						.addClass('zoom')
						.setStyles({
							opacity:0.8, 
							position:'absolute', 
							left:ThumbPos.x, 
							top:ThumbPos.y,
							width:ThumbSize.x-20, // padding
							height:ThumbSize.y-20 // padding
						})
						.addEvent('click', function () {this.remove();})
						.adopt(new Element('img', {src:'/images/loading.gif'}))
						.injectInside(document.body);
					
					var FullSize = new Image();
						$(FullSize).addEvent('load', function () {
							div.empty();
							var top = ThumbPos.y - (FullSize.height / 2);
							var left = ThumbPos.x - (FullSize.width / 2);
							var scrollTop = window.getScrollTop();
							if (window.ie)	scrollTop = document.body.scrollTop;
							var scrollBottom = scrollTop + window.getHeight();
							if (window.ie)	scrollBottom = scrollTop + document.body.clientHeight;
							
							if (left < 0) left = 10;
							if (top < 0 || top < scrollTop) top = scrollTop + 10;
							if ((top + FullSize.height) > scrollBottom)	top = scrollBottom - FullSize.height - 30;							
							if (!window.ie) {
								if ((left + FullSize.width) > window.getWidth())	left = window.getWidth() - FullSize.width - 30;
							} else {
								if ((left + FullSize.width) > document.body.clientWidth)	left = document.body.clientWidth - FullSize.width - 30;
							}
							
							var fx = new Fx.Styles(div, {
								onComplete: function () {
									div.setOpacity(1).adopt(FullSize);
								}.bind(this)
							}).start({
								top:top,
								left:left,
								width:FullSize.width,
								height:FullSize.height
							});
						});
						FullSize.src = thumb.src.contains('thumb') ? thumb.src.replace('thumb', 'large') : thumb.src.replace('medium', 'large');
				});
			});
		}
	},
	
	addToCart: function (productVariationID, quantity) {
		new Ajax('/utilities/ajax.asp?action=AddToCart', {
			data: {
				productVariationID: productVariationID,
				update: quantity
			},
//			update: $('cart_container'),
			onSuccess: function(html) {
				if (html == 'error')	return catalogue.handleError();
//				$('cart_container').setHTML(unescape(html.substring(1, html.length-1)));
//				catalogue.informUser("Thank you - your enquiry has been updated, as indicated to the right of the page.");
				checkout.init(html);
			}
		}).request();
	},
	updateCart: function (productVariationID, quantity) {
		new Ajax('/utilities/ajax.asp?action=AddToCart', {
			data: {
				productVariationID: productVariationID,
				update: quantity
			},
			onSuccess: function(html) {
				if (html == 'error')	return catalogue.handleError();
				if ($('products')) {
					$('products').setHTML(unescape(html));
					initReviewBehaviours();
				}
			}
		}).request();
	},
	
	search:{
		init:function(e) {
			new Event(e).stop();
			if ($('SERP')) {
				var SERP = $('SERP');
				if (results = SERP.getElementsByTagName('ul')[0]) {
					results.remove();
				} else {
					SERP.getElementsByTagName('p')[1].remove();
				}
			} else {
				var SERP = new Element('div', {id:'SERP', 'class':'popup'})
					.adopt(new Element('a', {id:'SERPClose', 'class':'close'}).setText('Close'))
					.adopt(new Element('h5').setText('Search Results'))
					.adopt(new Element('p').setText('Please select from the following search results:'));
			}
			
			SERP.adopt(new Element('p', {id:'SERPloader'})
				.adopt(new Element('img', {src:'/images/interstitial_loading.gif'}))
			);
			
			var query = $('search').getValue();
			// GOOGLE
//			pageTracker._trackPageview('search.asp?q=' + query);
			if (query.indexOf(' ') != -1) {
				if (query.charAt(0) != '"') query = '"' + query;
				if (query.charAt(query.length-1) != '"') query = query + '"';
			}
			new Ajax(catalogue.ajaxPath + 'Search', {
				data: {
					query: escape(query)
				},
				onSuccess: function(response) {
					if (response == 'error') {
						catalogue.handleError("Our apologies, we were unable to complete your search - please call us on 0141 944 4443.");
					} else {
						if (response) {
							var results = Json.evaluate(response);
							if (results = results.records) {
								var ul = new Element('ul', {'class':'productList'});
								$A(results).each(function(item, index) {
									if ( (index == 0) || ((index > 0) && (item.shortTitle != results[index-1].shortTitle)) ) {
										var li = new Element('li');
										var note = '';
										if (item.Type == 'Product') {
											li.appendChild(new Element('img', {src:'/pictures/' + item.id + '-thumb.jpg'}));
										} else {
											note = ' (Category Page)';
										}
										li.appendChild(new Element('a', {href:'/' + item.url + '/', title:item.longTitle}).setText(item.shortTitle + note));
										ul.appendChild(li);
									}
								});
								SERP.appendChild(ul);
								$A($('SERP').getElementsByTagName('img')).each(function(img) {
									$(img).addEvent('click', function() {
										catalogue.imgZoom.init(this);
									});
								});
							} else {
								var noResults = true;
							}
						} else {
							var noResults = true;
						}
					}
					if (noResults) {
						new Element('div')
							.adopt(new Element('p').setText('We were unable to find any matches for your search - please refine your search or give us a call.'))
							.injectInside(SERP);
					}
					$('SERPloader').remove();
				}
			}).request();
			$('page').appendChild(SERP);
			$('SERPClose').addEvent('click', catalogue.search.close);
		},
		close: function() {
			catalogue.fadeDestroy(['SERP']);
		}
	},
	
	submitContactForm: function(e) {
		// GOOGLE
		pageTracker._trackPageview('/enquiry-submitted/');
		new Event(e).stop();
		if (catalogue.validate.form($('contactForm'))) {
			$('contactForm').appendChild(new Element('img', {id:'loader', src:'/images/interstitial_loading.gif'}));
			if (catalogue.validate.form($('contactForm'))) {
				new Ajax(catalogue.ajaxPath + 'SendContactForm', {
					data: {
						name: escape($('contactName').getValue()),
						emailAddress: escape($('contactEmail').getValue()),
						phone: escape($('contactPhone').getValue()),
						message: escape($('contactMessage').getValue()),
						permission: escape($('permission').getValue())
					},
					onSuccess: function (response) {
						// GOOGLE
						pageTracker._trackPageview('/enquiry-sent/');
						$('loader').remove();
						new Element('p').setText('Thank you, your message has been sent, and we shall get back to you shortly.').injectAfter('contactForm');
						$('contactForm').remove();
					},
					onFailure: function() {catalogue.handleError();}
				}).request();
			}
		}
	},

	getSelectedVariationValues: function () {
		var selects = $$('#variationSelection2 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);
			}
		}
		return selectedVariationValues;
	},	
	
	product: {
		populate: function() {
			var successCalled = false;
			var request = new Ajax(catalogue.ajaxPath + 'SelectProductVariationsById', {
				async: false,
				data: 'id=' + this.id,
				onSuccess: function(response) {
					successCalled = true;
					if (response == 'error') {
						catalogue.handleError();
					} else {
						if (response)	catalogue.product.variations = Json.evaluate(response).records;
					}
				},
				onFailure: function (response) {catalogue.handleError();}
			}).request();
			if (!successCalled)	request.onStateChange();	// firefox 3 doesn't fire the onreadystatechange event on asyncronous requests
		},
		isolateProductVariation: function(selectedVariationValues) {
			if (!selectedVariationValues)	selectedVariationValues = catalogue.getSelectedVariationValues();
			
			// get the matching product variations
			var productVariationFound = false;
			var productVariationArrayPos = 0;
			if (catalogue.product.variations) {
				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 && productVariation.values && valueArrayPos != productVariation.values.length) {
							var value = productVariation.values[valueArrayPos];
							if ( (selectedVariationValue.VariationID == value.VariationID) && (selectedVariationValue.ValueID == value.ValueName) ) {
								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];
			}
		},
		setVariationPrice: function() {
			var productVariation = catalogue.product.isolateProductVariation();
			var quantity = $('customQuantity') ? $('customQuantity').getValue() : $$('select[name=Quantity]')[0].getValue();
			
			if (productVariation && (!(productVariation.available == 'false'))) {
				if (productVariation.salePrice != 'null') {
					var unitPrice = String(productVariation.salePrice).returnCurrency();
					var totalPrice = String(productVariation.salePrice * quantity).returnCurrency();
					if ($('product' + catalogue.product.id + 'cost'))	$('product' + catalogue.product.id + 'cost').innerHTML = '<span class="strikethrough">' + String(productVariation.unitPrice).returnCurrency() + '</span> <span class="salePrice">' + unitPrice + '</span>';
//					$$('#totalPrice span')[0].innerHTML = '<span class="strikethrough">' + String(productVariation.unitPrice * quantity).returnCurrency() + '</span> <span class="salePrice">' + totalPrice + '</span>';
					$$('#totalPrice span')[0].innerHTML = '<span class="salePrice">' + totalPrice + '</span>';
					$('UnitPrice').value = unitPrice;
					$('Total').value = totalPrice;
				} else {
					var unitPrice = String(productVariation.unitPrice).returnCurrency();
					var totalPrice = String(productVariation.unitPrice  * quantity).returnCurrency()
					if ($('product' + catalogue.product.id + 'cost'))	$('product' + catalogue.product.id + 'cost').innerHTML = unitPrice;
					$$('#totalPrice span')[0].innerHTML = totalPrice;
					$('UnitPrice').value = unitPrice;
					$('Total').value = totalPrice;
				}
//				$('AddToCart' + catalogue.product.id).disabled = false;
			} else {
				$('product' + catalogue.product.id + 'cost').innerHTML = '';
				$$('#totalPrice span')[0].innerHTML = '';
//				$('AddToCart' + catalogue.product.id).style.backgroundPosition = 'bottom';
//				$('AddToCart' + catalogue.product.id).disabled = true;
			}
		}
	}
}

	
checkout={
	init: function (html) {
		if (typeof(html) === "string") {
			checkout.draw(html);
		} else {
			new Ajax('/utilities/ajax.asp?action=getCartHTML', {
				data:{},
				onComplete: function (html) {
					checkout.draw(html);
				}
			}).request();
		}
	},
	draw: function (html) {
		if (!$('overlay')) {
			new Element('div', {id:'overlay'})
				.setStyles({
					width:window.getScrollWidth(), height:window.getScrollHeight(),
					background:'black',
					position:'absolute', top:0, left:0,
					zIndex:9999
				})
				.setOpacity(0.5)
				.injectInside(document.body);
		
			$$('select').setStyle('display', 'none');
		}
				
		var popup = $('review').empty().addClass('interface').setStyle('width', 550)
			.adopt(new Element('a').addClass('close').setText('Close').addEvent('click', checkout.close))
			.adopt(new Element('h3').setText('Review & Send Enquiry'))
			.adopt(new Element('div', {id:'products'}).setHTML(unescape(html)))
			.adopt(new Element('div').setHTML("<p style='padding-top:0px'><small>* Delivery charged at cost</small></p>"))
			.adopt(new Element('div').setHTML('\
				<ul class="bulletless">\
				<li><label for="name">Name:</label><input type="text" name="name" /></li> \
				<li><label for="phone">Phone:</label><input type="text" name="phone" /></li> \
				<li><label for="email">Email:</label><input type="text" name="email" /></li> \
				<li class="upload"><label for="artwork">Artwork:</label><input type="file" name="upload" /></li> \
				<li><label for="message">Message:</label><textarea name="message"></textarea></li> \
				<li class="checkbox"><label for="permission">May we email you special offers?</label><input type="checkbox" name="permission" checked /></li> \
				</ul> \
				<input type="hidden" id="nospam" name="nospam" value="nospam" />'
			))
			.adopt(new Element('ul').addClass('buttons')
				.adopt(new Element('li').adopt(new Element('input', {id:'send', type:'submit', value:'Send'}).addEvent('click', function () {$('review').submit();})))
				.adopt(new Element('li').setText('or ').adopt(new Element('a').setText('Continue Shopping >').addEvent('click', checkout.close)))
			)
			.addEvent('submit', function () {pageTracker._trackPageview('/order-submitted/'); $('products').empty().setStyles({background: 'url(/images/loading.gif) center no-repeat', height:50});})
			.setStyle('visibility', 'visible')
			.center();//.setStyle('top', 75);
			popup.setProperty('enctype', 'multipart/form-data');
			
		initReviewBehaviours();
		
		pageTracker._trackPageview('/checkout/');
	},
	close: function () {
		if ($('overlay'))	$('overlay').remove();
		$('review').setStyle('visibility', 'hidden');
		$$('select').setStyle('display', '');
//		$('mainmenuShadow').remove();
		if (!$('cartRetrieval')) {
			new Element('div', {id:'cartRetrieval'}).injectAfter('review').setHTML('Your enquiry will remain available - <u>click here</u> to retreive it at any time.')
				.addEvent('click', checkout.init);
			new Fx.Scroll(window, {
				wait: false,
				duration: 500
			}).toTop();
			$('page').setStyle('top', '31px');
		}

		pageTracker._trackPageview('/checkout-closed/');
	}
}

function initReviewBehaviours() {
	$$('#review .quantity input').each(function (input) {
		input.addEvent('change', function () {
			catalogue.updateCart(this.id.replace('quantity', ''), this.value);
		});
	});
	$$('#review .quantity a').each(function (removeBtn) {
		removeBtn.addEvent('click', function () {
			catalogue.updateCart(this.id.replace('remove', ''), 0);
		});
	});
}	


window.addEvent('domready', catalogue.init);

ticker={
	list:false,
	paused: false,
	fps: 50,
	scrollDistance: 2,
	overflow: 0,
	item: {
		width: false
	},
	init: function() {
		if ($('carousel')) {
			ticker.list = $('carousel');
			ticker.items = ticker.list.getElements('li');
			ticker.item.width = ticker.items[0].getSize().size.x + 10;
								
			// absolutize
			ticker.items.each(function (item) {
				item.coords = item.getPositionedOffset();
			});
			y = ticker.items[0].coords.y;
			ticker.edge = 0
			ticker.items.each(function (item) {
				item.setStyles({
					position:'absolute',
					left:ticker.edge,
					top:y
				});
				ticker.edge += ticker.item.width + 20;
			});
			
			ticker.list.addEvent('mouseover', function() {ticker.paused = true;});
			ticker.list.addEvent('mouseout', function() {ticker.paused = false;});
			ticker.shift();
		}
	},
	shift: function() {
		if(!ticker.paused) {
			ticker.items.each(function (item) {
				if (parseInt(item.getStyle('left')) > ticker.edge) {
					item.setStyle('left', 0);
				}
				item.setStyle('left', parseInt(item.getStyle('left')) + ticker.scrollDistance);
			});
		}
		setTimeout('ticker.shift();', ticker.fps);
	}
};
		
window.addEvent('domready', ticker.init);

/*
Script: FixPNG.js
	Extends the Browser hash object to include methods useful in managing the window location and urls.

License:
	http://clientside.cnet.com/wiki/cnet-libraries#license
*/
function fixPNG() {
	$$('img.fixPNG').each(function (el) {
		var dim = el.getSize();
		var replacement = new Element('span', {
			id:(el.id)?el.id:'',
			'class':(el.className)?el.className:'',
			title:(el.title)?el.title:(el.alt)?el.alt:'',
			styles: {
				width: dim.size.x,
				height: dim.size.y,
				filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='" + el.src + "', sizingMethod='scale')"
			},
			src: el.src
		});
		if (el.style.cssText) {
			var styles = {};
			var s = el.style.cssText.split(';');
			s.each(function(style){
				var n = style.split(':');
				styles[n[0]] = n[1];
			});
			replacement.setStyles(styles);
		}
		replacement.cloneEvents(el);
		replacement.injectAfter(el);
		el.remove();
	});
	
/*
	try {
		if (window.ie6){
			el = $(el);
			if (!el) return el;
			if (el.getTag() == "img" && el.getProperty('src').test(".png")) {
				alert(el.getProperty('src'));
				var vis = el.isVisible();
				try { //safari sometimes crashes here, so catch it
					dim = el.getSize();
				}catch(e){}
				if(!vis){
					var before = {};
					//use this method instead of getStyles 
					['visibility', 'display', 'position'].each(function(style){
						before[style] = this.style[style]||'';
					}, this);
					//this.getStyles('visibility', 'display', 'position');
					this.setStyles({
						visibility: 'hidden',
						display: 'block',
						position:'absolute'
					});
					dim = el.getSize(); //works now, because the display isn't none
					this.setStyles(before); //put it back where it was
					el.hide();
				}
				var replacement = new Element('span', {
					id:(el.id)?el.id:'',
					'class':(el.className)?el.className:'',
					title:(el.title)?el.title:(el.alt)?el.alt:'',
					styles: {
						display: vis?'inline-block':'none',
						width: dim.x,
						height: dim.y,
						filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='" 
							+ el.src + "', sizingMethod='scale');"
					},
					src: el.src
				});
				if(el.style.cssText) {
					try {
						var styles = {};
						var s = el.style.cssText.split(';');
						s.each(function(style){
							var n = style.split(':');
							styles[n[0]] = n[1];
						});
						replacement.setStyle(styles);
					} catch(e){ dbug.log('fixPNG1: ', e)}
				}
				if(replacement.cloneEvents) replacement.cloneEvents(el);
				replacement.replaces(el);
			} else if (el.get('tag') != "img") {
				var imgURL = el.getStyle('background-image');
				if (imgURL.test(/\((.+)\)/)){
					el.setStyles({
						background: '',
						filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src=" + imgURL.match(/\((.+)\)/)[1] + ")"
					});
				};
			}
		}
	} catch(e) {alert('out');}
*/
}

if(window.ie6) 
	window.addEvent('domready', fixPNG);

Element.extend({
	getPositionedOffset: function () {
		var left = 0, top = 0, element = this;
		do {
			left += element.offsetLeft || 0;
			top += element.offsetTop  || 0;

			element = $(element.offsetParent);
			if (element) {
				if (element.tagName == 'BODY') break;
				var p = element.getStyle('position');
				if (p == 'relative' || p == 'absolute') break;
			}
		} while (element);
		return {'x':left, 'y':top};
	},
	center: function () {
		var left = (window.getWidth()/2) - (this.getSize().size.x/2);
		var top = (window.getHeight()/2) - (this.getSize().size.y/2) + (window.getScrollTop());
		if (left < 0) left = 10;
		if (top < 0 || top < window.getScrollTop()) top = window.getScrollTop() + 75;

		this.setStyles({
			position:'absolute',
			left: left,
			top: top
		});
		return this;
	}
});
String.extend({
	returnCurrency: function() {
		var number = (this=='')? '0.00' : this;									// if no number, set to 0.00
			number = String(Math.round(this*1000)/1000);						// round to three decimal places
			number = (number.indexOf(".") == -1) ? number + '.00' : number;		// if no decimal places, add .00
		
		var numeral = number.substring(0, number.indexOf('.'));
		var decimal = number.substring(number.indexOf('.') + 1, number.length);
			decimal = (decimal.length < 2) ? decimal + '0' : decimal;			// if decimal has only 1 digit, add the extra 0
		
		if (numeral == 0 && decimal != "00") {
			if (decimal.charAt(0) == '0')	decimal = decimal.substring(1, decimal.length);		// change 05p to 5p
			if (decimal.length > 2)	decimal = decimal.substring(0, 2) + '.' + decimal.substring(2, decimal.length);
			
			number = decimal + 'p';
		} else {
			number = '&pound;' + Math.round(number*100)/100;
			if (number.substring(number.indexOf('.') + 1, number.length).length == 1)	number += '0'
		}
		if (number == '&pound;0') return 'POA';
		return number;
	}
});