//
//  These are our clumsy global variables

var oXmlHttpLoadInventory 	= null;

//
//  Note that for our qstore stuff we don't rely on an OnLoad event, so
//  we call the OnBodyLoaded manually at the bottom of this script 


function OnBodyLoaded ()
{
	//
	//  Just want to load the inventory for the current product
	//  I think getting the current product SKU might be tough as
	//  it looks like it sits in an unlabled DIV with plenty of formatting.
	//  For now, fake it
	
	LoadInventoryForProduct ("Roc");

} // end on body loaded


////////////////////////////////////////////////////////////////////////////
//
//  L O A D   I N V E N T O R Y   F O R   P R O D U C T
//
//  This takes a SearchID, sends a request to load this search from the
//  database.  When it's done loading we'll read the XML and stick it
//  in the form.
//
function LoadInventoryForProduct  (strProductID)
{
	//
	//  We used to use a hidden iFrame for this but we're changing to use AJAX 

	oXmlHttpLoadInventory = GetXmlHttpObject()

	if (null == oXmlHttpLoadInventory)
	{
		alert ("Your browser does not support HTTP Request updates");
		return false;
	} 

	var strURL = "http://www.chickswithdiscs.com/Inventory/LoadInventory.php?ProductID=" + strProductID;
	
	oXmlHttpLoadInventory.onreadystatechange = OnLoadedInventory;
	oXmlHttpLoadInventory.open ("GET", strURL, true);
	oXmlHttpLoadInventory.send (null);

} // end load search to form




///////////////////////////////////////////////////////////////////////////////
//
//  O N   L O A D E D   I N V E N T O R Y
//
//  This means our inventory has finished loading and we're supposed to stick
//  it in the form for the user to play with...
//
function OnLoadedInventory ()
{
	
	if (oXmlHttpLoadInventory.readyState == 4 || oXmlHttpLoadInventory.readyState == "complete")
	{ 
		//
		//  That means we're done loading.  First check to see if there was an 
		//  error. 
		
		var oXmlDoc 				= oXmlHttpLoadInventory.responseXML;
		var oInventoryContainer 	= oXmlDoc.documentElement;

		if (CheckForXmlError (oInventoryContainer))
			return false;
		
		//
		//  Get our inventory

		var oInventoryNodeList = oInventoryContainer.getElementsByTagName ('Inventory');
		if ((null == oInventoryNodeList) || (oInventoryNodeList.length == 0)) {
			alert ("No Inventory tag found in XML");
			return false;
		}	

		var oInventoryNode = oInventoryNodeList.item(0);
		LoadInventoryFromXMLToForm (oInventoryNode);

		return true;

	}  // end if we're done loading	
	
	return true;
	
} // end on loaded inventory





///////////////////////////////////////////////////////////////////////////////
//
//  L O A D   I N V E N T O R Y    F R O M   X M L   T O   F O R M
//
//
//
function LoadInventoryFromXMLToForm (oInventoryNode)
{
	//
	//  Clear out anything in our table to start
	
	var oOutputTable = document.getElementById('InventoryTable');
	while (oOutputTable.rows.length > 0)
		oOutputTable.deleteRow (0);
	
	//
	//  Figure out how many colors and weights we have, then create
	//  our table space, then fill it in
	
	var nColorCount		= parseInt (GetXMLValueFromChildNode(oInventoryNode, "ColorCount"));
	var nWeightCount 	= parseInt (GetXMLValueFromChildNode(oInventoryNode, "WeightCount"));
	
	for (nRow = 0; nRow < nWeightCount + 1; nRow ++)
	{
		var oRow = oOutputTable.insertRow(nRow);
		for (nCol = 0; nCol < nColorCount + 1; nCol++) {
			oRow.insertCell (nCol);
		}
	} // end loop through weights


	if (! LoadWeightAndColorHeaders (oInventoryNode, oOutputTable))
		return false;

	
	//
	//  Now load our actual inventory data!

	var oItemNodeList = oInventoryNode.getElementsByTagName ('Item');
	if ((null == oItemNodeList) || (oItemNodeList.length == 0)) {
		alert ("No items found in XML");
		return false;
	}	

	for (nItem = 0; nItem < oItemNodeList.length; nItem++) {
		var oItem = oItemNodeList.item(nItem);
		
		var nColorIndex		= parseInt (GetXMLValueFromChildNode(oItem, "ColorIndex"));
		var nWeightIndex 	= parseInt (GetXMLValueFromChildNode(oItem, "WeightIndex"));
		var strCount		= GetXMLValueFromChildNode(oItem, "Count");

		var oRow = oOutputTable.rows[nWeightIndex];
		oRow.cells[nColorIndex].innerHTML = strCount;
	
	} // end loop through items
		
} // end Load Search from XML to Form




