// JavaScript Document

var addedId;
var aJax = false;
var iPid = 0;
var iList;
var iCurrent = -1
var iTimeoutId = 0;


function setColour(id, col) {
	
	var variat = document.getElementById("variation_general");
	var divtop = document.getElementById("vantop");
	var divbot = document.getElementById("vanbottom");
	var divtopcol = document.getElementById("topColDivCol");
	var divbotcol = document.getElementById("botColDivCol");

	if (id=="top") {
		if (divtop) divtop.style.backgroundColor=col;
		if (divtopcol) divtopcol.innerHTML=col;
	}
	else {
		if (divbot) divbot.style.backgroundColor=col;
		if (divbotcol) divbotcol.innerHTML=col;
	}
		
	if (variat && divtopcol && divbotcol)
		variat.value = "Top Colour: " + divtopcol.innerHTML + ", Bottom Colour: " + divbotcol.innerHTML;
}

function getAjaxConnection() {
	try {
		aJax = new XMLHttpRequest();
	} catch (trymicrosoft) {
		try {
			aJax = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				aJax = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				aJax = false;
			}  
		}
	}
	if (!aJax) alert("Error initializing AJAX");
}


function subcatNav(obj) {
	var sRef = obj.options[obj.selectedIndex].value;
	location.href = sRef;
}

function searchBlur() {
	var txt = document.getElementById("searchtext");
	if (txt) {
		if (txt.value == '') {
			txt.value='Search'
		}
		txt.className = "searchGrey"
	}
}


function searchFocus() {
	var txt = document.getElementById("searchtext");
	if (txt) {
		if (txt.value == 'Search') {
			txt.value=''
		}
		txt.className = "searchBlack"
	}
}

function CheckBasketAdd(sBtn) {
	if (!testSessionCookie()) {
		alert("You will need to enable cookies before you can add products to your shopping basket");
		return false;
	}
	else {
		addedId=sBtn;
		return true;
	}
}


function showFilter(sDiv) {
	var oDiv = document.getElementById(sDiv);
	var oRef = document.getElementById("a_" + sDiv);
	if (oDiv && oRef) {
		oDiv.style.display = "";
		oRef.style.display = "none";
	}
}


function playWatchMovie(sCodeNumber) {
	var div = document.getElementById("swfdiv-" + sCodeNumber);
	
	if (div) {
		var obj = "<div style='width:256px;'><div style='float:left;width:205px;'><p style='margin:0px;font-size:9pt;'><span style='padding-right:10px;'>Colours in this 360<sup>o</sup> may vary due to lighting and your monitor</span></p></div><div style='float:left; width:45px;'><a href='JavaScript:hideWatchMovie(" + String.fromCharCode(34) + sCodeNumber + String.fromCharCode(34) + ");'><img src='/images/close.gif' border='0' alt='Close 360'></a></div>";
		obj += "<div style='float:left;width:256px;'><object width='256' height='340' type='application/x-shockwave-flash' data='/watches/" + sCodeNumber + ".swf'>";
		obj += "<param value='/watches/" + sCodeNumber + ".swf' name='movie'>"
		obj += "</object></div></div>"
		div.innerHTML = obj;
		if (div.style.display=="none") {
			div.style.display = ""; 
			div.width = "256px"; 
		}
		else {
			div.style.display = "none";
		}
	}
}

function hideWatchMovie(sCodeNumber) {
	var div = document.getElementById("swfdiv-" + sCodeNumber);
	if (div) {
		div.style.display = "none";
	}	
}


function setFilter(sURL) {
	location.href = sURL;
}


function removeFromBasket(id) {

	getAjaxConnection();
	
	if (aJax) {
		var url = "/includes/getSmallBasket.asp?rem=" + String(id) + "&" + Date();
		aJax.open("GET", url, true);
		
		aJax.onreadystatechange = setSmallBasket;
		aJax.send(null);
		location.reload(true);
	}
}

function updateSmallBasket() {
	var div = document.getElementById("smallbasketDiv");

	getAjaxConnection();
	
	if (aJax && div) {
		var url = "/includes/getSmallBasket.asp?" + Date();
		aJax.open("GET", url, true);
		aJax.onreadystatechange = setSmallBasket;
		aJax.send(null);
	}
}

