var txtCurrencyCode = "&pound;";
var mouseondiv = 0;
var xmlHttp;
var CurrentOpacity = 100;
var OpacityInterval = 15;
var IntervalTime = 75;
var WaitSeconds = 5000;
var direction=1;
var txtRedHot=0;
var CurrentTbl = 0;
var wait = 0;
var CurrentRow = 0;
var intProductPage = 0;
var CurRowSearch=-1;
var intTimes=0;
var blnSearchOver=false;
var intEmbroideryLine = 0;
var txtEmbroideryErrorMessage = "";

function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	return IsNumber;
}

function hSwatch(id) {
	j = document.getElementById("txtSwatch").value;
	for (i=0; i<=j; i++) {
		document.getElementById("SwatchCell" + i).style.border="";
	}
	document.getElementById("SwatchCell" + id).style.border="2px solid #FF0000";
}

function SwatchPopup(id) {
	obj = document.getElementById("Swatch" + id);
	obj2 = document.getElementById("SwatchCell" + id);
	obj.style.display='';
	obj.style.left = findPosX(obj2) - 11;
	obj.style.top = findPosY(obj2) + 14;
}

function HideSwatch(id) {
	document.getElementById("Swatch" + id).style.display='none';
}

function GetValue(oRootNode, txtElementName) {
	return oRootNode.getElementsByTagName(txtElementName)[0].childNodes[0].nodeValue;
}

function UpdateCart() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		try {
			document.getElementById("emptybasket").style.display='none';
		} catch(e) {}
		try {
			var oRootNode = GetRootNode(xmlHttp.responseText);
			var oProduct = oRootNode.getElementsByTagName("Product");
			oShoppingBasket = document.getElementById("ShoppingBasket");
			var tbody = document.getElementById("ShoppingBasket").getElementsByTagName("TBODY")[0];
			if (oShoppingBasket.rows.length > 0) {
				for (intCurrentRow=0; intCurrentRow<=oShoppingBasket.rows.length;intCurrentRow++) {
					document.getElementById("ShoppingBasket").removeChild(tbody);
				}
			}
			var tbody = document.createElement("TBODY");
			document.getElementById("ShoppingBasket").appendChild(tbody);
			for (intCurrentProduct=0; intCurrentProduct<=oProduct.length-1; intCurrentProduct++) {
				intShoppingBasketId = oRootNode.getElementsByTagName("intShoppingBasketId")[intCurrentProduct].childNodes[0].nodeValue;
				txtSupplierCode = oRootNode.getElementsByTagName("txtSupplierCode")[intCurrentProduct].childNodes[0].nodeValue;
				txtProductName = oRootNode.getElementsByTagName("txtProductName")[intCurrentProduct].childNodes[0].nodeValue;
				txtProductUrl = oRootNode.getElementsByTagName("txtProductUrl")[intCurrentProduct].childNodes[0].nodeValue;
				txtColour = oRootNode.getElementsByTagName("txtColour")[intCurrentProduct].childNodes[0].nodeValue;
				txtSize = oRootNode.getElementsByTagName("txtSize")[intCurrentProduct].childNodes[0].nodeValue;
				intQuantity = oRootNode.getElementsByTagName("intQuantity")[intCurrentProduct].childNodes[0].nodeValue;
				intClearanceId = oRootNode.getElementsByTagName("intClearanceId")[intCurrentProduct].childNodes[0].nodeValue;
				intVAT = oRootNode.getElementsByTagName("intVAT")[intCurrentProduct].childNodes[0].nodeValue;
				txtRate = oRootNode.getElementsByTagName("txtRate")[intCurrentProduct].childNodes[0].nodeValue;
				txtPrice = oRootNode.getElementsByTagName("txtPrice")[intCurrentProduct].childNodes[0].nodeValue;
				intEmbroidery = oRootNode.getElementsByTagName("intEmbroidery")[intCurrentProduct].childNodes[0].nodeValue;
				var tbody = document.createElement("TBODY");
				var row = document.createElement("TR");
				var td = document.createElement("TD");
				var table = document.createElement("TABLE");
				var tbody1 = document.createElement("TBODY");
				var row1 = document.createElement("TR");
				var row2 = document.createElement("TR");
				var td1 = document.createElement("TD");
				var td2 = document.createElement("TD");
				var td3 = document.createElement("TD");
				
				td1.appendChild(document.createTextNode(intQuantity + " X  <a href='" + txtProductUrl + "'>a</a>"));
				td1.className='color18';
				td2.appendChild(document.createTextNode("&#xBB; " + txtColour + ", " + txtSize));
				td3.appendChild(document.createTextNode("£" + txtPrice));
				td2.colspan="3";
				td2.style.padding="0px";
				td2.style.paddingLeft="30px";
				td3.align="right";
				
				row1.appendChild(td1);
				row1.appendChild(td3);
				row1.style.bacgroundColor="#000000";
				row2.appendChild(td2);
				tbody1.appendChild(row1);
				tbody1.appendChild(row2);
				table.appendChild(tbody1);
				table.width="100%";
				table.style.backgroundColor="#000000";
				table.id="shop" + intShoppingBasketId;
				td.appendChild(table);
				row.appendChild(td);
				document.getElementById("ShoppingBasket").getElementsByTagName("TBODY")[0].appendChild(row);
				oTable = document.getElementById("shop" + intShoppingBasketId);
				oTable.rows[0].cells[0].innerHTML = intQuantity  + " X <a href='" + txtProductUrl + "'>" + txtProductName + "</a>";
				oTable.rows[1].cells[0].innerHTML = "&#xBB; " + txtColour + ", " + txtSize;
			}
			intProductCount = oRootNode.getElementsByTagName("intProductCount")[0].childNodes[0].nodeValue;
			intEmbroidery = oRootNode.getElementsByTagName("intEmbroidery")[0].childNodes[0].nodeValue;
			txtSubTotal = oRootNode.getElementsByTagName("txtSubTotal")[0].childNodes[0].nodeValue;
			txtPostage = oRootNode.getElementsByTagName("txtPostage")[0].childNodes[0].nodeValue;
			txtVAT = oRootNode.getElementsByTagName("txtVAT")[0].childNodes[0].nodeValue;
			txtTotal = oRootNode.getElementsByTagName("txtTotal")[0].childNodes[0].nodeValue;
			intLastProductAdded = oRootNode.getElementsByTagName("intLastProductAdded")[0].childNodes[0].nodeValue;
			document.getElementById("TotalPrice").innerHTML = "£" + txtSubTotal;
			window.scrollTo(0,0);
			FlashRow("shop" + intLastProductAdded, 1, "#000000", "#FFCC66");
		} catch(err) {
			setTimeout(function () {alert("The Shopping Cart has encounted an error.\n\nPlease Ring 0800 376 0273");}, 1000);
			window.location.href=window.location.href;
			return
		}
	}
}