function LoadWeightAndColorHeaders (oInventoryNode, oOutputTable)
{
	//
	//  Add our headers, first the weight

	var oWeightList = oInventoryNode.getElementsByTagName ('WeightList');
	if ((null == oWeightList) || (oWeightList.length == 0)) {
		alert ("No weights found in XML");
		return false;
	}	

	var oWeightNodeList = oWeightList.item(0).getElementsByTagName ('Weight');
	if ((null == oWeightNodeList) || (oWeightNodeList.length == 0)) {
		alert ("No weights found in XML");
		return false;
	}	

	for (nItem = 0; nItem < oWeightNodeList.length; nItem++) {
		var oWeight = oWeightNodeList.item(nItem);
		
		var strWeightName	= GetXMLValueFromChildNode(oWeight, "WeightName");
		var nWeightIndex 	= parseInt (GetXMLValueFromChildNode(oWeight, "WeightIndex"));

		var oRow = oOutputTable.rows[nWeightIndex];
		oRow.cells[0].innerHTML = "<strong>" + strWeightName + "</strong>";
	
	} // end loop through weights
		
		
	//
	//  Add our headers, now the colors

	var oColorList = oInventoryNode.getElementsByTagName ('ColorList');
	if ((null == oColorList) || (oColorList.length == 0)) {
		alert ("No Colors found in XML");
		return false;
	}	

	var oColorNodeList = oColorList.item(0).getElementsByTagName ('Color');
	if ((null == oColorNodeList) || (oColorNodeList.length == 0)) {
		alert ("No Colors found in XML");
		return false;
	}	

	for (nItem = 0; nItem < oColorNodeList.length; nItem++) {
		var oColor = oColorNodeList.item(nItem);
		
		var strColorName	= GetXMLValueFromChildNode(oColor, "ColorName");
		var nColorIndex 	= parseInt (GetXMLValueFromChildNode(oColor, "ColorIndex"));

		var oRow = oOutputTable.rows[0];
		oRow.cells[nColorIndex].innerHTML = "<strong>" + strColorName + "</strong>";
	
	} // end loop through colors

	return true;
	
} // end LoadWeightAndColorHeaders




function OnAjaxError (strError)
{
	alert (strError);
} 


function ReturnAlert (strMsg, ReturnValue)
{
	alert (strMsg);
	return ReturnValue;

} // end return alert




/////////////////////////////////////////////////////////////////////////
//
//  O N   S H O W   O R   H I D E   R E S U L T
//
//  Toggles expanded state for strDivID
//
//
function OnShowOrHideID (strID)
{
	var oDiv = document.getElementById (strID);
	if (null == oDiv)
		return;

	if (oDiv.style.display == "none") {
		oDiv.style.display = "inline";
	}
	else {
		oDiv.style.display = "none";
	}
	
} // end on hide result



function ShowID (strID)
{
	var oDiv = document.getElementById (strID);
	if (null == oDiv)
		return;

	oDiv.style.display = "inline";
}

function HideID (strID)
{
	var oDiv = document.getElementById (strID);
	if (null == oDiv)
		return;

	oDiv.style.display = "none";
}