function setSmallBasket() {
	if (aJax.readyState == 4 && aJax.responseText != "") {
		var div = document.getElementById("smallbasketDiv");
		if (div) {
//			document.write(aJax.responseText);
			div.innerHTML = aJax.responseText;
			showBasketDiv();
		}
		aJax = false;
	}
}

function setPageLocation() {
	var sel = document.getElementById("topten");
	if (sel) location.href=sel.value;
}

function setVariationImage(oObj, iProd) {
	
	iPid = iProd;
	iList = oObj.options[oObj.selectedIndex].value;
	getAjaxConnection();
	
	if (aJax) {
		var url = "/includes/getnewprice.asp?id=" + iList + "&pid=" + iPid + "&d=" + Date();
		aJax.open("GET", url, true);
		aJax.onreadystatechange = updateProductPrice;
		aJax.send(null);
	}
}
	
function updateProductPrice() {
	if (aJax.readyState == 4 && aJax.status == 200) {
		var img = document.getElementById("productPrice-" + String(iPid));
		if (img) img.innerHTML = aJax.responseText;

		var url = "/includes/loadimagegroup.asp?id=" + iList + "&pid=" + iPid + "&d=" + Date();
		aJax.open("GET", url, true);
		aJax.onreadystatechange = showImageGroup;
		aJax.send(null);
	}
}

function showImageGroup() {
	if (aJax.readyState == 4 && aJax.status == 200) {
		var img = document.getElementById("imageDisplayRow");
		if (img) img.innerHTML = aJax.responseText;
	}
}


function advsearch() {
	document.advsearchform.submit();
}

function invalidCaptcha() {
	document.getElementById("feedbackerr").style.display = "";
	document.getElementById("systheform").style.display = "";
	sysReloadCa();
}

function feedbackThanks() {
	document.getElementById("systhanks").innerHTML = "<b>Thank you for your feedback, it's much appreciated.</b>";
	document.getElementById("systheform").style.display="none";
	document.getElementById("feedbackerr").style.display="none";
}

function sysReloadCa() {
	document.getElementById('syscaimg').src='/includes/caimage.asp?' + Date();
}

function sysReloadCa1() {
	document.getElementById('sysca1img').src='/includes/caimage.asp?' + Date();
}


function callBack(valid) {
	var tbl = document.getElementById("callbacktable");
	var spn = document.getElementById("callbackmessage");
	var frm = document.getElementById("callback-form");
	if (valid) {
		if (tbl && spn) {
			tbl.style.display="none";
			frm.style.display="none";
			spn.innerHTML = "<p style='color:maroon;text-align:left;'>Thank you for your interest, we will contact you very soon</p>"
		}
	}
	else {
		if (tbl && spn) {
			tbl.style.display="";
			frm.style.display="";
			spn.innerHTML = "<p style='color:red;text-align:left;'>Please complete all fields marked with a red asterix <sup>*</sup></p>"
		}
	}	
}

function notAdded(sTxt) {
	alert(sTxt);
}

function popup(img) {
	result = window.open("/viewimage.asp?img=" + img, "prodimg", "height=350,width=350,scrollbars,resizable");
	var cr = String.fromCharCode(13);
	if (result == null) alert("You browser is currently blocking Popups." + cr + cr + "Please change your settings to allow popups on this site." + cr + "Alternatively just click on 'more details' to view the images.");
}

function sImgR() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function loadImg() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=loadImg.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function swapImg() { //v3.0
  var i,j=0,x,a=swapImg.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function GetXmlHttpObject() {
	var xmlHttp=null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest(); }
	catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e) {
				alert("Sorry, your browser does not support AJAX.");
				xmlHttp=null; }
		}
	}
	return xmlHttp;
}

function writeIn(pre, dom1, ext) {
	var lt = String.fromCharCode(60);
	var gt = String.fromCharCode(62);
	var at = String.fromCharCode(64);
	var qt = String.fromCharCode(34);
	var eq = String.fromCharCode(61);
	
	var act1 = String.fromCharCode(109) + "a";
	var act2 = "i" + String.fromCharCode(108);
	var act3 = "to";
	var act4 = String.fromCharCode(58);
	
	var lnk1 = lt + String.fromCharCode(97) + " " + String.fromCharCode(104) + String.fromCharCode(114) + String.fromCharCode(101) + String.fromCharCode(102) + eq + qt + act1 + act2 + act3 + act4;
	var lnk2 = lt + String.fromCharCode(47) + String.fromCharCode(97) + gt;
	
	var ad = lnk1 + pre + at + dom1 + ext + qt + gt + pre + at + dom1 + ext + lnk2;
	var ol = document.getElementById("kont");
	ol.innerHTML = ad;
}