function GetRootNode(XmlData) {
	var xmlDoc;
	try {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(XmlData);
	} catch(e) {
		try {
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(XmlData,"text/xml");
		} catch(e) {
			alert("The Shopping Cart has encounted an error.\n\nPlease Ring 0800 376 0273");
			return
		}
	}
	return xmlDoc;
}

function getHexColor(txtColour) {
	if (txtColour.indexOf("rgb") != -1) {
		var RGB = txtColour.substring(4,txtColour.length-1);
		oRGB = RGB.split(",");
		txtColour = "#" + RGBtoHex(oRGB[0], oRGB[1], oRGB[2]);
	}
	return txtColour.toUpperCase();
}

function FlashRow(txtRowId, intTimes, txtStartColour, txtFlashColour) {
	oShopRow = document.getElementById(txtRowId);
	txtBackColour = oShopRow.style.backgroundColor;
	if (intTimes < 11) {
		if (txtBackColour.indexOf("rgb") != -1) {
			var RGB = oShopRow.style.backgroundColor.substring(4,oShopRow.style.backgroundColor.length-1);
			oRGB = RGB.split(",");
			txtBackColour = "#" + RGBtoHex(oRGB[0], oRGB[1], oRGB[2]);
		}
		txtBackColour = getHexColor(txtBackColour)
		if (txtBackColour == txtFlashColour.toUpperCase()) {
			oShopRow.style.backgroundColor=txtStartColour;
		} else {
			oShopRow.style.backgroundColor=txtFlashColour;
		}
		intTimes++;
		setTimeout("FlashRow('" + txtRowId + "', '" + intTimes + "', '" + txtStartColour + "', '" + txtFlashColour + "')", 100);
	}
}

function RGBtoHex(R,G,B) {return toHex(R)+toHex(G)+toHex(B)}

