// JavaScript Document

function makeBasketRequest(url) {

	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() { populateContents(http_request,section); };
	http_request.open('GET', url, true);
	http_request.send(null);

}

function populateContents(http_request,section) {
	var elemHolder = document.getElementById(section+'Holder');
	elemHolder.innerHTML = '<br clear="all" /><label style="display:block;float:left; width:100px;" for="new_'+section+'_name">Name</label><input type="text" id="new_'+section+'_name" name="new_'+section+'_name" value="" style="display:block;float:left;width:100px;">';
	elemHolder.innerHTML += '<label style="display:block; float:left; width:100px;" for="new_'+section+'_description">Description</label><input type="text" name="new_'+section+'_description" id="new_'+section+'_description" value="" style="display:block;float:left;width:150px;">';
	elemHolder.innerHTML += '&nbsp;<a href="javascript:addElem(\''+section+'\')">Add</a><br clear="all" />';
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var nodes = xmldoc.getElementsByTagName(section);
			for(i=0;i < nodes.length;i++){
				for(j=0;j<nodes[i].attributes.length;j++){
					if(nodes[i].attributes[j].nodeName == 'id'){
						thisid = nodes[i].attributes[j].nodeValue;
					} else if (nodes[i].attributes[j].nodeName == 'name'){
						thisname = nodes[i].attributes[j].nodeValue;
					}
				}
				
				thisdescription = nodes[i].firstChild.data;
				
				newelem = '<input type="hidden" name="'+section+'s[]" value="'+thisid+'" style="display:none;">';
				newelem += '<label style="float:left; width:100px;" for="'+section+'_name['+thisid+']">Name</label><input type="text" name="'+section+'_name['+thisid+']" id="'+section+'_name['+thisid+']" value="'+thisname+'" style="float:left;width:100px;">';
				newelem += '<label style="float:left; width:100px;" for="'+section+'_description['+thisid+']">Description</label><input type="text" name="'+section+'_description['+thisid+']" id="'+section+'_description['+thisid+']" value="'+thisdescription+'" style="float:left;width:150px;">';
				newelem += '&nbsp;<a href="javascript:saveElem('+thisid+',\''+section+'\')">Save Changes</a> <a href="javascript:deleteElem('+thisid+',\''+section+'\')">Delete</a><br clear="all" />';
				elemHolder.innerHTML += newelem;
				
				/*new_option = document.createElement("option");
				new_option.value = thisid;
				new_option.text = thisname;
				size_select = document.getElementById('sizes');
				size_select.add(new_option,null);*/
			}
			
		} else {
			alert('There was a problem with the request.');
		}
	}

}


function URLEncode(str){
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function showStock(theForm){
	if((theForm.colour.type == 'hidden' || theForm.colour.selectedIndex != 0) || (theForm.size.type == 'hidden' || theForm.size.selectedIndex != 0)){
		if(theForm.size.type == 'hidden'){
			size = theForm.size.value;
		} else if(theForm.size.type == 'select-one') {
			size = theForm.size.options[theForm.size.selectedIndex].value;
		} else {
			size = '';
		}
		if(theForm.colour.type == 'hidden'){
			colour = theForm.colour.value;
		} else if(theForm.colour.type == 'select-one') {
			colour = theForm.colour.options[theForm.colour.selectedIndex].value;
		} else {
			colour = '';
		}
		var product = theForm.product_id.value;
		makeStockRequest('getstock_xml.php?colour='+colour+'&size='+size+'&product='+product);
	} else {
		// failed
	}
}

function makeStockRequest(url) {

	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() { setStock(http_request); };
	http_request.open('GET', url, true);
	http_request.send(null);

}

function setStock(http_request){
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var nodes = xmldoc.getElementsByTagName('stock');
			for(i=0;i < nodes.length;i++){
				for(j=0;j<nodes[i].attributes.length;j++){
					if (nodes[i].attributes[j].nodeName == 'value'){
						thisvalue = nodes[i].attributes[j].nodeValue;
					}
				}
				stockLevel = document.getElementById('stocklevel');
				stockLevel.value = thisvalue;
				newelem = '';
				elemHolder = document.getElementById('stockdisplay');
				requestedQuantity = document.getElementById('quantity').value;
				if(parseInt(requestedQuantity) <= parseInt(thisvalue)){
					newelem = 'Yes';
				} else if (parseInt(thisvalue) < 1){
					newelem = 'No';
				} else {
					newelem = 'Insufficient, only '+thisvalue+' available';
					document.getElementById('quantity').value = thisvalue;
				}
				elemHolder.innerHTML = newelem;
				
				/*new_option = document.createElement("option");
				new_option.value = thisid;
				new_option.text = thisname;
				size_select = document.getElementById('sizes');
				size_select.add(new_option,null);*/
			}
			
		} else {
			alert('There was a problem with the request.');
		}
	}
}

