Array.prototype.in_array = function(obj){
	for(var x = 0; x <= this.length; x++)
		if(this[x]==obj) return true;
	return false;
}

function page_loaded()
{
	BASKET.loaded();
	PAGE.loaded();
}

function match_elements(els)
{	
	if (BrowserDetect.browser=="Firefox")
	{	return XML.getNodes(window.document, els, "");
	} else
	{	
		return false;
	}
	
}

function field_validate(el, filters)
{	
	validated = true;
	
	valu = el.value;
	
	if (filters!="")
	{	
		filter_list = filters.split(',');
		
		accept_blank = (filters.indexOf('NONEMPTY')>0);
		
		if (accept_blank && valu=="")
		{	
		} else
		{
			for (i=0; i<filter_list.length; i++)
			{	
			//	alert(filter_list[i]);
				switch (filter_list[i])
				{	
					case "NONEMPTY":
						if (valu=="")
						{	validated = false;
						}
					break;
					
					case "EMAIL":
						if (valu.search(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/))
						{	validated = false;
						}
					break;
					
					case "ONELINE":
						
						if (valu.search(/([\r\n]+)/))
						{	validated = false;
						}
					break;
					
					case "NUMERIC":
					case "NUMERICSTR":
						if (isNaN(valu))
						{	validated = false;
						}
					break;
					
					case "YEAR":
						if (isNaN(valu))
						{	validated = false;
						} else
						{	if (valu < 1000 || valu > 10000)
							{	validated = false;
							}
						}
					break;
					
					case "MONTH":
						if (isNaN(valu))
						{	validated = false;
						} else
						{	if (valu < 1 || valu > 12)
							{	validated = false;
							}
						}
					break;
					
					case "BANKCARD":
						
					break;
					
					case "PASSWORD":
						
					break;
				}
			}
		}
	}
	
	if (validated)
	{	el.className = el.className.replace(" alert", "");
	} else
	{	el.className = el.className + " alert";
	}
}