function toHex(N) {
	if (N==null) return "00";
	N=parseInt(N); if (N==0 || isNaN(N)) return "00";
	N=Math.max(0,N); N=Math.min(N,255); N=Math.round(N);
	return "0123456789ABCDEF".charAt((N-N%16)/16) + "0123456789ABCDEF".charAt(N%16);
}


function AddCart(intProductId) {
	if (intProductId.length == 0) {
		return
	}
	try {
		txtSize = document.getElementById("txtSnickersSize").value;
	} catch (e) {
		txtSize = document.getElementById("os0").value;
	}
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return
	}
	try {
		intClearance = document.getElementById("intClearanceId").value;
	} catch(e) {
		intClearance = 0;
	}
	
	txtColour = document.getElementById("os1").value;
	intQuantityVal = document.getElementById("txtQuantity").value;
	
	if (!IsNumeric(intQuantityVal) && intQuantityVal != "0") {
		alert("Please Enter a valid Quantity");
		document.getElementById("txtQuantity").focus();
		return;
	}
	var url = "/includes/shop/addtocart.asp?intClearanceId=" + intClearance + "&intProductId=" + intProductId + "&txtColour=" + txtColour + "&txtSize=" + txtSize + "&intQuantity=" + intQuantityVal + "&s=" + Math.random();
	xmlHttp.onreadystatechange=UpdateCart;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function GetXmlHttpObject() {
	var objXMLHttp=null
	if (window.XMLHttpRequest) {
		objXMLHttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}

function HideOverlay(txtDivName) {
	oSelect = document.getElementsByTagName("select");
	for (i=0; i<oSelect.length; i++) {
		oSelect[i].style.display='';
	}
	document.getElementById("divOverlay").style.display='none';
	document.getElementById("div" + txtDivName).style.display='none';
}

function DisplayOverlay(txtDivName) {
	oSelect = document.getElementsByTagName("select");
	for (i=0; i<oSelect.length; i++) {
		if (oSelect[i].show!=1) {
			oSelect[i].style.display='none';
		}
	}
	updateOverlay(txtDivName);
	document.getElementById("divOverlay").style.display='';
	document.getElementById("div" + txtDivName).style.display='';
}

function updateOverlay(txtDivName) {
	if (self.pageYOffset) {
		ScrollTop = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop > -1) {
		ScrollTop = document.documentElement.scrollTop;
	} else if (document.body) {
		ScrollTop = document.body.clientHeight;
	}
	intWidth = window.document.body.clientWidth - parseInt(document.getElementById("tbl" + txtDivName).style.width);
	intHeight = parseInt(document.documentElement.clientHeight) - parseInt(document.getElementById("tbl" + txtDivName).style.height);
	document.getElementById("divOverlay").style.width = document.body.scrollWidth + "px";
	document.getElementById("divOverlay").style.height = document.body.scrollHeight + "px";
	try {
		document.getElementById("div" + txtDivName).style.width = document.body.scrollWidth + "px";
		document.getElementById("div" + txtDivName).style.height = document.body.scrollHeight + "px";
		document.getElementById("tbl" + txtDivName).style.top = parseInt(ScrollTop) + (intHeight / 2) + "px";
		document.getElementById("tbl" + txtDivName).style.left = (intWidth / 2) + "px";
	} catch (e) {}
}

function ChangePosition(intPosition) {
	oPosition = document.getElementById("selPosition");
	for (intCurrentPosition=0; intCurrentPosition<oPosition.length; intCurrentPosition++) {
		if (oPosition.options[intCurrentPosition].value == intPosition) {
			oPosition.selectedIndex = intCurrentPosition;
			
		}
	}
	document.getElementById("intPositionId").value=intPosition;
	FlashRow("tdPositionSelectHolder", 5, "#FFFFFF", "#FFCC66");
}
//Fix for FireFox next 2 functions
function InputChangeReq(oInput) {
	if (oInput.value == oInput.defaultValue) {
		oInput.value = '';
		oInput.style.color='#000';
	}
}

function InputLeaveReq(oInput) {
	if (oInput.value.length == 0) {
		oInput.value = oInput.defaultValue;
		oInput.style.color='#999';
	}
}

function UpdateEmbroideryPreview() {
	txtFontName = document.getElementById("selFont").options[document.getElementById("selFont").selectedIndex].getAttribute("FolderName");
	GetEmbroideryFontReq(Base64.encode(document.getElementById("txtLine1").value), document.getElementById("intFontId").value, "divLine1", document.getElementById("intLine1Percent").value);
	GetEmbroideryFontReq(Base64.encode(document.getElementById("txtLine2").value), document.getElementById("intFontId").value, "divLine2", document.getElementById("intLine2Percent").value);
	GetEmbroideryFontReq(Base64.encode(document.getElementById("txtLine3").value), document.getElementById("intFontId").value, "divLine3", document.getElementById("intLine3Percent").value);
}

function GetEmbroideryFontReq(txtConvertText, intFontId, txtDivName, intPercentId) {
	var oXmlDom
	oXmlDom=GetXmlHttpObject()
	if (oXmlDom == null) {
		alert ("Browser does not support HTTP Request");
		return
	}
	
	var url = "/includes/branding/generateembroidery.asp?txtConvertText=" + txtConvertText + "&intFontId=" + intFontId + "&intPercentId=" + intPercentId + "&s=" + Math.random();
	oXmlDom.onreadystatechange=function () {
		if (oXmlDom.readyState == 4) GetEmbroideryFontRes(txtDivName, oXmlDom.responseText)
	};
	oXmlDom.open("GET",url,true);
	oXmlDom.send(null);	
}

function GetEmbroideryFontRes(txtDivName, responseText) {
	if (txtDivName == "divLine1") {
		intEmbroideryLine = 0;
		txtEmbroideryErrorMessage = "";
	}
	var oRootNode = GetRootNode(responseText);
	var oLetters = oRootNode.getElementsByTagName("Letter");
	txtDivContents = "";
	//if (oLetters.length > 0) {
		for (intLoop=0; intLoop<oLetters.length;intLoop++) {
			txtDivContents = txtDivContents + "<img src='" + oLetters[intLoop].getElementsByTagName('txtSrc')[0].childNodes[0].nodeValue + "' width='" + oLetters[intLoop].getElementsByTagName('txtWidth')[0].childNodes[0].nodeValue + "' height='" + oLetters[intLoop].getElementsByTagName('txtHeight')[0].childNodes[0].nodeValue + "' />";
		}
		try {
			txtRemoved = oRootNode.getElementsByTagName("Removed")[0].childNodes[0].nodeValue;
		} catch(e) {
			txtRemoved = ""
		}
	//}
	
	intEmbroideryLine++;
	if (txtRemoved.length > 0) {
		txtEmbroideryErrorMessage = txtEmbroideryErrorMessage + "Line " + intEmbroideryLine + " was too big so I have removed the following characters {" + txtRemoved + "}\n";
	}
	document.getElementById(txtDivName).innerHTML = txtDivContents;
	if (txtDivName == "divLine3" && txtEmbroideryErrorMessage.length > 0) {
		alert("I encountered these problems whilst processing your request.\n\n" + txtEmbroideryErrorMessage);
		
	}
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },
	
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function UpdateEmbroideryCartReq(intShoppingBasketId, intEmbroidery) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return
	}

	var url = "/includes/shop/updateembroiderycart.asp?intShoppingBasketId=" + intShoppingBasketId + "&intEmbroidery=" + intEmbroidery + "&s=" + Math.random();
	xmlHttp.onreadystatechange=function () {if (xmlHttp.readyState == 4) UpdateEmbroideryCartRes()};
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function UpdateEmbroideryCartRes() {
	var oRootNode = GetRootNode(xmlHttp.responseText);
	var oResponse = oRootNode.getElementsByTagName("EmbroideryCartUpdateRes");	
	intTotalEmbroideries = oRootNode.getElementsByTagName("intTotalEmbroideries")[0].childNodes[0].nodeValue;
	txtEmbroideryPrice = oRootNode.getElementsByTagName("txtEmbroideryPrice")[0].childNodes[0].nodeValue;
	txtSubTotal = oRootNode.getElementsByTagName("txtSubTotal")[0].childNodes[0].nodeValue;
	txtShipping = oRootNode.getElementsByTagName("txtShipping")[0].childNodes[0].nodeValue;
	txtVAT = oRootNode.getElementsByTagName("txtVAT")[0].childNodes[0].nodeValue;
	txtTotal = oRootNode.getElementsByTagName("txtTotal")[0].childNodes[0].nodeValue;

	document.getElementById("spnTotalEmbroideries").innerHTML = intTotalEmbroideries;
	document.getElementById("spnEmbroideryPrice").innerHTML = txtCurrencyCode + txtEmbroideryPrice;
	document.getElementById("spnSubTotal").innerHTML = txtCurrencyCode + txtSubTotal;
	document.getElementById("spnShipping").innerHTML = txtCurrencyCode + txtShipping;
	document.getElementById("spnVAT").innerHTML = txtCurrencyCode + txtVAT;
	document.getElementById("spnTotal").innerHTML = txtCurrencyCode + txtTotal;
}

