
var pageID = 0;
var processingResponse = false;
var dataRequests = new Array();

var stockData = null;

function addLoadEvent(eventHandler)
{
	var currentOnload = window.onload;
	
	if(typeof currentOnload != 'function')
	{
		window.onload = eventHandler;
	}
	else
	{
		window.onload = function()
		{
			currentOnload();
			eventHandler();
		}
	}
}

function getStockInfo(page_id)
{
	pageID = page_id;
	addLoadEvent(performStockGet);
}

function performStockGet()
{
	var url = '../dynamic/stockcheck.php?page=' + pageID;
	
	var request = new Array();
	request['type'] = 'callback';
	request['callback'] = onStockReceive;
	request['http'] = getXmlHttpObject(httpStateChanged);
	request['http'].open("GET", url, true);
	
	dataRequests[dataRequests.length] = request;
	
	request['http'].send(null);
}

function deliveryChange(productLineID, deliveryValue)
{
	// Get the form for this product
	var delivery = document.getElementById('delivery' + productLineID);
	delivery.value = deliveryValue;
}

function onStockReceive(stock, delivery_days)
{
	// Store our stock data
	stockData = stock;
		
	// Preload the respective stock for each item
	
	// Get all the form objects
	for(var i = 0; i < stockData.length; i++)
	{
		var product_line = stockData[i];
		
		// See if this product line has any items that have options set for it
		var products = product_line['products'];
		var hasOptions = false;
		for(var j = 0; j < products.length; j++)
		{
			var product = products[j];
			
			if(product['combinations'].length > 0)
			{
				hasOptions = true;
				break;
			}
		}
		
		if(hasOptions)
		{
			// Get the select options and see if that has any stock attached to it
			// Display the stock text
			var stockText = document.getElementById('no_stock' + product_line['product_line_id']);
			if(stockText)
			{
				stockText.style.display = '';
			}
		}
		else
		{
			// If the item is in stock, display the dropdown, otherwise display the stock text.  Note that there will only be one product as there's no options
			var product = products[0];
			
			var stock = product['stock'];
			if(stock > 0)
			{
				// Display the dropdown
				var delivery_dropdown = '<select name="delivery_list" class="dropdownList" onchange="deliveryChange(' + product_line['product_line_id'] + ', this.value)" >';
				
				for(var j = 0; j < delivery_days.length; j++)
				{
					if(j == 0)
					{						
						// Set our hidden delivery object to the first value
						var delivery = document.getElementById('delivery' + product_line['product_line_id']);
						if(delivery != null)
						{
							delivery.value = delivery_days[j]['value'];
						}
					}
					
					delivery_dropdown += '<option value="' + delivery_days[j]['value'] + '">' + delivery_days[j]['text'] + '</option>';
				}
				
				delivery_dropdown += '</select>';
				
				// Display the in stock option
				var stockText = document.getElementById('stock' + product_line['product_line_id']);
				if(stockText)
				{
					stockText.style.display = '';
				}
				
				setSpanValue('spnDelivery' + product_line['product_line_id'], delivery_dropdown);
			}
			else
			{
				// Display the stock text
				var stockText = document.getElementById('no_stock' + product_line['product_line_id']);
				if(stockText)
				{
					stockText.style.display = '';
				}
			}
		}
	}
}

function getXmlHttpObject(handler)
{
	var objXMLHTTP = null;
		
	if(navigator.userAgent.indexOf("Opera") >= 0)
	{
		//alert("Asynchronous data access is not supported in this web browser");
		return;
	}
		
	if(navigator.userAgent.indexOf("MSIE") >= 0)
	{
		var objectName =  "Msxml2.XMLHTTP";
		
		if(navigator.appVersion.indexOf("MSIE 5.5") >= 0)
		{
			objectName = "Microsoft.XMLHTTP";
		}
		
		try
		{
			objXMLHTTP = new ActiveXObject(objectName);
			objXMLHTTP.onreadystatechange = handler;
			return objXMLHTTP;
		}
		catch(e)
		{
			//alert("Error: Scripting for ActiveX might be disabled.");
			return;
		}
	}
	
	if(navigator.userAgent.indexOf("Mozilla") >= 0)
	{
		objXMLHTTP = new XMLHttpRequest();
		objXMLHTTP.onload = handler;
		objXMLHTTP.onerror = handler;
		return objXMLHTTP;
	}
}

function httpStateChanged()
{
	// See if we are already it is currently being processed
	if(!processingResponse)
	{
		processingResponse = true;

		// Loop through each active request
		var i = 0;
		while(i < dataRequests.length)
		{
			if(dataRequests[i]['http'] != null)
			{
				// Check the status of the request
				if(dataRequests[i]['http'].readyState == 4 || dataRequests[i]['http'].readyState == "complete")
				{
					var dataRequest = dataRequests[i];
										
					// Remove the request as it is now complete
					dataRequests.splice(i, 1);
					processResponseXML(dataRequest);
				}
				else
				{
					i++;
				}
			}
			else
			{
				i++;
			}
		}
		processingResponse = false;
	}
	else
	{
		// So we don't lose the event altogether, we'll schedule it to try again in a second
		setTimeout(httpStateChanged, 1000);
	}
}