var BASKET = {};
	
	BASKET.BUTTON = null;
	BASKET.CONTENTS = null;
	
	BASKET.smart_timer = null;
	
	BASKET.BASKET = [];
	BASKET.ITEMS = [];
	
	BASKET.set_basket = function(basket, items)
	{	BASKET.BASKET = basket;
		BASKET.ITEMS = items;
	}
	
	BASKET.add_product = function(product, size, colour, qty)
	{	//alert('['+product+'] ['+size+'] ['+colour+'] ['+qty+']');
		fnDone = function (x) {
			PAGE.messages_add(eval(x.responseText));
			PAGE.messages_process();
			
			BASKET.show_smart();
			BASKET.CONTENTS.onmouseout();
		};
		myConn.connect("/basket.php?act=add&vector=inpage", "POST", "product="+product+"&size="+size.toLowerCase()+"&colour="+colour.toLowerCase()+"&quantity="+qty, fnDone, false);
		return false;
	}
	
	
	BASKET.delete_product = function(sku)
	{	
		fnDone = function (x) {
			PAGE.messages_add(eval(x.responseText));
			PAGE.messages_process();
			BASKET.make_smart();
		};
		myConn.connect("/basket.php?act=delete&vector=inpage", "POST", "sku="+sku, fnDone, false);
	}
	
	function roundNumber(number,decimals) {
		var newString;// The new rounded number
		decimals = Number(decimals);
		if (decimals < 1) {
			newString = (Math.round(number)).toString();
		} else {
			var numString = number.toString();
			if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
				numString += ".";// give it one at the end
			}
			var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
			var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
			var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
			if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
				if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
					while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
						if (d1 != ".") {
							cutoff -= 1;
							d1 = Number(numString.substring(cutoff,cutoff+1));
						} else {
							cutoff -= 1;
						}
					}
				}
				d1 += 1;
			} 
			newString = numString.substring(0,cutoff) + d1.toString();
		}
		if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
			newString += ".";
		}
		var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
		for(var i=0;i<decimals-decs;i++) newString += "0";
		//var newNumber = Number(newString);// make it a number if you like
		return newString; // Output the result to the form field (change for your purposes)
	}
	
	BASKET.make_smart = function()
	{	
		txt = ""; items = [];
		
		for (i=0; i<BASKET.ITEMS.length; i++)
		{//	alert(BASKET.ITEMS[i]['product']);
			
			efs = '<div class="item">'+ BASKET.ITEMS[i]['quantity'] +'x ';
			
			efs+= '<a href="/products/'+ BASKET.ITEMS[i]['ref'] +'.html" title="View this product">' + BASKET.ITEMS[i]['product'] + '</a> &pound;' + roundNumber(parseFloat(parseFloat(BASKET.ITEMS[i]['price_ea'])+parseFloat(BASKET.ITEMS[i]['tax'])),2) + ' each ';
			efs+= '<a href="javascript:{};" onclick="BASKET.delete_product(\''+BASKET.ITEMS[i]['sku']+'\');" title="Remove this product">Del</a>';
			
			efs+= '</div>';
			items.push(efs);
		}
		
		txt+= items.join('');
		
		
		
		if (txt!="")
		{	btns = '';
			btns+= '<div class="SmartButtons">';
			btns+= '<a href="/basket.php" title="Go to basket"><img src="/images/buttons/basket.gif" alt="Basket"/></a>';
			btns+= '<a href="/Checkout/details" title="Go to checkout"><img src="/images/buttons/checkout.gif" alt="Checkout" /></a>';
			btns+= '</div>';
			
			txt = txt + btns;
		} else
		{	BASKET.CONTENTS.style.display='none';
		}
		
		BASKET.CONTENTS.innerHTML = txt;
	}
	
	
	BASKET.show_smart = function()
	{	if (BASKET.CONTENTS)
		{	
			BASKET.make_smart();
			
			if (BASKET.CONTENTS.innerHTML!="")
			{	BASKET.CONTENTS.style.display='block';
				
				BASKET.CONTENTS.onmouseout = function()
				{	
					BASKET.smart_timer = setTimeout('BASKET.hide_smart();', 1000);
				}
				
				BASKET.CONTENTS.onmouseover = function()
				{	
					if (BASKET.smart_timer)
					{	clearTimeout(BASKET.smart_timer);
					}
				}
			}
		}
		
	}
	
	
	BASKET.hide_smart = function()
	{	
		if (BASKET.CONTENTS)
		{	BASKET.CONTENTS.style.display='none';
		}
	}
	
	
	BASKET.update_minibasket = function()
	{	
		if (BASKET.BUTTON && BASKET.ITEMS)
		{	var item_count = 0;
			for(i in BASKET.ITEMS) if(BASKET.ITEMS[i]["quantity"])
				item_count+= BASKET.ITEMS[i]["quantity"] * 1;
			
			if(item_count==1)
			{	BASKET.BUTTON.innerHTML = "Shopping Bag - "+ item_count +" item";
			} else
			{	BASKET.BUTTON.innerHTML = "Shopping Bag - "+ item_count +" items";
			}
			
			BASKET.BUTTON.onmouseover = function(event)
			{	if (BASKET.ITEMS.length>0)
				{	
					BASKET.show_smart();
					return false;
				} else
				{	
					return true;
				}
			}
			
			BASKET.BUTTON.onmouseout = function()
			{	
				if (!BASKET.smart_timer)
				{	BASKET.smart_timer = setTimeout('BASKET.hide_smart();', 1000);
				}
			}
		}
	}
	
	BASKET.loaded = function()
	{	BASKET.BUTTON = document.getElementById('MiniBasketA');
		if (BASKET.BUTTON) { BASKET.update_minibasket(); }
		
		BASKET.CONTENTS = document.getElementById('SmartBasket');
		
	}