function buyThisNow(){
	theForm = document.getElementById('productForm');
	if(validateAdd(theForm)){
		theForm.submit();
	}
}

function addToCart(formname){
	theForm = document.getElementById(formname);
	if(validateAdd(theForm)){
		if(theForm.size.options){
			size = theForm.size.options[theForm.size.selectedIndex].value;
		} else {
			size = theForm.size.value;
		}
		if(theForm.colour.options){
			colour = theForm.colour.options[theForm.colour.selectedIndex].value;
		} else {
			colour = theForm.colour.value;
		}
		// add item
		makeBasketRequest('basket_xml.php?action=add&product='+URLEncode(theForm.product_id.value)+'&size='+URLEncode(size)+'&colour='+URLEncode(colour)+'&quantity='+URLEncode(theForm.quantity.value));
		theForm.stocklevel.value = theForm.stocklevel.value-theForm.quantity.value;
	}
}

function validateAdd(theForm){
	var error = false;
	var errmsg = 'There are the following problems with your request'+"\n";
	if(theForm.colour.type != 'hidden' && theForm.colour.selectedIndex == 0){
		errmsg += ' - You must select a colour'+"\n";
		error = true;
	}
	if(theForm.size.type != 'hidden' && theForm.size.selectedIndex == 0){
		errmsg += ' - You must select a size'+"\n";
		error = true;
	}
	if(theForm.quantity.value == '' || theForm.quantity.value == 0){
		errmsg += ' - You must select a quantity'+"\n";
		error = true;
	} else if (theForm.stocklevel.value < theForm.quantity.value){
		errmsg += ' - Insufficient stock for your request'+"\n";
		error = true;
	}
	if(error){
		alert(errmsg);
		return false;
	} else {
		return true;
	}
}
function URLEncode(str){
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function makeBasketRequest(url) {

	var http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() { populateMiniBasket(http_request); };
	http_request.open('GET', url, true);
	http_request.send(null);

}

function populateMiniBasket(http_request){
	var priceHolder = document.getElementById('basket_total');
	var itemHolder = document.getElementById('basket_items');
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var nodes = xmldoc.getElementsByTagName('order');
			for(i=0;i < nodes.length;i++){
				for(j=0;j<nodes[i].attributes.length;j++){
					if(nodes[i].attributes[j].nodeName == 'totalitems'){
						totalitems = nodes[i].attributes[j].nodeValue;
					} else if (nodes[i].attributes[j].nodeName == 'price'){
						price = nodes[i].attributes[j].nodeValue;
					}
				}
				priceHolder.value = '£'+price;
				itemHolder.value = totalitems;
			}
			
		} else {
			alert('There was a problem with the request.');
		}
	}

}

function printfire() {
	if (document.createEvent) {
		printfire.args =  arguments;
		var ev = document.createEvent("Events");
		ev.initEvent("printfire", false, true );
		dispatchEvent(ev);
	}
}