function EmbroideryPreview(txtImageName) {
	document.getElementById('imgEmbroideryPreview').src = "/images/embexamples/large/" + txtImageName + ".jpg";
	DisplayOverlay('EmbroideryPreview');
}

function HideEmbroideryPreview() {
	document.getElementById('imgEmbroideryPreview').src = "/images/embexamples/large/blank.jpg";
	HideOverlay('EmbroideryPreview');
}

function HideElement(txtElementId) {
	document.getElementById(txtElementId).style.visibility='hidden';
	document.getElementById(txtElementId).style.display='none';
}

function ShowElement(txtElementId) {
	document.getElementById(txtElementId).style.visibility='visible';
	document.getElementById(txtElementId).style.display='';
}

function ChangePaginationReq(intDisplayPerPage) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return
	}

	var url = "/includes/shop/changepagination.asp?intDisplayPerPage=" + intDisplayPerPage + "&s=" + Math.random();
	xmlHttp.onreadystatechange=function () {if (xmlHttp.readyState == 4) window.location.href=window.location.href;};
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function AJAXShoppingBasketArtworkNameUpdateReq(intSender) {
	txtArtworkName = document.getElementById("txtArtworkName" + intSender).value;
	intArtworkId = document.getElementById("intArtworkId" + intSender).value;
	
	xmlHttp=GetXmlHttpObject();
	
	var url = "/includes/ajax/AJAXShoppingBasketArtworkNameUpdateReq.asp?txtArtworkName=" + txtArtworkName + "&intArtworkId=" + intArtworkId + "&s=" + Math.random();
	xmlHttp.onreadystatechange=AJAXShoppingBasketArtworkNameUpdateRes;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function AJAXShoppingBasketArtworkNameUpdateRes() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText == "ok") {
			//change Logos Upstairs
		}
	}
}