/*==============================================================================

    Routines written by John Gardner - 2003 - 2005

    See www.braemoor.co.uk/software for information about more freeware
    available.

/*==============================================================================

Routine to write a session cookie

    Parameters:
        cookieName        Cookie name
        cookieValue       Cookie Value
    
    Return value:
        true              Session cookie written successfullly
        false             Failed - persistent cookies are not enabled

   e.g. if (writeSessionCookie("pans","drizzle") then
           alert ("Session cookie written");
        else
           alert ("Sorry - Session cookies not enabled");
*/

function writeSessionCookie (cookieName, cookieValue) {
  if (testSessionCookie()) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
  }
  else return false;
}

/*==============================================================================

Routine to get the current value of a cookie

    Parameters:
        cookieName        Cookie name
    
    Return value:
        false             Failed - no such cookie
        value             Value of the retrieved cookie

   e.g. if (!getCookieValue("pans") then  {
           cookieValue = getCoookieValue ("pans2);
        }
*/

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

/*==============================================================================

Routine to see if session cookies are enabled

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testSessionCookie())
           alert ("Session coookies are enabled");
        else
           alert ("Session coookies are not enabled");
*/

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

/*==============================================================================

Routine to see of persistent cookies are allowed:

    Parameters:
        None
    
    Return value:
        true              Session cookies are enabled
        false             Session cookies are not enabled

   e.g. if (testPersistentCookie()) then
           alert ("Persistent coookies are enabled");
        else
           alert ("Persistent coookies are not enabled");
*/

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  if (getCookieValue ("testPersistentCookie")=="Enabled")
    return true  
  else 
    return false;
}

/*==============================================================================

Routine to write a persistent cookie

    Parameters:
        CookieName        Cookie name
        CookieValue       Cookie Value
        periodType        "years","months","days","hours", "minutes"
        offset            Number of units specified in periodType
    
    Return value:
        true              Persistent cookie written successfullly
        false             Failed - persistent cookies are not enabled
    
    e.g. writePersistentCookie ("Session", id, "years", 1);
*/       

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;
  
  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  } 
  
  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}  

/*==============================================================================

Routine to delete a persistent cookie

    Parameters:
        CookieName        Cookie name
    
    Return value:
        true              Persistent cookie marked for deletion
    
    e.g. deleteCookie ("Session");
*/    

function deleteCookie (cookieName) {

  if (getCookieValue (cookieName)) writePersistentCookie (cookieName,"Pending delete","years", -1);  
  return true;     
}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function showAdsense() {
	var cl = document.getElementById("adsensediv").className;
	if (cl=="adsense") cl="showadsense"; else cl="adsense";
	document.getElementById("adsensediv").className=cl;
}

function checkCaps(oObj) {
	var val = new String(oObj.value), sChar, iasc;
	var sentence = new String(""), upperNext = true;
	var i, count=0, len=val.length, perc=0.5;
	
	for (i=0;i<len;i++) {
		sChar = val.charAt(i);
		iasc = val.charCodeAt(i);
		if (sChar==sChar.toUpperCase()) count++;
		if (sChar=="!" || sChar=="?" || sChar=="." || iasc==10 || iasc==13) upperNext=true;
		if ((iasc >= 65 && iasc <= 90) || (iasc >= 97 && iasc <= 122) || (iasc >= 48 && iasc <= 57)) {
			if (upperNext) {
				sChar= sChar.toUpperCase();
				upperNext = false;
			}
			else {
				sChar = sChar.toLowerCase();
			}
		}
		sentence = sentence + sChar;
	}
	
	if ((count/len) > perc) {
		// number of caps exceeds limit
		oObj.value = sentence;
		alert("Unfortunately you can't use excessive CAPITAL LETTERS in your advert" + String.fromCharCode(10) + "We have converted this for you so please check this before proceeding.");
		oObj.focus();
		return false;
	}
	else {
		return true;
	}
}

function toggleStockRegister(sObj) {
	var obj = document.getElementById(sObj);
	if (obj) {
		if (obj.style.display=="")
			obj.style.display="none";
		else
			obj.style.display="";
	}
}