function OnShowOrHideObject (oObject)
{
	if (oObject.style.display == "none") {
		oObject.style.display = "inline";
	}
	else {
		oObject.style.display = "none";
	}
}



////////////////////////////////////////////////////////////////////
//
//  G E T   X M L   H T T P   O B J E C T
//
//  Tries to be a browser independent way to create an XML HTTP 
//  object for our ajax-ing 
//
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)
		{
			xmlHttp = new ActiveXObject ("Microsoft.XMLHTTP");
		}
	}
	
	return xmlHttp;

} // end get xml http object






function GetXMLChildNode (oXmlElement, strChildName)
{
	var oCurNode = oXmlElement.firstChild;
	while (null != oCurNode)
	{
		if (oCurNode.nodeType == 1)
		{
			var strNodeNameLower = oCurNode.nodeName.toLowerCase ();

			if (strChildName.toLowerCase () == strNodeNameLower)
				return oCurNode;
		}

		oCurNode = oCurNode.nextSibling;
	} // end loop through XML nodes under SearchContainer		

	return null;
}


function GetXMLValueFromChildNode (oXmlElement, strChildName)
{
	var oNode = GetXMLChildNode (oXmlElement, strChildName);
	if (null == oNode)
		return false;
	
	return GetNodeText (oNode);
	
}


var bShow = true;
function GetNodeText (oElement)
{ 
	//
	//  This was a fucking nightmare.  But I don't feel like going into details and this
	//  works for IE, Firefox, and Chrome.

	var strTypeText 		= typeof (oElement.text);
	var strTypeInnerText 	= typeof (oElement.innerText);
	var strTypeTextContent 	= typeof (oElement.textContent);

	if (strTypeText !== 'undefined')	
		return oElement.text;
	if (strTypeTextContent !== 'undefined')
		return oElement.textContent;
	if (strTypeInnerText !== 'undefined')
		return oElement.innerText;
				
} 



////////////////////////////////////////////////////////////////////////////
//
//  C H E C K   F O R   X M L   E R R O R
//
//  Takes an XML Document object and checks for an <ERROR><ERRORCODE> entry
//  other than 0.  If it finds one, it gives an alert and returns true.
// 
//  Returns false if there is no error.
//
function CheckForXmlError (oXmlDoc, bAlertOnError)
{
	var oErrorNodeList = oXmlDoc.getElementsByTagName("Error");
	if (null == oErrorNodeList)
		return false;

	if (oErrorNodeList.length == 0) {
		return false;
	}
	
	//
	//  We assume we only have 1...  we should only have 1...  
	//  that is, we use the first...
		
	var nErrorCode 		= -1;
	var strErrorMessage = "";
	
	var oErrorNode 	= oErrorNodeList[0];
	var oErrorChild = oErrorNode.firstChild;

	while (null != oErrorChild)
	{
		if (oErrorChild.nodeType == 1)
		{
			var strNodeName = oErrorChild.nodeName;
			if ("ErrorCode".toLowerCase () == strNodeName.toLowerCase ()) {
				var strErrorText = GetNodeText (oErrorChild);
				nErrorCode = parseInt (GetNodeText (oErrorChild));
			}
			else if ("ErrorMessage".toLowerCase () == strNodeName.toLowerCase ()) {
				strErrorMessage = GetNodeText (oErrorChild);
			}
		}
		
		oErrorChild = oErrorChild.nextSibling;

	} // end loop through error message nodes

	//
	//  Now that we know what our values are...  well, look at 'em

	if (nErrorCode == 0)
	{
		return false;
	}
	
	var bShowMessage = true;
	if ((null != bAlertOnError) && (false == bAlertOnError))
		bShowMessage = false;
		
	if (bShowMessage) {
		alert("Error " + nErrorCode + ": " + strErrorMessage);
	}

	return true;
	
} // end check for xml error




OnBodyLoaded ();