//function SearchTypeClick() {
//	intX = findPosX(document.getElementById("txtSearchType"));
//	intY = findPosY(document.getElementById("txtSearchType"));
//	intHeight = document.getElementById("divSearchType").style.height;
//	intWidth = document.getElementById("divSearchType").style.width;
//	document.getElementById("divSearchType").style.left = intX + "px";
//	document.getElementById("divSearchType").style.top = (intY-178) + "px";
//	document.getElementById("divOverlay").style.width = document.body.scrollWidth + "px";
//	document.getElementById("divOverlay").style.height = document.body.scrollHeight + "px";
//	document.getElementById("divSearchType").style.display='';
//	document.getElementById("divOverlay").style.display='';
//}

//function SearchTypeSave() {
//	oSearchTypeList = document.getElementById("SearchTypeList").getElementsByTagName("li");
//	txtSearchTypes = "";
//	for (intCurrentType=0; intCurrentType<oSearchTypeList.length; intCurrentType++) {
//		if (oSearchTypeList.item(intCurrentType).getAttribute("id") == "selected") {
//			txtSearchTypes = txtSearchTypes + oSearchTypeList.item(intCurrentType).innerHTML + ",";
//		}
//	}
//	txtSearchTypes = txtSearchTypes.substr(0, txtSearchTypes.length-1);
//	document.getElementById("txtSearchType").value = txtSearchTypes;
//	document.getElementById("divOverlay").style.display='none';
//	document.getElementById("divSearchType").style.display='none';
//}

function ToggleSearchType(oListItem, blnDisableAll) {
	if (oListItem.id == "selected") {
		oListItem.id = "";
	} else {
		oListItem.id = "selected";
	}
}

function CloseSearch() {
	document.getElementById("divSearchResults").style.display='none';
	document.getElementById("divOverlay").style.display='none';
}