var PAGE = {};
{	PAGE.MESSAGES = [];
	PAGE.messagebox = null;
	PAGE.el = null;
	PAGE.searchform = {};
	PAGE.searchbox = {};
	PAGE.subscribebox = {};
	
	PAGE.loaded = function()
	{	PAGE.el = document.getElementById('Pane');
	
		PAGE.searchbox.el = document.getElementById("SearchFormInput");
		//PAGE.searchbox.initval = PAGE.searchbox.el.value;
		PAGE.searchbox.initval = "Enter search...";
		PAGE.searchbox.el.onfocus = function()
		{	if(this.value==PAGE.searchbox.initval) this.value = "";
		}
		PAGE.searchbox.el.onblur = function()
		{	if(this.value=="") this.value = PAGE.searchbox.initval;
		}
		
		PAGE.searchform.el = document.getElementById("SearchForm");
		PAGE.searchform.el.onsubmit = function(){
			if(!this.q.value || this.q.value==PAGE.searchbox.initval){
				alert("Please enter a search term, such as a brand, product name, style or other keyword.");
				return false;
			}
		}
	
		PAGE.subscribebox.el = document.getElementById("SubscribeFormInput");
		PAGE.subscribebox.initval = PAGE.subscribebox.el.value;
		PAGE.subscribebox.el.onfocus = function()
		{	if(this.value==PAGE.subscribebox.initval) this.value = "";
		}
		PAGE.subscribebox.el.onblur = function()
		{	if(this.value=="") this.value = PAGE.subscribebox.initval;
		}
		
		PAGE.messagebox = document.getElementById('MessagesTop');
		
		PAGE.init_validation();
	}
	
	
	PAGE.messages_add = function(messages)
	{//	alert("appending");
		PAGE.MESSAGES = PAGE.MESSAGES.concat(messages);
	}
	
	PAGE.alert_msg = function(type, msg, js)
	{	PAGE.messagebox.innerHTML = '<div class="messagebox messagebox_'+type.toLowerCase()+'">'+msg+'</div>';
	}
	
	PAGE.messages_process = function()
	{	//alert('processing');
		var MSGS = PAGE.MESSAGES;
		PAGE.MESSAGES = [];

		for (i=0; i<MSGS.length; i++)
		{	msg = MSGS[i];
			switch (msg["to"])
			{	case "msgtop":
					PAGE.alert_msg(msg["code"], msg["msg"], msg["js"]);
				break;
				case "basket":
					wr = eval(msg["msg"]);
					BASKET.set_basket(wr[0], wr[1]);
					BASKET.update_minibasket();
					return true;
				break;
			}
		}
	}
	
	
	PAGE.init_validation = function()
	{	
		inputs = match_elements('//input');
		
		if (typeof inputs == "object")
		{	// alert('arrayk');
			for (k=0;k<inputs.length;k++)
			{	
				input = inputs[k];
				if (input.attributes["validation"])
				{	
					input.onblur = function() { field_validate(this, this.attributes["validation"].value); }
				}
			}
		}
	}
	
	PAGE.jump_searchpage = function(url)
	{	
		elem_order = document.getElementById('id_order');
		elem_total = document.getElementById('id_total');
		
		
		if (elem_order && elem_total && url!="")
		{	
			newrl = url.replace("%orderby%", elem_order.value);
			newrl = newrl.replace("%total%", elem_total.value);
			
			if (newrl!="" && window.location!=newrl)
			{	
				window.location = newrl;
			}
		}
	}
}


function AjaxConn()
{
	var xmlhttp, bComplete = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	catch (e) { try { xmlhttp = new XMLHttpRequest(); }
	catch (e) { xmlhttp = false; }}}
	if (!xmlhttp) return null;
	this.connect = function(sURL, sMethod, sVars, fnDone, bAsynch)
	{
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();
		
		if (bAsynch == null) bAsynch = true; //treat asynch as an optional argument
		
		try {
			if (sMethod == "GET")
			{
				xmlhttp.open(sMethod, sURL+"?"+sVars, (bAsynch == true));
				sVars = "";
			}
			else
			{
				xmlhttp.open(sMethod, sURL, (bAsynch == true));
				xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
				xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			}
			
			xmlhttp.onreadystatechange = function(){
				if (xmlhttp.readyState == 4 && !bComplete)
				{
					bComplete = true;
					fnDone(xmlhttp);
				}
			};
			xmlhttp.send(sVars);
			
			/**
			 * Firefox doesn't fire onreadystatechange for synchronous requests.
			 * See http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/
			 */
			var isGecko = (document.addEventListener) ? true : false;
			try {
				if (!bAsynch && isGecko && xmlhttp.onReadyStateChange == null) {
					bComplete = true;
					fnDone(xmlhttp);
					return true;
				}
			}
			catch (e) { return false; }
			/**
			 * End synchronous request patch
			 */
		}
		catch(z) { return false; }
		return true;
	};
	
	this.makeurl = function (pane, act, val, vars)
	{	ret = "pane="+pane+"&act="+act;
		if (val!="") { ret+= "&val="+val; }
		if (vars!="") { ret+= "&"+vars; }
		
		return ret;
	}
	
	this.server_connect = function (url, params, fnWhenDone, asynch, method)
	{	if (method=="") { method="GET"; }
		return this.connect(url, method, params, fnWhenDone, asynch);
	}
	
	return this;
}


var myConn = new AjaxConn();


var PRODUCT = {
	scrollzoom : false,
	scrollposX : 0,
	scrollposY : 0
};

/*
 * Bodged document.onload function executed on the product page to set up the object
 * (until such time as we can instantiate the product object within the page)
 */
function load_product(){
	
	document.body.onmousemove = function(event) { PRODUCT.scrollzoomimage(event); }
	document.body.onmouseup = function(event) { return PRODUCT.scrollzoomimage_off(event); }
	document.body.onmousedown = function(event) { return PRODUCT.scrollzoomimage_on(event); }
	
	PRODUCT.txtid = document.getElementById("id_product");
	PRODUCT.img = document.getElementById("ProductImage");
	PRODUCT.imgZ = document.getElementById("ProductZoomImage");
	PRODUCT.size = document.getElementById("id_size");
	PRODUCT.colour = document.getElementById("id_colour");
	PRODUCT.quantity = document.getElementById("id_quantity");
}