function submitAlertRegistration(sPid) {
	var ofrm = document.getElementById("basketframe");
	var oeml = document.getElementById("alertemail");
	if (ofrm && oeml) ofrm.src = '/stockregister.asp?pid=' + sPid + '&eml=' + oeml.value;
}


function changeImg(src) {
	var spc = document.getElementById("productimgcvr");
	var img = document.getElementById("productimg")
	
	img.src = src;
	spc.height = img.height;
	spc.width = img.width;
}

function zoomImg(coy) {
	var spc = document.getElementById("productimgcvr");
	var img = document.getElementById("productimg")
	var zm = document.getElementById("pr_zoom");
	var newZm = "pr_zoom.gif";
	
	var newImg = document.getElementById("prodimg1");
	
	if (img.src==newImg.src) {
		var newImg = document.getElementById("prodimg2");
		newZm = "pr_zoomDwn.gif";
	}
	zm.src = "/assets/" + coy + "/images/" + newZm;
	img.src = newImg.src;
	spc.height = img.height;
	spc.width = img.width;
}


function changePImg(file, hgt, wdth) {
	var cel = document.getElementById("productimgcell");
	var spc = document.getElementById("productimgcvr");
	
	cel.style.backgroundImage = "url('/assets/products/" + file + "')";
	spc.height = hgt;
	spc.width = wdth;
	alert("Testing " + cel + " - " + "url('/assets/products/" + file + "')");
}

function changePImgSrc(file, hgt, wdth) {
	var cel = document.getElementById("productimgcell");
	var spc = document.getElementById("productimgcvr");
	
	spc.src = "/assets/products/" + file;
	spc.height = hgt;
	spc.width = wdth;
}

function isEmail(emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		alert("Please check your email address (" + emailStr + ") in particular the @'s and .'s");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		alert("Please check your email address, the name before the '@' contains some invalid characters.");
		return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
		alert("Please check your email address, the domain name contains some invalid characters.");
		return false;
	   }
	}
	
	if (user.match(userPat)==null) {
		alert("Please check your email address, the name before the '@' appears to be invalid.");
		return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
		if (IPArray[i]>255) {
		alert("Please check your email address, the destination IP address is invalid.");
		return false;
	   }
	}
	return true;
	}
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
		alert("Please check your email address, the domain name does not appear to be valid.");
		return false;
	   }
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("Please check your email address, it should end in a well-known domain or two letter country.");
		return false;
	}
	
	if (len<2) {
		alert("Please check your email address, it is missing a hostname.");
		return false;
	}
	
	return true;
}

// Custom Functions 

function showBasketDiv() {

	var div = document.getElementById("smallbasket");
	var downarrow = document.getElementById("downarrow");
	var uparrow = document.getElementById("uparrow");
	
	if(div) {
		if(div.style.display == "none") {
			div.style.display = "block";
			if(downarrow && uparrow) {
				downarrow.style.display = "none";
				uparrow.style.display = "block";
			}
		}
		else {
			div.style.display = "none";	
			if(downarrow && uparrow) {
				downarrow.style.display = "block";
				uparrow.style.display = "none";
			}
		}
	}
	
}

function hideBasketDiv() {
	var arrowimage = document.getElementById("arrowimage");
	var div = document.getElementById("smallbasket");
	var downarrow = document.getElementById("downarrow");
	var uparrow = document.getElementById("uparrow");
	
	if(downarrow && uparrow) {
		downarrow.style.display = "block";
		uparrow.style.display = "none";
	}
	if(div) {
		div.style.display = "none";	 
		
	}
	
}

function setButton() {
	if (addedId!="") {
		swapImg(addedId, '', '<%= gsInBasketImg%>');
	}
}



function setVariationValue(sVar, iVal, iProd) {
	
	var sel = document.getElementById("variation_" + sVar);
	
	if (sel) {
		sel.value=iVal;
		setVariationImage(sel, iProd);
	}
}