function getSearch() {
	//txtSearchTypeVal = document.getElementById("txtSearchType").value;
	txtSearchTermVal = document.getElementById("txtSearchTerm").value;
	document.getElementById("iFrameSearchResults").src='/includes/search/search.asp?txtSearchTerm=' + txtSearchTermVal + "&s=" + Math.random();
	//document.getElementById("iFrameSearchResults").src='/includes/search/search.asp?txtSearchType=' + txtSearchTypeVal + '&txtSearchTerm=' + txtSearchTermVal + "&s=" + Math.random();
	intX = findPosX(document.getElementById("txtSearchTerm"));
	intY = findPosY(document.getElementById("txtSearchTerm"));
	intHeight = document.getElementById("divSearchResults").style.height;
	intWidth = document.getElementById("divSearchResults").style.width;
	document.getElementById("divSearchResults").style.left = (intX-475) + "px";
	document.getElementById("divSearchResults").style.top = (intY+20) + "px";
	document.getElementById("divOverlay").style.width = document.body.scrollWidth + "px";
	document.getElementById("divOverlay").style.height = document.body.scrollHeight + "px";
	document.getElementById("divSearchResults").style.display='';
	document.getElementById("divOverlay").style.display='';
}

var grayscale = (function(){
    
    var config = {
            colorProps: ['color','backgroundColor','borderBottomColor','borderTopColor','borderLeftColor','borderRightColor','backgroundImage'],
            externalImageHandler : {
                /* Grayscaling externally hosted images does not work
                   - Use these functions to handle those images as you so desire */
                /* Out of convenience these functions are also used for browsers
                   like Chrome that do not support CanvasContext.getImageData */
                init : function(el, src) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        // Default - remove background images
                        data(el).backgroundImageSRC = src;
                        el.style.backgroundImage = '';
                    }
                },
                reset : function(el) {
                    if (el.nodeName.toLowerCase() === 'img') {
                        // Is IMG element...
                    } else {
                        // Is background-image element:
                        el.style.backgroundImage = 'url(' + (data(el).backgroundImageSRC || '') + ')';
                    }
                }
            }
        },
        log = function(){
            try { window.console.log.apply(console, arguments); }
            catch(e) {};
        },
        isExternal = function(url) {
            // Checks whether URL is external: 'CanvasContext.getImageData'
            // only works if the image is on the current domain.
            return (new RegExp('https?://(?!' + window.location.hostname + ')')).test(url);
        },
        data = (function(){
            
            var cache = [0],
            expando = 'data' + (+new Date());
            
            return function(elem) {
                var cacheIndex = elem[expando],
                    nextCacheIndex = cache.length;
                if(!cacheIndex) {
                    cacheIndex = elem[expando] = nextCacheIndex;
                    cache[cacheIndex] = {};
                }
                return cache[cacheIndex];
            };
            
        })(),
        desatIMG = function(img, prepare, realEl) {
            
            // realEl is only set when img is temp (for BG images)
            
            var canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                height = img.naturalHeight || img.offsetHeight || img.height,
                width = img.naturalWidth || img.offsetWidth || img.width,
                imgData;
                
            canvas.height = height;
            canvas.width = width;
            context.drawImage(img, 0, 0);
            try {
                imgData = context.getImageData(0, 0, width, height);
            } catch(e) {}
            
            if (prepare) {
                desatIMG.preparing = true;
                // Slowly recurse through pixels for prep,
                // :: only occurs on grayscale.prepare()
                var y = 0;
                (function(){
                    
                    if (!desatIMG.preparing) { return; }
                    
                    if (y === height) {
                        // Finished!
                        context.putImageData(imgData, 0, 0, 0, 0, width, height);
                        realEl ? (data(realEl).BGdataURL = canvas.toDataURL())
                               : (data(img).dataURL = canvas.toDataURL())
                    }
                    
                    for (var x = 0; x < width; x++) {
                        var i = (y * width + x) * 4;
                        // Apply Monoschrome level across all channels:
                        imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                        RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                    }
                    
                    y++;
                    setTimeout(arguments.callee, 0);
                    
                })();
                return;
            } else {
                // If desatIMG was called without 'prepare' flag
                // then cancel recursion and proceed with force! (below)
                desatIMG.preparing = false;
            }
            
            for (var y = 0; y < height; y++) {
                for (var x = 0; x < width; x++) {
                    var i = (y * width + x) * 4;
                    // Apply Monoschrome level across all channels:
                    imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] =
                    RGBtoGRAYSCALE(imgData.data[i], imgData.data[i+1], imgData.data[i+2]);
                }
            }
            
            context.putImageData(imgData, 0, 0, 0, 0, width, height);
            return canvas;
        
        },
        getStyle = function(el, prop) {
            var style = document.defaultView && document.defaultView.getComputedStyle ? 
                        document.defaultView.getComputedStyle(el, null)[prop]
                        : el.currentStyle[prop];
            // If format is #FFFFFF: (convert to RGB)
            if (style && /^#[A-F0-9]/i.test(style)) {
                    var hex = style.match(/[A-F0-9]{2}/ig);
                    style = 'rgb(' + parseInt(hex[0], 16) + ','
                                   + parseInt(hex[1], 16) + ','
                                   + parseInt(hex[2], 16) + ')';
            }
            return style;
        },
        RGBtoGRAYSCALE = function(r,g,b) {
            // Returns single monochrome figure:
            return parseInt( (0.2125 * r) + (0.7154 * g) + (0.0721 * b), 10 );
        },
        getAllNodes = function(context) {
            var all = Array.prototype.slice.call(context.getElementsByTagName('*'));
            all.unshift(context);
            return all;
        };
        
    var init = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.call(this, allContexts[cIndex]); }
            return;
        }
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)';
            context.style.zoom = 1;
            return;
        }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
            
        while (++i<len) {
            var cur = all[i];
            
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if(!src) { continue; }
                if (isExternal(src)) {
                    config.externalImageHandler.init(cur, src);
                } else {
                    data(cur).realSRC = src;
                    try {
                        // Within try statement just encase there's no support....
                        cur.src = data(cur).dataURL || desatIMG(cur).toDataURL();
                    } catch(e) { config.externalImageHandler.init(cur, src); }
                }
                
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    var prop = config.colorProps[pIndex],
                    style = getStyle(cur, prop);
                    if (!style) {continue;}
                    if (cur.style[prop]) {
                        data(cur)[prop] = style;
                    }
                    // RGB color:
                    if (style.substring(0,4) === 'rgb(') {
                        var monoRGB = RGBtoGRAYSCALE.apply(null, style.match(/\d+/g));
                        cur.style[prop] = style = 'rgb(' + monoRGB + ',' + monoRGB + ',' + monoRGB + ')';
                        continue;
                    }
                    // Background Image:
                    if (style.indexOf('url(') > -1) {
                        var urlPatt = /\(['"]?(.+?)['"]?\)/,
                            url = style.match(urlPatt)[1];
                        if (isExternal(url)) {
                            config.externalImageHandler.init(cur, url);
                            data(cur).externalBG = true;
                            continue;
                        }
                        // data(cur).BGdataURL refers to caches URL (from preparation)
                        try {
                            var imgSRC = data(cur).BGdataURL || (function(){
                                    var temp = document.createElement('img');
                                    temp.src = url;
                                    return desatIMG(temp).toDataURL();
                                })();
                            
                            cur.style[prop] = style.replace(urlPatt, function(_, url){
                                return '(' + imgSRC + ')';
                            });
                        } catch(e) { config.externalImageHandler.init(cur, url); }
                    }
                }
            }
        }
        
    };
    
    init.reset = function(context) {
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.reset.call(this, allContexts[cIndex]); }
            return;
        }
        context = context || document.documentElement;
        if (!document.createElement('canvas').getContext) {
            context.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayscale=0)';
            return;
        }
        var all = getAllNodes(context),
            i = -1, len = all.length;
        while (++i<len) {
            var cur = all[i];
            if (cur.nodeName.toLowerCase() === 'img') {
                var src = cur.getAttribute('src');
                if (isExternal(src)) {
                    config.externalImageHandler.reset(cur, src);
                }
                cur.src = data(cur).realSRC || src;
            } else {
                for (var pIndex = 0, pLen = config.colorProps.length; pIndex < pLen; pIndex++) {
                    if (data(cur).externalBG) {
                        config.externalImageHandler.reset(cur);
                    }
                    var prop = config.colorProps[pIndex];
                    cur.style[prop] = data(cur)[prop] || '';
                }
            }
        }
    };
    
    init.prepare = function(context) {
        
        // Handle if a DOM collection is passed instead of a single el:
        if (context && context[0] && context.length && context[0].nodeName) {
            // Is a DOM collection:
            var allContexts = Array.prototype.slice.call(context),
                cIndex = -1, cLen = allContexts.length;
            while (++cIndex<cLen) { init.prepare.call(null, allContexts[cIndex]); }
            return;
        }
        
        // Slowly recurses through all elements
        // so as not to lock up on the user.
        
        context = context || document.documentElement;
        
        if (!document.createElement('canvas').getContext) { return; }
        
        var all = getAllNodes(context),
            i = -1, len = all.length;
        
        while (++i<len) {
            var cur = all[i];
            if (data(cur).skip) { return; }
            if (cur.nodeName.toLowerCase() === 'img') {
                if (cur.getAttribute('src') && !isExternal(cur.src)) {
                    desatIMG(cur, true);
                }
                
            } else {
                var style = getStyle(cur, 'backgroundImage');
                if (style.indexOf('url(') > -1) {
                    var urlPatt = /\(['"]?(.+?)['"]?\)/,
                        url = style.match(urlPatt)[1];
                    if (!isExternal(url)) {
                        var temp = document.createElement('img');
                        temp.src = url;
                        desatIMG(temp, true, cur);
                    }
                }
            }
        }
    };
    
    return init;

})();