PRODUCT.add = function(){
	var txtid = PRODUCT.txtid.value;
	var size = PRODUCT.size.value;
	var colour = PRODUCT.colour.value;
	var quantity = PRODUCT.quantity.value;
	if(size && colour){
		//alert("Size: "+size+"\nColour: "+colour);return false;
		BASKET.add_product(txtid, size, colour, quantity);
	}else{
		if(!colour && !size) alert("Please select a colour and size");
		else if(!colour) alert("Please select a colour");
		else if(!size) alert("Please select a size");
	}
	return false;
}

/*
 * Handler function for colour selection widgets on product page
 */
PRODUCT.applycolour = function(colour){
	// Reset
	document.getElementById('SizeSelector').style.display='block';
	document.getElementById('SizeSelectorHeader').style.display='block';
	//document.getElementById("addbox").style.display="none";	
	var feedback = document.getElementById("feedback");
	feedback.innerHTML = "";
	// Reset Size Selection
	var resetel = document.getElementById("SizeSelector");
	for(i in resetel.childNodes) { if(typeof resetel.childNodes[i]=="object"){
		var s = resetel.childNodes[i];
		this.widgetstate(s, 0);
	} }
	document.getElementById("id_size").value = "";
	
	// Reset price to main price
	document.getElementById('price_large').innerHTML = "Price: <span class=\"price\"><abbr title=\"GBP\">&pound;</abbr>"+roundNumber(mainPrice,2)+"</span>";
	
	// Get the selected colour widget
	var cel = document.getElementById("select_colour_"+colour);
	// Get colour swatch container
	var el = document.getElementById("ColourSwatch");

	// Set the hidden field
	document.getElementById("id_colour").value = colour;
		
	// Update the product image
	this.findimage(colour);
	
	// Update the thumbnail images
	this.switchthumbimages(colour);

	// Reset colour widgets and mark active widget as selected
	// Takes current size selection into account if necessary
	for(i in el.childNodes) if(typeof el.childNodes[i]=="object"){
		var c = el.childNodes[i];
		if(this.size.value){
			var f = true;
			for(n in ColoursSizes[this.size.value]) if(c.id=="select_colour_"+ColoursSizes[this.size.value][n]){
				this.widgetstate(c, 1);
				f = false;
				break;
			}
			if(f) { this.widgetstate(c, 0); }
		}else this.widgetstate(c, 1);
	}
	this.widgetstate(cel, 2);
	/*
	// Check sizes for availability and reset selection where necessary
	var el = document.getElementById("SizeSelector");
	for(i in el.childNodes) if(typeof el.childNodes[i]=="object"){
		var s = el.childNodes[i];
		// f is for FOO
		var f = true;
		// Find whether the current size is available in the 
		// selected colour by looping available sizes array
		for(n in SizesColours[colour]) if(s.id=="select_size_"+SizesColours[colour][n]){
			// This one is available so enable the size widget
			// Note the conditional to check for previous size selection
	//		this.widgetstate(s, this.size.value==SizesColours[colour][n] ? 2 : 1);
			f = false;
			break;
		}
		// When true, means the size is NOT available in selected colour
		if(f){
			// Style the size widget
			this.widgetstate(s, 0);
			// Check to see if the [unavailable] size is the selected size
			if(s.id=="select_size_"+this.size.value){
				// Reset the field
				this.size.value = "";
			}
		}
	}
	*/
	return false;
}

/*
 * Handler function for size selection widgets on product page
 */
