// Additional scripts to show stock level / out of stock message when using ActiveStock

function checkElements(){
	var products = "";
	var mycheck = document.getElementsByTagName("span");
		 for (i=0;i<mycheck.length; i++){
			if (mycheck[i].id){
			var strId = mycheck[i].id.substr(0,4);
			if (strId == "cart"){
					var prodarray = mycheck[i].id.split("cart_");
					var prodref = prodarray[1];
					products += prodref + ",";
				}	
			}
		}
	xmlhttpPost(products);
	}

	function updateElem(response){
	var mytext = "Stock availability: ";
	var stock = response.split(",");
	var i=0;
	for (i=0;i<stock.length;i=i+3){
		var myId = "cart_" +  stock[i];
		var myElem = document.getElementById(myId);
		if(myElem){	
			if(stock[i+1] == 1){
				var newdiv = document.createElement("div");
				var mynode = document.createTextNode("WE'RE SORRY, THIS PRODUCT IS CURRENTLY OUT OF STOCK.");
				newdiv.appendChild(mynode);
				myElem.appendChild(newdiv);
				myElem.lastChild.className="actrequired";
				myElem.lastChild.style.fontWeight="700";
				myElem.lastChild.style.clear="both";
				myElem.firstChild.style.display="none";
				}
			}
		}
	}
	
function xmlhttpPost(ref) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
	var qstr = 'http://www.mumstuff.co.uk/cgi-bin/checkstock.pl?prodref=' + escape(ref) + '&time=' + new Date().getTime();
    self.xmlHttpReq.open('GET', qstr, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
			updateElem(self.xmlHttpReq.responseText);
			}	
        }
    self.xmlHttpReq.send(null);
}