function ChangePrint(txtType, intArtworkId) {
	if (txtType != "economy") {
		txtType = "premium";
	}
	window.location.href = "/includes/branding/changeArtworkType.asp?intArtworkId=" + intArtworkId + "&txtType=" + txtType;
}

function AddPrint(intShoppingBasketId) {
	var intQuantity = document.getElementById("selArtworkQuantity" + intShoppingBasketId).value;
	var intArtworkLeftBreast = document.getElementById("selArtworkLeftBreast" + intShoppingBasketId).value;
	var intArtworkRightBreast = document.getElementById("selArtworkRightBreast" + intShoppingBasketId).value;
	var intArtworkBack = document.getElementById("selArtworkBack" + intShoppingBasketId).value;
	window.location.href = "/includes/shop/addbranding.asp?intShoppingBasketId=" + intShoppingBasketId + "&intQuantity=" + intQuantity + "&intArtworkLeftBreast=" + intArtworkLeftBreast + "&intArtworkRightBreast=" + intArtworkRightBreast + "&intArtworkBack=" + intArtworkBack;
}

function RemovePrint(intArtworkId) {
	window.location.href = "/includes/shop/removebranding.asp?intArtworkId=" + intArtworkId;
}

function ToggleFilterByColour(oElement) {
	if (oElement.className == "Open") {
		oElement.className = "";
		HideElement("ProductColours");
	} else {
		oElement.className = "Open";
		ShowElement("ProductColours");
	}
}