PRODUCT.applysize = function(size){
	document.getElementById("addbox").style.display="none";	
	var feedback = document.getElementById("feedback");
	feedback.innerHTML = "";
	// Get the selected size widget
	var sel = document.getElementById("select_size_"+size);
	// Get size widget container
	var el = document.getElementById("SizeSelector");
	
	// Set the hidden field
	document.getElementById("id_size").value = size;

	// Apply any price change modifier
	var thisPrice = roundNumber(mainPrice + SizePrices[size],2);
	document.getElementById('price_large').innerHTML = "Price: <span class=\"price\"><abbr title=\"GBP\">&pound;</abbr>"+thisPrice+"</span>";

	// Reset size widgets and mark active widget as selected
	// Takes current colour selection into account if necessary
	for(i in el.childNodes) if(typeof el.childNodes[i]=="object"){
		var s = el.childNodes[i];
		if(this.colour.value){
			var f = true;
			for(n in SizesColours[this.colour.value]) if(s.id=="select_size_"+SizesColours[this.colour.value][n]){
				this.widgetstate(s, 1);
				f = false;
				break;
			}
			if(s) { this.widgetstate(s, 0); }
		}else this.widgetstate(s, 1);
	}
	this.widgetstate(sel, 2);
	
	// Check colours for availability and reset selection where necessary
	var el = document.getElementById("ColourSwatch");
	for(i in el.childNodes) if(typeof el.childNodes[i]=="object"){
		var c = el.childNodes[i];
		var f = false;
		// Check whether current colour is available in the chosen size
		for(n in ColoursSizes[size]) if(document.getElementById("id_colour").value==ColoursSizes[size][n]){
			// Enable the colour widget if colour if found to be available
			// Note the conditional to check for previous colour selection
//			this.widgetstate(c, this.colour.value==ColoursSizes[size][n] ? 2 : 1);
			f = true;
			break;
		}
		// When true, the current colour is NOT available
		if(f){
			// so we style it as such
			//this.widgetstate(c, 0);
			feedback.innerHTML = "";
			document.getElementById("addbox").style.display="block";	
			// Reset the field if it's the selected colour
			//if(c.id=="select_colour_"+this.colour.value) { this.colour.value = ""; }
		} else {
			feedback.innerHTML = "";
			document.getElementById("addbox").style.display="none";
		}
		var g = false;
		// Check whether current colour is available in the chosen size
		for(n in ColoursSizesAwaiting[size]) if(document.getElementById("id_colour").value==ColoursSizesAwaiting[size][n]){
			// Enable the colour widget if colour if found to be available
			// Note the conditional to check for previous colour selection
//			this.widgetstate(c, this.colour.value==ColoursSizes[size][n] ? 2 : 1);
			g = true;
			break;
		}
		// When true, the current colour is NOT available
		if(g){
			// so we style it as such
			//this.widgetstate(c, 0);
			feedback.innerHTML = "Awaiting Stock (<a href=\"?section=stock\">set up stock alert email?</a>)";
			// Reset the field if it's the selected colour
			//if(c.id=="select_colour_"+this.colour.value) { this.colour.value = ""; }
		} else {
			if(!f) {
			feedback.innerHTML = "Sorry, this is not available.";
			}
		}
		
	}
	return false;
}

/*
 * Set colour/size widget state
 */
PRODUCT.widgetstate = function(el, state){
	switch(state){
		// Widget is not available (ie. colour/size combination not in stock)
		case 0:
			//el.style.opacity = 0.60;
			//el.style.filter = "alpha(opacity=60)";
			el.style.cursor = "pointer";
			el.style.borderColor = "transparent";
			break;
		// Widget is available but not selected (ie. in stock)
		case 1:
			//el.style.opacity = 1;
			//el.style.filter = "alpha(opacity=100)";
			el.style.cursor = "pointer";
			el.style.borderColor = "transparent";		
			break;
		// Widget is available and selected
		case 2:
			//el.style.opacity = 1;
			//el.style.filter = "alpha(opacity=100)";
			el.style.cursor = "pointer";
			el.style.borderColor = "red";
			break;
	}
}

/*
 * Finds the most appropriate product image for a given colour and optional group
 */
PRODUCT.findimage = function(colour, group){
	var img;
	for(i in ProductImages){
		img = ProductImages[i];
		if((typeof(group)=="undefined" && img[1] && img[2].toLowerCase()==colour.toLowerCase()) || (typeof(group)!="undefined" && img[0]==group && img[2].toLowerCase()==colour.toLowerCase()))
			return this.changeimage(i);
	}
	return false;
}

/*
 * Changes the current product image to the one specified (by productimage_id)
 */
PRODUCT.changeimage = function(id){
	var img = document.getElementById("ProductImage");
	var imgZ = document.getElementById("ProductZoomImage");
	img.src = "/images/products/"+ProductImages[id][3];
	imgZ.src = "/images/products/large/"+ProductImages[id][3];
	if(this.iszoomed()) this.switchzoomimage();
	return true;
}

/*
 * Shows/hides the zoom image for a product
 */