function showTab(iTab) {
	var desc = document.getElementById("pdescription");
	var spec = document.getElementById("pspecification");
	var buy = document.getElementById("pbuywith");
	var call = document.getElementById("pcallback");
	var linkDesc = document.getElementById("pdesclink");
	var linkSpec = document.getElementById("pspeclink");
	var linkBuy = document.getElementById("pbuylink");
	var linkCall = document.getElementById("pcalllink");
	
	if (desc && spec && buy) {
		switch (iTab) {
			case "desc" :
				desc.style.display = "";
				spec.style.display = "none";
				buy.style.display = "none";
				call.style.display = "none";
				
				linkDesc.className = "selected";
				linkSpec.className = "";
				linkBuy.className = "";
				linkCall.className = "";
				break;
				
			case "spec" :
				desc.style.display = "none";
				spec.style.display = "";
				buy.style.display = "none";
				call.style.display = "none";
				
				linkDesc.className = "";
				linkSpec.className = "selected";
				linkBuy.className = "";
				linkCall.className = "";
				break;
				
			case "buy" :
				desc.style.display = "none";
				spec.style.display = "none";
				buy.style.display = "";
				call.style.display = "none";
				
				linkDesc.className = "";
				linkSpec.className = "";
				linkBuy.className = "selected";
				linkCall.className = "";
				break;
			case "call" :
				desc.style.display = "none";
				spec.style.display = "none";
				buy.style.display = "none";
				call.style.display = "";
				
				linkDesc.className = "";
				linkSpec.className = "";
				linkBuy.className = "";
				linkCall.className = "selected";
				break;
		}
	}
}

function showDiv(sDiv) {

	var div = document.getElementById(sDiv+"-links");
	var arrow = document.getElementById(sDiv+"-arrow");
	
	if(div) {
		if(div.style.display == "none") {
			div.style.display = "block";
			arrow.className = "right-arrow";
		}
		else {
			div.style.display = "none";	
			arrow.className = "down-arrow";
		}
	}
}

function ShowImage(sThumbContainer,sPreviewContainer) {
	
	
	for(i=1;i <= 10; i++) {
		if(document.getElementById("thumb_" + i)) {
			document.getElementById("thumb_" + i).style.backgroundColor = "White";
		}
		if(document.getElementById("ThumbContainer_" + i)) {
			document.getElementById("ThumbContainer_" + i).style.display = "none";
		}
	}
	
	var ThumbContainer = document.getElementById(sThumbContainer);
	var PreviewContainer = document.getElementById(sPreviewContainer);
	
	if(ThumbContainer) {
		PreviewContainer.style.display = "block";
		ThumbContainer.style.backgroundColor = "Black";
	}
}


/**
 * Formats the number according to the 'format' string; adherses to the american number standard where a comma is inserted after every 3 digits.
 *  note: there should be only 1 contiguous number in the format, where a number consists of digits, period, and commas
 *        any other characters can be wrapped around this number, including '$', '%', or text
 *        examples (123456.789):
 *          '0' - (123456) show only digits, no precision
 *          '0.00' - (123456.78) show only digits, 2 precision
 *          '0.0000' - (123456.7890) show only digits, 4 precision
 *          '0,000' - (123,456) show comma and digits, no precision
 *          '0,000.00' - (123,456.78) show comma and digits, 2 precision
 *          '0,0.00' - (123,456.78) shortcut method, show comma and digits, 2 precision
 *
 * @method format
 * @param format {string} the way you would like to format this text
 * @return {string} the formatted number
 * @public
 */
Number.prototype.format = function(format) {
 
	var hasComma = -1 < format.indexOf(','),
		psplit = format.stripNonNumeric().split('.'),
		that = this;
 
	// compute precision
	if (1 < psplit.length) {
		// fix number precision
		that = that.toFixed(psplit[1].length);
	}
	// error: too many periods
	else if (2 < psplit.length) {
		throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
	}
	// remove precision
	else {
		that = that.toFixed(0);
	}
 
	// get the string now that precision is correct
	var fnum = that.toString();
 
	// format has comma, then compute commas
	if (hasComma) {
		// remove precision for computation
		psplit = fnum.split('.');
 
		var cnum = psplit[0],
			parr = [],
			j = cnum.length,
			m = Math.floor(j / 3),
			n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
 
		// break the number into chunks of 3 digits; first chunk may be less than 3
		for (var i = 0; i < j; i += n) {
			if (i != 0) {n = 3;}
			parr[parr.length] = cnum.substr(i, n);
			m -= 1;
		}
 
		// put chunks back together, separated by comma
		fnum = parr.join(',');
 
		// add the precision back in
		if (psplit[1]) {fnum += '.' + psplit[1];}
	}
 
	// replace the number portion of the format with fnum
	return format.replace(/[d,?.?]+/, fnum);
};

function submitform(formId){
	document.getElementById(formId).submit()
}