function FilterByColour(oElement) {
	var blnFiltered = false;
	var txtFilter = "";
	var oProductColours = document.getElementById("ProductColours").getElementsByTagName("li");
	if (oElement.innerHTML == "All") {
		for (var intCurrentListItem=0; intCurrentListItem<oProductColours.length; intCurrentListItem++) {
			if (oProductColours[intCurrentListItem].innerHTML != "All") {
				oProductColours[intCurrentListItem].className = "";
			}
		}
	} else {
		document.getElementById("FilterByColourListItemAll").className = "";
	}
	if (oElement.className == "selected") {
		oElement.className = "";
	} else {
		oElement.className = "selected";
	}
	
	for (var intCurrentListItem=0; intCurrentListItem<oProductColours.length; intCurrentListItem++) {
		if (oProductColours[intCurrentListItem].className == "selected") {
			blnFiltered = true;
			txtFilter = txtFilter + oProductColours[intCurrentListItem].innerHTML + ",";
		}
	}
	if (!blnFiltered) {
		document.getElementById("FilterByColourListItemAll").className = "selected";
		txtFilter = "All,";
	}
	txtFilter = txtFilter.substr(0, txtFilter.length-1);
	SendXmlRequest("/includes/shop/Filter.asp?txtColours=" + txtFilter, FilterByColourResponse);
}

function SendXmlRequest(txtURL, txtResponseFunction) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return
	}
	xmlHttp.onreadystatechange=eval(txtResponseFunction);
	xmlHttp.open("GET", txtURL, true);
	xmlHttp.send(null);
}

function FilterByColourResponse() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText == "Status Ok") {
			window.location.href=window.location.href;
		}
	}
}