PRODUCT.switchzoomimage = function(){
	var ctr = document.getElementById("ProductImageContainer");
	var img = document.getElementById("ProductImage");
	var imgZ = document.getElementById("ProductZoomImage");
	var control = document.getElementById("ProductImageZoomControl");
	
	if(this.iszoomed()){
		img.style.display = "block";
		imgZ.style.display = "none";
		control.innerHTML = "Zoom +";
	}else{
		img.style.display = "none";
		imgZ.style.display = "block";
	//	alert(0 - (imgZ.width / 2) + (ctr.offsetWidth / 2));
		imgZ.style.left = Math.floor(ctr.offsetWidth / 2 - imgZ.width / 2) + "px";
		imgZ.style.top = "0px";
		control.innerHTML = "Zoom -";
	}
	return true;
	/*
	if(img.src.indexOf("/large/")==-1){
		img.src = img.src.replace(/\/products\//, "/products/large/");
		img.style.width = "870px";
		img.style.height = "1110px";
		control.innerHTML = "- Zoom";
		PRODUCT.makedraggable();
	}else{
		img.src = img.src.replace(/\/large\//, "/");
		control.innerHTML = "+ Zoom";
	}
	*/
}

/*
 * Returns true if the current image is zoomed, false if not
 * For determining whether the image needs resetting on colour change
 */
PRODUCT.iszoomed = function(){
	var imgZ = document.getElementById("ProductZoomImage");
	return imgZ.style.display=="none" || !imgZ.style.display ? false : true;
}

/*
 * Attaches an event handler to the product image to make it draggable
 */
PRODUCT.makedraggable = function(){
	img.onmousedown = function(ev){
		alert("YOU CLICK DOWN");
	}
	img.onmousedown = function(ev){
		alert("UP YOU HAVE CLICKED");
	}
}

/*
 * Changes the product thumbnails to the specified colour
 */
PRODUCT.switchthumbimages = function(colour){
	var cont = document.getElementById("ProductThumbs");
	var img;
	var defaulto = false;
	cont.innerHTML = "";
	while(cont.childNodes[0])
		cont.removeChild(cont.childNodes[0]);
	for(i in ProductImages){
		img = ProductImages[i];
		if(img[2]==colour){
			if(defaulto) defaulto = false;
			else{
				var thumb = new Image();
				thumb.src = "/images/products/thumbs/"+img[3];
				eval("thumb.onclick = function(){ PRODUCT.changeimage("+i+"); }");
				cont.appendChild(thumb);
			}
		}
	}
}

PRODUCT.scrollzoomimage_on = function(e){
	var target;
	if(!e) var e = window.event;
  if(e.target) target = e.target;
  else if(e.srcElement) target = e.srcElement;
	if(target.nodeType==3) target = target.parentNode;

	if(target.id=="ProductZoomImage"){
		this.scrollposX = e.screenX;
		this.scrollposY = e.screenY;
		this.scrollzoom = true;
		target.ondragstart = function(){ return false } 
		target.onselectstart = function(){ return false } 
		//e.cancelBubble = false;
		e.returnValue = false;
		return false;
	}else return true;
}

PRODUCT.scrollzoomimage_off = function(e){
	var target;
	if(!e) var e = window.event;
  if(e.target) target = e.target;
  else if(e.srcElement) target = e.srcElement;
	if(target.nodeType==3) target = target.parentNode;


	if(target.id=="ProductZoomImage" || this.scrollzoom){
		this.scrollzoom = false;
		this.scrollposX = 0;
		this.scrollposY = 0;
		e.returnValue = false;
		return false;
	}else return true;
}

PRODUCT.scrollzoomimage = function(e){
	if(!e) var e = window.event;
	var target = document.getElementById("ProductZoomImage");

	if(this.scrollzoom && target.width > target.parentNode.offsetWidth && target.height > target.parentNode.offsetHeight){
		var left = target.style.left.replace(/[^0-9.-]/g, "") - (this.scrollposX - e.screenX);
		var top = target.style.top.replace(/[^0-9.-]/g, "") - (this.scrollposY - e.screenY);
		var leftMin = 0 - target.width + target.parentNode.offsetWidth;
		var topMin = 0 - target.height + target.parentNode.offsetHeight;
		if(left > 0)
			target.style.left = "0px";
		else if(left < leftMin)
			target.style.left = leftMin + "px";
		else
			target.style.left = left + "px";
		if(top > 0)
			target.style.top = "0px";
		else if(top < topMin)
			target.style.top = topMin + "px";
		else
			target.style.top = top + "px";
		this.scrollposX = e.screenX;
		this.scrollposY = e.screenY;
	}
}




var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();


XML = {};
/**
 * XML.XPathExpression is a class that encapsulates an XPath query and its
 * associated namespace prefix-to-URL mapping. Once an XML.XPathExpression
 * object has been created, it can be evaluated one or more times (in one
 * or more contexts) using the getNode() or getNodes() methods.
 *
 * The first argument to this constructor is the text of the XPath expression.
 *
 * If the expression includes any XML namespaces, the second argument must
 * be a JavaScript object that maps namespace prefixes to the URLs that define
 * those namespaces. The properties of this object are the prefixes, and
 * the values of those properties are the URLs.
 */