function setVariationId(id, nme) {
	var vari=document.getElementById("variationid");
	if (vari) vari.value = id;

	var varn=document.getElementById("variation_" + nme);
	if (varn) varn.value = id;
}
// Shoe & Boot - Homepage banner switch
function switchBanner(sId){
	var placeholder = document.getElementById("rotate-banners");
	var filePath = "/assets/shoe01_50/homepage-banners/";
	var bannerLink = document.getElementById("rotate-link")
	
	var sowerby = document.getElementById("sowerby");
	var loake = document.getElementById("loake");
	var john_white = document.getElementById("john-white");
	var sanders = document.getElementById("sanders");
	var barker = document.getElementById("barker");
	var ariat = document.getElementById("ariat");
	var crocs = document.getElementById("crocs");
	var dr_martens = document.getElementById("dr-martens");
	
	switch(sId){
		case "sowerby":
			sowerby.src = filePath+"/hp-sowerby-selected.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 0;
			bannerLink.href = "/sowerby.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-sowerby.jpg)";
		break;	
		case "loake":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake-selected.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 1;
			bannerLink.href = "/loake.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-loake.jpg)";
		break;
		case "john-white":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white-selected.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 2;
			bannerLink.href = "/John-White.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-john-white.jpg)";
		break;
		case "sanders":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders-selected.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 3;
			bannerLink.href = "/sanders.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-sanders.jpg)";
		break;
		case "barker":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker-selected.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 4;
			bannerLink.href = "/barkers.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-barker.jpg)";
		break;
		case "ariat":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat-selected.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 5;
			bannerLink.href = "/Ariat.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-ariat.jpg)";
		break;
		case "crocs":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs-selected.png";
			dr_martens.src = filePath+"/hp-dr-martens.png";
			iCurrent = 6;
			bannerLink.href = "/crocs.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-crocs.jpg)";
		break;
		case "dr-martens":
			sowerby.src = filePath+"/hp-sowerby.png";
			loake.src = filePath+"/hp-loake.png";
			john_white.src = filePath+"/hp-john-white.png";
			sanders.src = filePath+"/hp-sanders.png";
			barker.src = filePath+"/hp-barker.png";
			ariat.src = filePath+"/hp-ariat.png";
			crocs.src = filePath+"/hp-crocs.png";
			dr_martens.src = filePath+"/hp-dr-martens-selected.png";
			iCurrent = 7;
			bannerLink.href = "/dr-marten.htm"
			
			placeholder.style.backgroundImage = "url("+filePath+"hp-banner-dr-martens.jpg)";
		break;
	}
	clearTimeout(iTimeoutId)
	iTimeoutId = setTimeout("selectNextBanner(true)",5000);
}

function selectNextBanner(){
	var aBanners = Array("sowerby","loake","john-white","sanders","barker","ariat","crocs","dr-martens");
	iCurrent++;
	if(iCurrent>aBanners.length-1){iCurrent=0}
	switchBanner(aBanners[iCurrent])
	clearTimeout(iTimeoutId)
	iTimeoutId = setTimeout("selectNextBanner(true)",5000);
}

function runBanner(lOnLoad){
	if(lOnLoad){selectNextBanner(true)}
	iTimeoutId = setTimeout("selectNextBanner(true)",5000);
}

function reloadMatrix(pid){
	getAjaxConnection();
	if (aJax) {
		var sides = document.getElementById("matrix-sides").value
		var finishes = document.getElementById("matrix-finish").value
		var sizes = document.getElementById("matrix-sizes").value
		var qty = document.getElementById("matrix-qty").value
		var gsm = document.getElementById("matrix-gsm").value
		var url = "/prin01-matrix.asp?id="+pid+"&sides="+sides+"&finish="+finishes+"&size="+sizes+"&qty="+Number(qty)+"&gsm="+Number(gsm)+"&" + Date();
		aJax.open("GET", url, true);
		
		aJax.onreadystatechange = loadMatrix;
		aJax.send(null);
	}
}

function loadMatrix() {
	if (aJax.readyState == 4 && aJax.status == 200) {
		var table = document.getElementById("matrix-table");
		if(table) table.innerHTML = aJax.responseText;
		if(document.getElementById("price-cell") && document.getElementById("matrix-price")) document.getElementById("matrix-price").innerHTML = "&pound;" + document.getElementById("price-cell").innerHTML
	}
}