function processResponseXML(dataRequest)
{
	var text = dataRequest['http'].responseText;
	
	if(document.implementation && document.implementation.createDocument)
	{
		parser = new DOMParser();
		xmlDoc = parser.parseFromString(text, "text/xml");
		
		var roottag = xmlDoc.documentElement;
		if ((roottag.tagName == "parserError") || (roottag.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml"))
		{
			//debug(roottag);
			 //alert('Error processing XML response: ' + roottag.childNodes.item(0).nodeValue + "\r\n\r\nResponse:\r\n" + text);
		}
		else
		{
			switch(dataRequest['type'])
			{
				case 'callback':
				{
					xmlProcessedCallCallback(xmlDoc, dataRequest['callback']);
					break;
				}
				default:
				{
					//alert('Error: Unknown async process type \'' + dataRequest['type'] + '\'');
				}
			}
		}
	}
	else if(window.ActiveXObject)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = false;
		xmlDoc.loadXML(text);
		if(xmlDoc.parseError.errorCode != 0)
		{
		  //alert('Error processing XML response: ' + xmlDoc.parseError.reason + "\r\n\r\nResponse:\r\n" + text);
		}
		else
		{
			if(xmlDoc.readyState == 4)
			{
				switch(dataRequest['type'])
				{
					case 'table':
					{
						xmlProcessedPopulateTable(xmlDoc, dataRequest['table']);
						break;
					}
					case 'callback':
					{
						xmlProcessedCallCallback(xmlDoc, dataRequest['callback']);
						break;
					}
					default:
					{
						//alert('Error: Unknown async process type \'' + dataRequest['type'] + '\'');
					}
				}
			}
		}
	}
	else
	{
		//alert("Your browser does not support client XML processing");
		return;
	}
}

function getAttributeValue(attribute_list, key)
{
	for(var i = 0; i < attribute_list.length; i++)
	{
		if(attribute_list[i].name == key)
		{
			return attribute_list[i].value;
		}
	}
	return '';
}

function xmlProcessedCallCallback(xmlDoc, callbackFunction)
{
	var root = xmlDoc.getElementsByTagName('stock');
	var stock = new Array();
	var delivery_days = new Array();

	// Get all the line items
	root = root[0];
	var items = root.getElementsByTagName('product_line');
	
	for(var i = 0; i < items.length; i++)
	{
		var product_line = new Array();
		
		// Store the product line ID
		product_line['product_line_id'] = getAttributeValue(items[i].attributes, 'id');
		product_line['products'] = new Array();

		// Search every combination
		var comb = items[i].getElementsByTagName('combination');
		for(var j = 0; j < comb.length; j++)
		{
			var product = new Array();
			
			product['id'] = getAttributeValue(comb[j].attributes, 'product_id');
			product['stock'] = getAttributeValue(comb[j].attributes, 'stock');
			product['combinations'] = new Array();
			
			// Search every child combination
			var product_options = comb[j].getElementsByTagName('option');
			for(var k = 0; k < product_options.length; k++)
			{
				var group = new Array();
				
				group['group_id'] = getAttributeValue(product_options[k].attributes, 'group');
				group['option_id'] = getAttributeValue(product_options[k].attributes, 'option');
				
				product['combinations'][product['combinations'].length] = group;
			}
			
			product_line['products'][product_line['products'].length] = product;
		}

		// Append our product line		
		stock[stock.length] = product_line;
	}
	
	// Get all the delvery days
	var days_root = xmlDoc.getElementsByTagName('delivery_days');
	// Get all the child days
	var days = days_root[0].getElementsByTagName('day');
	for(var i = 0; i < days.length; i++)
	{
		var option = new Array();
		option['text'] = days[i].firstChild.nodeValue;
		option['value'] = getAttributeValue(days[i].attributes, 'value');
		
		//alert('Option: ' + option['text'] + ', Value: ' + option['value']);
		
		delivery_days[delivery_days.length] = option;
	}
	
	callbackFunction(stock, delivery_days);
}

function getObjectValue(id)
{
	var object = document.getElementById(id);
	
	if(object == null)
	{
		//alert('Object ' + id + ' does not exist');
		return null;
	}
	
	switch(object.type)
	{
		case 'hidden': {}
		case 'text':
		{
			return object.value;
		}
		case 'checkbox':
		{
			return object.checked;
		}
		case 'select-one':
		{
			return object.options[object.selectedIndex].value;
		}
		default:
		{
			//alert('Error: Unknown object type \'' + object.type + '\' in function getObjectValue()');
			return null;
		}
	}
}

function setSpanValue(id, value)
{
	var object = document.getElementById(id);
	if(object != null)
	{
		object.innerHTML = value;
	}
}

function setObjectValue(id, value)
{
	var object = document.getElementById(id);
		
	if(object == null)
	{
		//alert('Object ' + id + ' does not exist');
		return null;
	}
	
	switch(object.type)
	{
		case 'button': {}
		case 'hidden': {}
		case 'text':
		{
			object.value = value;
			break;
		}
		case 'checkbox':
		{
			object.checked = value;
			break;
		}
		case 'select-one':
		{
			// Find the item that has a matching value, then set it to that index
			for(var i = 0; i < object.options.length; i++)
			{
				if(object.options[i].value == value)
				{
					object.selectedIndex = i;
					break;
				}
			}
			break;
		}
		default:
		{
			//alert('Error: Unknown object type \'' + object.type + '\' in function setObjectValue()');
			return null;
		}
	}
}