XML.XPathExpression = function(xpathText, namespaces) {
    this.xpathText = xpathText;    // Save the text of the expression
    this.namespaces = namespaces;  // And the namespace mapping
    if (document.createExpression) {
        // If we're in a W3C-compliant browser, use the W3C API
        // to compile the text of the XPath query
        this.xpathExpr =
            document.createExpression(xpathText,
                                      // This function is passed a
                                      // namespace prefix and returns the URL.
                                      function(prefix) {
                                          return namespaces[prefix];
                                      });
    }
    else {
        // Otherwise, we assume for now that we're in IE and convert the
        // namespaces object into the textual form that IE requires.
        this.namespaceString = "";
        if (namespaces != null) {
            for(var prefix in namespaces) {
                // Add a space if there is already something there
                if (this.namespaceString) this.namespaceString += ' ';
                // And add the namespace
                this.namespaceString += 'xmlns:' + prefix + '="' +
                    namespaces[prefix] + '"';
            }
        }
    }
};
/**
 * This is the getNodes() method of XML.XPathExpression. It evaluates the
 * XPath expression in the specified context. The context argument should
 * be a Document or Element object. The return value is an array
 * or array-like object containing the nodes that match the expression.
 */
XML.XPathExpression.prototype.getNodes = function(context) {
    if (this.xpathExpr) {
        // If we are in a W3C-compliant browser, we compiled the
        // expression in the constructor. We now evaluate that compiled
        // expression in the specified context.
        var result =
            this.xpathExpr.evaluate(context,
                                    // This is the result type we want
                                    XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
                                    null);
        // Copy the results we get into an array.
        var a = new Array(result.snapshotLength);
        for(var i = 0; i < result.snapshotLength; i++) {
            a[i] = result.snapshotItem(i);
        }
        return a;
    }
    else {
        // If we are not in a W3C-compliant browser, attempt to evaluate
        // the expression using the IE API.
        try {
            // We need the Document object to specify namespaces
            var doc = context.ownerDocument;
            // If the context doesn't have ownerDocument, it is the Document
            if (doc == null) doc = context;
            // This is IE-specific magic to specify prefix-to-URL mapping
            doc.setProperty("SelectionLanguage", "XPath");
            doc.setProperty("SelectionNamespaces", this.namespaceString);
            // In IE, the context must be an Element not a Document,
            // so if context is a document, use documentElement instead
            if (context == doc) context = doc.documentElement;
            // Now use the IE method selectNodes() to evaluate the expression
            return context.selectNodes(this.xpathText);
        }
        catch(e) {
            // If the IE API doesn't work, we just give up
            throw "XPath not supported by this browser.";
        }
    }
}
/**
 * This is the getNode() method of XML.XPathExpression. It evaluates the
 * XPath expression in the specified context and returns a single matching
 * node (or null if no node matches). If more than one node matches,
 * this method returns the first one in the document.
 * The implementation differs from getNodes() only in the return type.
 */
XML.XPathExpression.prototype.getNode = function(context) {
    if (this.xpathExpr) {
        var result =
            this.xpathExpr.evaluate(context,
                                    // We just want the first match
                                    XPathResult.FIRST_ORDERED_NODE_TYPE,
                                    null);
        return result.singleNodeValue;
    }
    else {
        try {
            var doc = context.ownerDocument;
            if (doc == null) doc = context;
            doc.setProperty("SelectionLanguage", "XPath");
            doc.setProperty("SelectionNamespaces", this.namespaceString);
            if (context == doc) context = doc.documentElement;
            // In IE call selectSingleNode instead of selectNodes
            return context.selectSingleNode(this.xpathText);
        }
        catch(e) {
            throw "XPath not supported by this browser.";
        }
    }
};
// A utility to create an XML.XPathExpression and call getNodes() on it
XML.getNodes = function(context, xpathExpr, namespaces) {
    return (new XML.XPathExpression(xpathExpr, namespaces)).getNodes(context);
};
// A utility to create an XML.XPathExpression and call getNode() on it
XML.getNode  = function(context, xpathExpr, namespaces) {
    return (new XML.XPathExpression(xpathExpr, namespaces)).getNode(context);
};



function record_click(id)
{	
	img = new Image();
	img.src = '/tracker.php?sec=advert&id='+id;
	return true;
}


//pop-up

function popOpen(id) {
	var topOffset = 160;
	setSize(topOffset);
	var overShade = document.getElementById(id);
	var topPad =  pos+topOffset;
	// height-padding = div height
	overShade.style.height = (ph - topPad) + 'px'; /* remove topPad from height */
	overShade.style.width = pw + 'px';
	overShade.style.paddingTop = topPad + 'px';
	overShade.style.display = 'block'; 	
	if (document.all && !navigator.appVersion.match(/MSIE 7.0/) && !navigator.appVersion.match(/MSIE 8.0/) && !navigator.userAgent.match('Opera')) { 
		coverSelects(overShade);
	}
	
}
function popClose(id) {
	
	var fObj = document.getElementById(id);
	fObj.style.display = "";
	//end Added by Sarun
	
	if (document.all && !navigator.appVersion.match(/MSIE 7.0/)  && !navigator.appVersion.match(/MSIE 8.0/) && !navigator.userAgent.match('Opera')) {
		document.getElementById("popup-cover").outerHTML = "";
	}
		
}

function setSize(topOffset) { /* sets size of shade */
	if (window.pageYOffset != null) { /* moz and safari */
		pos = window.pageYOffset;
		ph = document.documentElement.scrollHeight;
		pw = document.documentElement.scrollWidth;
		if (document.body.scrollHeight > document.documentElement.scrollHeight) {
			ph = document.body.scrollHeight;
			pw = document.body.scrollWidth;
		}
	} else if (document.documentElement.scrollTop > document.body.scrollTop) { /* ie, catch if Standards compliance mode */
		pos = document.documentElement.scrollTop;
		ph = document.documentElement.scrollHeight;
		pw = document.documentElement.scrollWidth;
		if (document.documentElement.clientHeight > document.documentElement.scrollHeight) {
			ph = document.documentElement.clientHeight;
		}
	} else if (document.body != null) { /* if IE 5.5 */
		pos = document.body.scrollTop;
		ph = document.body.scrollHeight;
		pw = document.body.scrollWidth;
		if (document.documentElement.scrollHeight > document.body.scrollHeight) {
			ph = document.documentElement.scrollHeight;
		}
		ph = ph + pos + topOffset; /* fix box model */
	}
}	

/* covers select form elements with iframe in IE 6&< so they do not show through the popup */
function coverSelects(par) {
		var covHeight = document.body.scrollHeight+"px"; // add the negative margin to the height
		var coverFrame = "<IFRAME id='pop-up-cover' style='";
		coverFrame = coverFrame + "height:"+covHeight+";' ";
		coverFrame = coverFrame + "src='javascript:false;' frameBorder='0' scrolling='no'></IFRAME>";
		par.insertAdjacentHTML("afterEnd",coverFrame); // create new iframe that is the size of the popup window
}

jump_searchpage = function(url, order, total)
{	
	if (url!="" && order!="" && total!="")
	{	
		newrl = url.replace("%orderby%", order);
		newrl = newrl.replace("%total%", total);
		
		if (newrl!="" && window.location!=newrl)
		{	
			window.location = newrl;
		}
	}
}

change_image = function(src) { // Preload Images
	document.getElementById('productimage').style.width="66px";
	document.getElementById('productimage').style.height="66px";
	document.getElementById('productimage').src="/images/loader.gif";
	document.getElementById('productimage').style.paddingLeft="167px";
	document.getElementById('productimage').style.paddingTop="167px";
	var objImagePreloader = new Image();
	objImagePreloader.src = src;
	if(objImagePreloader.complete) {
		_change_image(src,objImagePreloader.width,objImagePreloader.height);
	} else {
		objImagePreloader.onload = function() {
			_change_image(src,objImagePreloader.width,objImagePreloader.height);
			objImagePreloader.onload = function(){};    
         }
	}
}

_change_image = function(src,width,height) { // Centre within div
	img = document.getElementById('productimage');
	var maxwidth = 400;
	var maxheight = 400;
	if(width<maxwidth) {
		img.style.paddingLeft = parseInt((maxwidth-width)/2)+"px";	
	} else {
		img.style.paddingLeft = "0px";
	}
	if(height<maxheight) {
		img.style.paddingTop = parseInt((maxheight-height)/2)+"px";	
	} else {
		img.style.paddingTop = "0px";
	}
	img.src=src;
	img.style.width=width+"px";
	img.style.height=height+"px";
}

load_form = function(url, vars, destination)
{	
	var fn = function(res)
	{	
		if (res.responseText)
		{	
			el = document.getElementById("MainForm");
			if (el) { el.innerHTML = res.responseText; }
		}
	}
	
	r = myConn.connect(url, 'get', vars, fn);
}