
/* ************************************************************/
// Build URL for XML
/* ************************************************************/
function randomString(len) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = len;
	var randomstring ='';
	for (var i=0; i<len; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

var OurURL = "";
function buildURL(sDate) {

	//OurURL = "http://" + URLBase + "/scripts/GetData.asp?UN=" + aToken+ "&comexrealtime=" + COMEXRealtime + "&lmerealtime=" + LMERealtime + "&currency=" + Currency;
	OurURL = "http://" + URLBase + "/subscription/xml/GetData.asp?UN=" + aToken + "&comexrealtime=" + COMEXRealtime + "&lmerealtime=" + LMERealtime + "&currency=" + Currency;
	if (sDate != "")
		OurURL = OurURL + "&limitdate=" + sDate;
		
	OurURL =    OurURL + "&symbols=";
	var needComma = false;
	if (LMESymbols != "") {
		if (needComma)
			OurURL = OurURL + ",";
		OurURL = OurURL + LMESymbols;
		needComma = true;
	}
	if (COMEXSymbols != "") {
		if (needComma)
			OurURL = OurURL + ",";
		OurURL = OurURL + COMEXSymbols;
		needComma = true;
	}
	if (Indexes != "") {
		if (needComma)
			OurURL = OurURL + ",";
		OurURL = OurURL + Indexes;
		needComma = true;
	}
	if (Currencies != "") {
		if (needComma)
			OurURL = OurURL + ",";
		OurURL = OurURL + Currencies;

		needComma = true;
	}
	
	if (TableSymbols != "") {
		if (needComma)
			OurURL = OurURL + ",";
		OurURL = OurURL + TableSymbols;
		needComma = true;
	}	
	//document.write(OurURL);
	OurURL = OurURL + "&rand=" + randomString(4);
	//try { document.getElementById('tempDiv').innerHTML = OurURL; }
	//catch (err) { }
	//alert(OurURL);
	return OurURL;
}


/* ************************************************************/
// End URL Building
/* ************************************************************/

/* ************************************************************/
// Basic AJAX Function used to instantiate objects
// Returns the proper object for your browser.
/* ************************************************************/
function makeObject(req)
{
    try { req = new XMLHttpRequest(); }
    // branch for IE/Windows ActiveX version
    catch (e) {
        //req = new ActiveXObject("Microsoft.XMLHTTP");
        try { req = new ActiveXObject("MSXML2.XMLHTTP"); }
			catch (e) {alert("Your browser does not support live Feed Screens.");}
	}
	
	return req;
}
/* ************************************************************/
// End Basic AJAX function
/* ************************************************************/

	/* ************************************************************/
	// Takes a symbol in and returns true if it is an Index
	/* ************************************************************/
	function testIndex(sSymbol) {
		var bIndex = false;
		sSymbol = sSymbol.toUpperCase();
		switch (sSymbol) {
			case "DJIAY":
			case "NSDQY":
			case "SP500":
				bIndex = true;
				break;		
		}
	
		return bIndex;
	}
	//function testIndex() {
	  //  return false;
	//}
	
/* ************************************************************/
// Start Feed Functions
//
// This function instantiates the object, makes the request and handles the reponse
// Once a response is received it is handled by the defined sub function and the data
// is updated.
/* ************************************************************/
var alertCount = 1;
	
var req = null;
function handleTimeout() {
	if (req != null) {	
		try { req.abort(); }
		catch (e) { }
		
	}
}
function LoadXML(){
   
	var Alertcounter = 0;
	var Stamp = new Date();
	var hours = Stamp.getHours();
	var minutes = Stamp.getMinutes();
	var seconds = Stamp.getSeconds();
	
	
	OurURL = buildURL(LimitDate);
	//alert("UserName = " + UserName);
	if ((UserName == "JWK") && (alertCount < 2)) {
	    alert("URL = " + OurURL);
	    alertCount += 1;
	    }
	//alert(OurURL);
	//alert("AJAX Req");
	// Handle cleaning up a previous request here to prepare for a current request
	handleTimeout();
	//curReq = null;
	
	//var req;
	req = makeObject(req);
	 
	req.onreadystatechange = function () {
		
		// only if req shows "loaded"
		if (req.readyState == 4) {
		
			// only if "OK"
			if (req.status && req.status == 200) {
			//alert("In LoadXML");
				var stuff = req.responseText;
				var response = req.responseXML.documentElement;
				
				// Check for error
				var x = response.getElementsByTagName("err");
				
				if (x.length > 0) 
				{
					// Get the error message
					
					for (m=0; m<x.length; m++) {
						
						var errEl = x[m].getElementsByTagName("ErrorMSG");
						if (errEl[0].firstChild.nodeValue == "InUse") {
							window.location = "/subscription/loginlimit.asp";
							//window.location = "/";
						}
					}
				}
				
				var accNode = response.getElementsByTagName("access");
				var sessNode = response.getElementsByTagName("mpsession");
				//alert("Access = " + accNode[0].firstChild.nodeValue + "\nsession = " + sessNode[0].firstChild.nodeValue);
				
				x = response.getElementsByTagName("quote");
				
				var symbolName;
				for(l=0; l<x.length; l++){ //Iterate though each quote
					var zz = x[l].getElementsByTagName("dispname");
					symbolName = zz[0].firstChild.nodeValue;
					var settledArr = x[l].getElementsByTagName("settleday");
					var settled = "false";
					try {settled = settledArr[0].firstChild.nodeValue; }
					catch (e) {}
					
					var hideLastArr = x[l].getElementsByTagName("hidelast");
					var hideLast = false;
					var hideXML = "false"
					try { hideXML = hideLastArr[0].firstChild.nodeValue; }
					catch (e) {}
					
					if  (hideXML == "True")
						hideLast = true;
						
					isIndex = false;
					var isIndex = testIndex(symbolName);
					var isCurrency = testCurrency(symbolName);
					
				    if ((symbolName != "") && (document.getElementById(symbolName+"dispname")) && (document.getElementById(symbolName+"dispname").innerHTML != symbolName)){
						if (checkObject(symbolName,"row"))
						{
							setObjectStyle(symbolName,"row","visibility","visible",false);
							setObjectStyle(symbolName,"row","display","",false);
						}
					}
					for(j=0; j<x[l].childNodes.length; j++) //Iterate through all the values
					{ 
					
						if(x[l].childNodes[j].nodeType != 1) continue;
						if(x[l].childNodes[j].nodeName != "dispname")
						{
							if((document.getElementById(symbolName+x[l].childNodes[j].nodeName)) || (x[l].childNodes[j].nodeName == "settleday") || (x[l].childNodes[j].nodeName == "time") || (x[l].childNodes[j].nodeName == "last") || (x[l].childNodes[j].nodeName == "lastnetchg") || (x[l].childNodes[j].nodeName == "lastinv"))
							{
								if ((!(isCurrency))) // Deal with non currencies, indexes included
								{
									if(x[l].childNodes[j].nodeName == "last") // Do coloring if last is selected.  This is our basis for comparison
									{	
									
										var current = "";
										if (document.getElementById(symbolName+x[l].childNodes[j].nodeName))
											current = document.getElementById(symbolName+x[l].childNodes[j].nodeName).innerHTML;
										
										if ((current != "") && (current.substring(0,1) != "&") && (current.substring(0,1) != "\n") && (!(isIndex)) && (!(firstTime))) 
										{
											if(current < correctValue(symbolName,x[l].childNodes[j].firstChild.nodeValue)) { 
												if (checkObject(symbolName,"time"))
												{
													setObjectStyle(symbolName,"time","backgroundColor","rgb(" + UpColor + ")",false);
													setObjectStyle(symbolName,"time","color","#FFFFFF",false);
												}
												if (checkObject(symbolName,"dispname")) 
												{
													setObjectStyle(symbolName,"dispname","backgroundColor","rgb(" + UpColor + ")",false);
													setObjectStyle(symbolName,"dispname","color","#FFFFFF",false);
												}
												
											}
											else if(current > correctValue(symbolName,x[l].childNodes[j].firstChild.nodeValue)) { 
												if (checkObject(symbolName,"time")) 
												{
													setObjectStyle(symbolName,"time","backgroundColor","rgb(" + DownColor + ")",false);
													setObjectStyle(symbolName,"time","color","#FFFFFF",false);
												}
												if (checkObject(symbolName,"dispname")) 
												{
													setObjectStyle(symbolName,"dispname","color","#FFFFFF",false);
													setObjectStyle(symbolName,"dispname","backgroundColor","rgb(" + DownColor + ")",false);
												}
												
											}
											else 
											{						
												var timeNode = x[l].getElementsByTagName("time");
												if (timeNode[0].firstChild)
												{
													var stampTime = timeNode[0].firstChild.nodeValue;
													
								
													var etimeArr = ESTTime.split(" ");
													var etimeDate = etimeArr[0];
													var etimeTime = MakeTime24Hr(etimeArr[1], etimeArr[2]);
													var eTime = getDateObject(etimeDate + " " + etimeTime);
													
													var stimeArr = stampTime.split(" ");
													var stimeDate = stimeArr[0];
													var stimeTime = MakeTime24Hr(stimeArr[1], stimeArr[2]);
													
													var sTime = getDateObject(stimeDate + " " + stimeTime);
													
													// Add 30 minutes to the timestamp if user is delayed.
													// This allows us to compare age to current time for color cleardown
													if (isDelayed)
														sTime = addMinutes(sTime,31);
														
													var Offset = 0;
													if (document.getElementById(symbolName+"offset"))
														Offset = document.getElementById(symbolName+"offset").value;
													var curHours = eTime.getHours();
													var Offset = parseInt(Offset) + parseInt(curHours);
													eTime.setHours(Offset);
													
													var Diff = ((eTime.getTime() - sTime.getTime()) / (1000 ));
												
													if (Diff > HoldTime)
													{ 
													     
														// Clear down color change using defined colors
														if (checkObject(symbolName,"time")) 
														{
															setObjectStyle(symbolName,"time","color","rgb(" + TextColor + ")",false);
															//alert("Time Color = " + getStyle(symbolName+"row","background-color"));
															setObjectStyle(symbolName,"time","backgroundColor",getStyle(symbolName+"row","background-color"),false);	
														}
														if (checkObject(symbolName,"dispname")) 
														{
															setObjectStyle(symbolName,"dispname","color","rgb(" + TextColor + ")",false);
															setObjectStyle(symbolName,"dispname","backgroundColor",getStyle(symbolName+"row","background-color"),false);
														}
													}												
												}
											}
										}
									}
									else if ((x[l].childNodes[j].nodeName == "netchg") || (x[l].childNodes[j].nodeName == "offnetchg") || (x[l].childNodes[j].nodeName == "lastnetchg") || (x[l].childNodes[j].nodeName == "opennetchg"))
									{
										// Deal with all possible change valus here (netchg, offnetchg,lastnetchg opennetchg	
										var thisNode = x[l].childNodes[j].firstChild;								
										if (thisNode)
										{
											var thisName = x[l].childNodes[j].nodeName;
											if (thisNode.nodeValue < 0) setObjectStyle(symbolName,thisName,"color","rgb(" + DownColor + ")",true);
											else if (thisNode.nodeValue > 0) setObjectStyle(symbolName,thisName,"color","rgb(" + UpColor + ")",true);
											else setObjectStyle(symbolName,thisName,"color","rgb(" + TextColor + ")",true);
											
											// Also check for a footer for change
											if (thisNode.nodeValue < 0) setObjectStyle(symbolName,thisName + "_footer","color","rgb(" + DownColor + ")",true);
											else if (thisNode.nodeValue > 0) setObjectStyle(symbolName,thisName + "_footer","color","rgb(" + UpColor + ")",true);
											else setObjectStyle(symbolName,thisName + "_footer","color","rgb(" + TextColor + ")",true);

										}
									}
									else if (x[l].childNodes[j].nodeName == "settleday")
									{
									   
										// Update settle is settleday becomes true.
										var thisNode = x[l].childNodes[j].firstChild;							
										if (thisNode)
										{
											// Removing using the S for settled contracts
										    if (!isLMESymbol(symbolName))
											    if (thisNode.nodeValue == "True") 
												{
													// Get the last and olsettle values here
													// If last == oldsettle then put the 's' - else do not
													// Get the last and olsettle values here
													// If last == oldsettle then put the 's' - else do not
													var lastNode = x[l].getElementsByTagName("last");
													var lastValue = 0;
													if (lastNode[0].firstChild)
													{
														lastValue = lastNode[0].firstChild.nodeValue;
													}
													
													var oldsettleNode = x[l].getElementsByTagName("oldsettle");
													var oldsettleValue = 0;
													if (oldsettleNode[0].firstChild)
													{
														oldsettleValue = oldsettleNode[0].firstChild.nodeValue;
													}
													//alert("oldsettle = " + oldSettleValue + "\nLast = " + lastValue); 
													if (lastValue == oldsettleValue)
														setObjectHTML(symbolName,"settled","s",true);
												}
											
										}
									}
									else if (x[l].childNodes[j].nodeName == "month")
									{
										// Month cannot be written as displayed in the XML.  Helper function properly formats
										var thisNode = x[l].childNodes[j].firstChild;								
										if (thisNode)
											if ((symbolName.substring(0,1) == "S") && (symbolName.substring(0,1) != "SI"))
												setObjectHTML(symbolName,"month",thisNode.nodeValue,true);
											else 
												setObjectHTML(symbolName,"month",makeMonthYearCOMEX(thisNode.nodeValue,symbolName),true);
									}
									else if (x[l].childNodes[j].nodeName == "oldsettle") {
									
										var thisNode = x[l].childNodes[j].firstChild;							
										if (thisNode)
										{
										    // test to see if this is COMEX - only mark for COMEX
										    var useSettle = false;
										    if (!isLMESymbol(symbolName) || isLMESymbol(symbolName)) {
										        useSettle = true;
										    }
										    if (useSettle) {
											    if (settled == "True")  {
											    	// Change to only set S on COMEX
											    	if (!isLMESymbol(symbolName))
												    setObjectHTML(symbolName,"oldsettle",correctValue(symbolName,thisNode.nodeValue)+"s",true); 
												else
													   setObjectHTML(symbolName,"oldsettle",correctValue(symbolName,thisNode.nodeValue),true); 
											    }
											    else
											        setObjectHTML(symbolName,"oldsettle",correctValue(symbolName,thisNode.nodeValue)+"y",true);
											}
											else
											     setObjectHTML(symbolName,"oldsettle",correctValue(symbolName,thisNode.nodeValue),true);
											
										}
									}
									//else { alert ("Nodename is " + x[l].childNodes[j].nodeName); }
									// Update values with that is present in XML here.
									// We ignore certain categories here as they are handled above.
									var thisNode = x[l].childNodes[j].firstChild
									var isSpread = false;
									if (symbolName.indexOf("MUL1F") != -1) 
									    var isSpread = true;						
									if (thisNode)
									{
										if (x[l].childNodes[j].nodeName == "time")
										{
											// Split on the " ",  make 24HR, then show the 2nd half.
											var timeStr = thisNode.nodeValue.split(" ");
											var quoteDateTemp = timeStr[0];
											var quoteDateArr = quoteDateTemp.split("/");
											var monthName = "";
											
											switch(quoteDateArr[0]) {
											    case "1":
											        monthName = "Jan";
											        break;
											     case "2":
											        monthName = "Feb";
											        break;
											     case "3":
											        monthName = "Mar";
											        break;
											     case "4":
											        monthName = "Apr";
											        break;
											     case "5":
											        monthName = "May";
											        break;
											     case "6":
											        monthName = "Jun";
											        break;
											     case "7":
											        monthName = "Jul";
											        break;
											     case "8":
											        monthName = "Aug";
											        break;
											     case "9":
											        monthName = "Sep";
											        break;
											     case "10":
											        monthName = "Oct";
											        break;
											     case "11":
											        monthName = "Nov";
											        break;
											     case "12":
											        monthName = "Dec";
											        break;
											     default:
											        monthName = quoteDateArr[0];
											        break;
											}
											var quoteDate = quoteDateArr[1] + "/" + quoteDateArr[0];
											var quoteTime = MakeTime24Hr2(timeStr[1], timeStr[2],false);
											setObjectHTML(symbolName,"time",quoteDate + " " + quoteTime,true);
											
											    if (document.getElementById(symbolName + "timeonly"))
												setObjectHTML(symbolName,"timeonly",quoteTime,true);
											    if (document.getElementById(symbolName + "timeonly2"))
												setObjectHTML(symbolName,"timeonly2",quoteTime,true);
											    if (document.getElementById(symbolName + "dateonly"))
												setObjectHTML(symbolName,"dateonly",quoteDateArr[1] + " " + monthName,true);
											    if (document.getElementById(symbolName + "dateonly2"))
												setObjectHTML(symbolName,"dateonly2",quoteDateArr[1] + " " + monthName,true);
										}
										else if ((x[l].childNodes[j].nodeName == "netchg") || (x[l].childNodes[j].nodeName == "offnetchg") || (x[l].childNodes[j].nodeName == "lastnetchg") || (x[l].childNodes[j].nodeName == "opennetchg"))
										{
										
										    if (!(isSpread)) {
										        
											    //var num = thisNode.nodeValue;
											    
											    var num = parseFloat(correctValue(symbolName,thisNode.nodeValue));
											    //if (symbolName.indexOf("HG") > 0)
											        //alert("Setting " + symbolName + "." +x[l].childNodes[j].nodeName +"\nOrig= " +  thisNode.nodeValue + "\n New=  " + correctValue(symbolName,thisNode.nodeValue));
											      //  alert("using num = " + num + " - oldvalue = " + thisNode.nodeValue);
											    if (document.getElementById(symbolName+"market"))
												    if (document.getElementById(symbolName+"market").value == "COMEX") {
													    setObjectHTML(symbolName,x[l].childNodes[j].nodeName,num.toFixed(iDecPrec),true);	
													}
												    else
														if (DesiredLME == "mt")
															setObjectHTML(symbolName,x[l].childNodes[j].nodeName,num.toFixed(2),true);
														else
															setObjectHTML(symbolName,x[l].childNodes[j].nodeName,num.toFixed(iDecPrec),true);
											    else
												    setObjectHTML(symbolName,x[l].childNodes[j].nodeName,num,true);
											}
											else {
											    setObjectHTML(symbolName,x[l].childNodes[j].nodeName,"&nbsp;",true);
											    setObjectHTML(symbolName,"high","&nbsp;",true);
											    setObjectHTML(symbolName,"low","&nbsp;",true);
											    setObjectHTML(symbolName,"dispname","<span style='padding-left:20px;'>Spread MUL_</span>",true);
										    }
										}
										else if ((x[l].childNodes[j].nodeName != "dispname") && (x[l].childNodes[j].nodeName != "time") && (x[l].childNodes[j].nodeName != "month") && (x[l].childNodes[j].nodeName != "vol") && (x[l].childNodes[j].nodeName != "bidvol") && (x[l].childNodes[j].nodeName != "askvol") && (x[l].childNodes[j].nodeName != "tradevol") && (x[l].childNodes[j].nodeName != "openint") && (x[l].childNodes[j].nodeName != "oldsettle"))
										{
											if ((x[l].childNodes[j].nodeName != "last") || (x[l].childNodes[j].nodeName == "last") && (!hideLast)) {
											//if (x[l].childNodes[j].nodeName == "last")
												//alert("Symbolname = " + symbolName + " hidelast = " + hideLast);
												//if (symbolName.indexOf("NG") >=0)
													//alert("Calling setObjectHTML on " + symbolName + x[l].childNodes[j].nodeName + "hidelast = " + hideLast);
												setObjectHTML(symbolName,x[l].childNodes[j].nodeName,correctValue(symbolName,thisNode.nodeValue),true);
										   }
										   if (isSpread) {
										        if ((x[l].childNodes[j].nodeName == "bid")  || (x[l].childNodes[j].nodeName == "ask")){
													if (x[l].childNodes[j].nodeValue > 0) setObjectStyle(symbolName,thisName,"color","rgb(" + UpColor + ")",true);
													if (x[l].childNodes[j].nodeValue < 0) setObjectStyle(symbolName,thisName,"color","rgb(" + DownColor + ")",true);
													if (x[l].childNodes[j].nodeValue == 0) setObjectStyle(symbolName,thisName,"color","rgb(0,0,0)",true);
													
										            // Check for the existance of symbolNamespreadresult - if exists grab the 3M bid price and do the math!
										            if (document.getElementById(symbolName + "spreadresult") + x[l].childNodes[j].nodeName) {
										                
										                var s3MSymbol = "";
										                if (symbolName.indexOf("PMUL1F") > 0)
										                    s3MSymbol = symbolName.substring(0,3) + "DMUL3M";
										                else
										                    s3MSymbol = symbolName.substring(0,4) + "MUL3M";
    										                
										                var s3mVal = findXMLValue(req.responseXML,s3MSymbol, x[l].childNodes[j].nodeName);
										                s3mVal = correctValue(s3MSymbol,s3mVal);
										                
										                var finalValue = s3mVal;
										                if (s3mVal > 0)
										                    finalValue = correctValue(s3MSymbol,parseFloat(correctValue(s3MSymbol,s3mVal)) + parseFloat(correctValue(symbolName,thisNode.nodeValue)));
										                else if (s3mVal == 0)
										                    finalValue = "";
										                        
										                setObjectHTML(symbolName,"spreadresult" + x[l].childNodes[j].nodeName,finalValue,true);
										            }
										            
										            
										        }  
										    }
											
									    }
									    else {
										// This is all ignored nodes
										// Handle vol and openint here - they just get assigned
										if ((x[l].childNodes[j].nodeName == "openint")  || (x[l].childNodes[j].nodeName == "vol") || (x[l].childNodes[j].nodeName == "bidvol") || (x[l].childNodes[j].nodeName == "askvol") || (x[l].childNodes[j].nodeName == "tradevol")){
											setObjectHTML(symbolName,x[l].childNodes[j].nodeName,thisNode.nodeValue,true);
										}
									    }
									}
									else {
									    // We have a node that doesn't exist.  If it's time check for timeonly and dateonly
									    if (x[l].childNodes[j].nodeName == "time")
										{
											// Split on the " ",  make 24HR, then show the 2nd half.
											var timeStr = thisNode.nodeValue.split(" ");
											var quoteDateTemp = timeStr[0];
											var quoteDateArr = quoteDateTemp.split("/");
											var quoteDate = quoteDateArr[1] + "/" + quoteDateArr[0];
											var quoteTime = MakeTime24Hr(timeStr[1], timeStr[2]);
											
											
										}
									}
								}
								else if (isCurrency)
								{
										
								   var thisNode = x[l].childNodes[j];
								   var thisValue = 0;
								   thisValue = thisNode.firstChild.nodeValue; 
								   if (thisValue == null)
								   	thisValue == thisNode.nodeValue;
								   
								 	//document.getElementById('tempDiv').innerHTML += "<br>Currency " + symbolName + " " + thisNode.nodeName + " val = " + thisValue;
								   try { thisValue = new Number(thisValue); }
								   catch (err) { document.getElementById('tempDiv').innerHTML += "<br>Err setting to number " + err;}
								    if (thisValue != null)
									{ 
										//alert("Not null - " + thisNode.nodeName);
										//document.getElementById('tempDiv').innerHTML += "<br>Not null - " + thisNode.nodeName;
									    if (thisNode.nodeName == "last") {
										
											//do a check if this is our specific currency for the feed, is so update that var
												
												 if (symbolName.toUpperCase() == Currency) {
													//alert("setting currency rate to " + thisValue);
													try { document.getElementById('Feed_Rate').innerHTML = thisValue.toFixed(6); }
													catch (ex) { }
													try { CurrencyRate = thisValue;}
													catch (ex) {  }
													
													
												}
													
									    	//document.getElementById('tempDiv').innerHTML += "<br>In last " + thisValue;
									    	try {thisValue = thisValue.toFixed(4);}
									    	catch (err) { document.getElementById('tempDiv').innerHTML += "<br>Error setting toFixed : " + err; alert("err"); }
									        //document.getElementById('tempDiv').innerHTML += "<br>Looking for el:" + symbolName.toLowerCase() + "last";
											//alert("Checking " + symbolName.toLowerCase() + "last to " + thisValue);
									         setObjectHTML(symbolName.toLowerCase(),"last",thisValue,true); 
									     }   
									      if (thisNode.nodeName == "lastinv") {
									      //	document.getElementById('tempDiv').innerHTML += "<br>In lastinv";
									      	try {
										      	thisValue = thisValue.toFixed(4); // Fix it at 4 decimal places
												}
											catch (err) { }
		
										// document.getElementById('tempDiv').innerHTML += "<br>Looking for el:" + symbolName.toLowerCase() + "lastinv";
										 setObjectHTML(symbolName.toLowerCase(),"lastinv",thisValue,true); 
									     }
										 if (thisNode.nodeName == "time") 
										 {
												var timeStr = thisNode.firstChild.nodeValue.split(" ");
												var quoteTime = MakeTime24Hr2(timeStr[1], timeStr[2],false);
												setObjectHTML("currency","time","Last Update: " + quoteTime + " EST",true); 
												
												if (symbolName.toUpperCase() == Currency)
												{
												try { document.getElementById('Feed_Rate_Time').innerHTML = quoteTime + " EST"; }
													catch (ex) { }
												}
										 }
									}
								}
							}	// End If Node exists
							else { //alert("Node for " + symbolName+x[l].childNodes[j].nodeName + " does not exist"); 
							}
							
							 if ((x[l].childNodes[j].nodeName == "ask") || (x[l].childNodes[j].nodeName == "bid") || (x[l].childNodes[j].nodeName == "last")) {
										    // Have bid / ask / last check the other 2 nodes as well and clear them down if *not* present in the XML.
										    // This will lead to redundant checks but is the only way we can guarantee that we clear down the other 2 if one is received.
										    if ((!testIndex(symbolName)) && (!isCurrency)) {
										        var lastArr = x[l].getElementsByTagName("last");
										        var last = "";
					                            try {last = lastArr[0].firstChild.nodeValue; }
					                            catch (e) { 
					                                //alert ("Could not grab last  for " + symbolName);
													setObjectHTML(symbolName,"last","",true);
					                            }
					                            
    					                        
					                            var bidArr = x[l].getElementsByTagName("bid");
										        var bid = "";
					                            try {bid = bidArr[0].firstChild.nodeValue; }
					                            catch (e) { 
					                                //alert ("Could not grab bid for " + symbolName);
					                                setObjectHTML(symbolName,"bid","",true);
					                            }
					                            
    					                        
					                            var askArr = x[l].getElementsByTagName("ask");
										        var ask = "";
					                            try {ask = askArr[0].firstChild.nodeValue; }
					                            catch (e) { 
					                                //alert ("Could not grab ask  for " + symbolName);
					                                setObjectHTML(symbolName,"ask","",true);
					                            }
												
												var litArr = x[l].getElementsByTagName("lastistrade");
										        var lit = "";
					                            try {lit = litArr[0].firstChild.nodeValue; }
					                            catch (e) { 
					                                //alert ("Could not grab ask  for " + symbolName);
					                                setObjectHTML(symbolName,"lastistrade","",true);
					                            }
					                            
					                        }
										    
										}
						} // End if Node != "dispname"
					} // End Child Iteration
				}// End Quotes Iteration
				if (firstTime)
					firstTime = false;	
				else
				{
					// Build a new date string
					/*var tDate = new Date();
					var tMonth = parseInt(tDate.getMonth()) + 1;
					var tDay = tDate.getDate();
					var tYear = tDate.getFullYear();
					
					var tHour = tDate.getHours();
					var tMin = tDate.getMinutes() - 3;
					var tSec = tDate.getSeconds();
					
					LimitDate = tMonth + "/" + tDay + "/" + tYear + "%20" + tHour + ":" + tMin + ":00";*/
				}
			} // End if Req == 200
			else {
				//alert("There was a problem retrieving the XML data:\n" +
				  //  req.statusText);
			 }
		} // End if Status == 4
	}	
		
	// Make request
	req.open("GET", OurURL,  true);
	req.setRequestHeader("Cache-Control","no-cache"); 
	req.setRequestHeader("Pragma","no-cache"); 
	req.send(null);
	// Now put in a timeout handler to abort the query if it's time for the next refresh
	//var timeoutRefresh = refreshTime - 500; // Handle timeout 500 miliseconds before next query
	//curReq = req;
	//var loadXMLTimeout = setTimeout("handleTimeout()", timeoutRefresh);
	var clock3 = setTimeout("LoadXML()",refreshTime);

 
}

	/* ************************************************************/
	// This function takes in a time string and a time of 
	// day designate
	// e.g 02:54:03, PM
	// It then formats and returns a 24 HR time string
	/* ************************************************************/
	function MakeTime24Hr(time,designate){
	    return MakeTime24Hr2(time,designate,true);
	}
	function MakeTime24Hr2(time,designate,useSeconds) {
		var timeSTR = "";
		var theTime = ""
		if (time != null)
			theTime = time;
		timeSTR	= theTime.split(":");
		
		if (time == "1/1/ undefined")
			theTime = "";
		if (timeSTR.length > 2) {
			var locHours = timeSTR[0];
			var locMins = timeSTR[1];
			var locSecs = timeSTR[2];
			if (designate == "PM")
			{
				if (locHours == 12) {
					var retString = locHours + ":" + locMins;
					if (useSeconds)
						    retString +=  ":" + locSecs;
				    return retString;
				    }
				else
				{
					locHours = parseInt(locHours) + 12;
					var retString = locHours + ":" + locMins;
					if (useSeconds)
						    retString +=  ":" + locSecs;
					return retString;
				}
			}
			else if (designate == "AM")
				if (locHours == 12)
				{
					locHours = "0"
					locMins = timeSTR[1];
					locSecs = timeSTR[2];
					var retString = locHours + ":" + locMins;
					if (useSeconds)
						    retString +=  ":" + locSecs;
					return retString;
				}
				else 
				{
					if (locHours < 10)
					{
						locHours = "0" + locHours;
						locMins = timeSTR[1];
						locSecs = timeSTR[2];
						var retString = locHours + ":" + locMins;
						if (useSeconds)
						    retString +=  ":" + locSecs;
						return retString;
					}
					else {
					    var retString = locHours + ":" + locMins;
						    if (useSeconds)
							retString +=  ":" + locSecs;
						    return retString;
						}
				}

			else {
			    var retString = locHours + ":" + locMins;
			    if (useSeconds)
				retString +=  ":" + locSecs;
			    return retString;
			}
	        }
	        else
	        	return theTime;
	}
	/* ************************************************************/
	// This function retrieves a style from a passed element
	// and returns the style itself.  Should work with most browsers
	/* ************************************************************/
	function getStyle(Element,StyleName) {
		var x = document.getElementById(Element);
		if (x)
		    if (x.currentStyle){
			    var y = x.currentStyle[StyleName];
			    y = x.style.color;
		    }
		    else if (window.getComputedStyle) {
			    var y = window.getComputedStyle(x,null).getPropertyValue(StyleName);
		    }
		    else if (document.defaultView.getComputedStyle){
			    var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(StyleName);
		    }
		    
		return y;
	}
	/* ************************************************************/
	// Takes a supplied date string in the format MM/DD/YYYY HH:MM:SS
	// and returns a properly formatted date object for comparison
	/* ************************************************************/
	function getDateObject(dString) {
		var dateStringTemp = dString.split(" ");
		var timeString = dateStringTemp[1];
		var dateString = dateStringTemp[0];
		var retDate = new Date();
		
		// Now split the Dates
		tempString = dateString.split("/");
		retDate.setDate
		retDate.setMonth(tempString[0]);
		retDate.setDate(tempString[1]);
		retDate.setYear(tempString[2]);
		
		// Set Time
		tempString = timeString.split(":");
		retDate.setHours(tempString[0]);
		retDate.setMinutes(tempString[1]);
		retDate.setSeconds(tempString[2]);
		
		return retDate;
	}
	/* ************************************************************/
	// Takes a full Month and a COMEX symbol and returns the appropriate
	// 3 Letter month and 2 digit year: e.g. Sep 07
	// for display
	/* ************************************************************/
	function makeMonthYearCOMEX(thisMonth,Symbol) {
		var theYear = Symbol.substring(Symbol.length - 2, Symbol.length);
		var theMonth = thisMonth.substring(0,3);
		
		return theMonth + " " + theYear;
	}
	/* ************************************************************/
	// Takes a Date() object and the # of minutes to add
	// Adds minutes to a Date() object using ms and then converts back
	// to a Date() object using the proper constructor.  Returns
	// a Date() object.
	/* ************************************************************/
	function addMinutes(dateTime, thisMinutes) {
		// Takes a date object and a # of minutes.  
		// Converts date to # of MS since 1/1/1970
		// Adds appropriate amount of MS by minutes.
		// Converts back to date object, returns date object.
		
		var length = thisMinutes * 60 * 1000;
		var thisSeconds = dateTime.getTime();
		thisSeconds += length;
		var dt = new Date(thisSeconds);
		return dt;
	}
	

	
	/* ************************************************************/
	// Takes a symbol in and returns true if it is a Currency
	/* ************************************************************/
	function testCurrency(sSymbol) {
		var bCurrency = false;
		
		switch (sSymbol.toUpperCase()) {
			case "ANG":
			case "ARS":
			case "AUD":
			case "BDT":
			case "BGN":
			case "BOB":
			case "BRL":
			case "CAD":
			case "CHF":
			case "CLP":
			case "CNY":
			case "COP":
			case "CUP":
			case "CZK":
			case "DKK":
			case "EGP":
			case "EUR":
			case "GBP":
			case "HKD":
			case "HUF":
			case "IDR":
			case "ILS":
			case "INR":
			case "JOD":
			case "JPY":
			case "KRW":
			case "LVL":
			case "MNT":
			case "MXN":
			case "MYR":
			case "NGN":
			case "NOK":
			case "NZD":
			case "PEN":
			case "PHP":
			case "PKR":
			case "PLN":
			case "RUB":
			case "SAR":
			case "SEK":
			case "SGD":
			case "THB":
			case "TRY":
			case "TWD":
			case "UAH":
			case "UYU":
			case "VEH":
			case "VEF":
			case "VND":
			case "ZAR":
			case "CAD":
			case "EUR":
			case "JPY":
			case "FXYEN":
			case "FXGBP":
			case "FXEUR":
				bCurrency = true;
				break;		
		}
		return bCurrency;
	}
	
	
	/* ************************************************************/
	// This function is only used to increment the ESTTime variable
	//  Returns a Date() object
	/* ************************************************************/
	function incrementTime(stringTime) {
		
		var tempTime = new Date();
		var tempTime = getDateObject(stringTime);
		
		tempTime.setSeconds(tempTime.getSeconds() + 1);
		ESTTime = tempTime.getMonth() + "/" + tempTime.getDate() + "/" + tempTime.getFullYear() + " " + tempTime.getHours() + ":" + tempTime.getMinutes() + ":" + tempTime.getSeconds();
		setTimeout("incrementTime(ESTTime)",1000);
		return tempTime;
	}
	/* ************************************************************/
	// Checks to see if an object exists in DOM - returns a boolean
	/* ************************************************************/
	function checkObject(sSymbol,suffix) {
		var bExists = false;
		
		if (document.getElementById(sSymbol+suffix))
			bExists = true;
			
		return bExists
	}
	
	/* ************************************************************/
	// Sets the style of an object.  The last parameter indicates
	// whether to call checkObject or not to verify object existence
	/* ************************************************************/
	function setObjectStyle(sSymbol,suffix,parameter,value,bDoCheck) {
		var bExists = false;
		if (bDoCheck)
			bExists = checkObject(sSymbol,suffix);
		else
			bExists = true;
			
		if (bExists)
			if (parameter == "color")
				document.getElementById(sSymbol+suffix).style.color = value
			else if (parameter == "backgroundColor")
				document.getElementById(sSymbol+suffix).style.backgroundColor = value;
			else if (parameter == "visibility")
				document.getElementById(sSymbol+suffix).style.visibility = value;
			else if (parameter == "display")
				document.getElementById(sSymbol+suffix).style.display = value;
	}
	
	/* ************************************************************/
	// Sets the innerHTML tag of an object.  The last parameter 
	// indicates whether to call checkObject or not to verify
	// object existence.
	/* ************************************************************/
	function setObjectHTML(sSymbol,suffix,value,bDoCheck) {			
		var bExists = false;
		if (bDoCheck)
			bExists = checkObject(sSymbol,suffix);
		else
			bExists = true;
		
		//if ((sSymbol.indexOf("CL") >= 0) || (sSymbol.indexOf("NG") >=0)) 
			//alert("Checking " + sSymbol + " " + suffix + " = " + bExists);
		if (bExists) {
			var elementArr = document.getElementById(sSymbol+suffix);
			elementArr.innerHTML = value;				
		}

		// Also check for a potential footer element here
		
		if ((sSymbol.indexOf("CL") >= 0) || (sSymbol.indexOf("NG") >=0)) {
			bExists = checkObject(sSymbol,suffix + "_footer");
			//alert("Checking " + sSymbol + " " + suffix + "_footer = " + bExists);
			if (bExists)
				document.getElementById(sSymbol+suffix+"_footer").innerHTML = value;
		}
		
	}
	/* ************************************************************/
	// This function takes in a numerical value and corrects it
	// based on known inconsistencies in data for Silver and Copper
	/* ************************************************************/
	function correctValue(sSymbol,value) {

		if (isNumeric(value))
		{
			var Metal;
			var Market;
			// Correct decimal precision
			var dPrec = 2;
			if ((sSymbol.substring(0,1) == "R") || (sSymbol.substring(0,1) == "B")) // COMEX Composite or floor
			{
				Metal = sSymbol.substring(1,3);
				Market = "COMEX";
				dPrec = iDecPrec;
			}
			else if (isLMESymbol(sSymbol))
			{
			    //alert("Setting LME " + sSymbol);
			        Market = "LME";
				dPrec = iDecPrec;
				if (sSymbol.substring(0,1) == "L")
					Metal = sSymbol.substring(1,3);	
				else
					Metal = sSymbol.substring(0,2);
			}
			else if ((sSymbol.substring(0,3) == "SAL") || (sSymbol.substring(0,3) == "SCU") || (sSymbol.substring(0,3) == "SZN") || (sSymbol.substring(0,3) == "SRU") || (sSymbol.substring(0,3) == "SFU") || (sSymbol.substring(0,3) == "SWR") || (sSymbol.substring(0,3) == "SRB") || (sSymbol.substring(0,3) == "SPB")) {
				Market = "Shanghai";
				Metal = sSymbol.substring(0,3);
			}
			else
			{
			    Market = "COMEX";
				Metal = sSymbol.substring(0,2);
				dPrec = iDecPrec;
			}
			// End Decimal precision correction
			
			// Correct for different Weights here
			var StoredWeight;
			
			
			switch (Metal) {
			    case "AA":
			        StoredWeight = "mt";
			        break;
			    case "AH":
			        StoredWeight = "mt";
			        break;
			    case "AL":
			        StoredWeight = "lb";
			        break;
			    case "CA":
			        StoredWeight = "mt";
			        break;
			    case "HG":
			        StoredWeight = "lb";
			        break;
			    case "NA":
			        StoredWeight = "mt";
			        break;
			    case "PB":
			        StoredWeight = "mt";
			        break;
			    case "NI":
			        StoredWeight = "mt";
			        break;
			    case "CO":
			       	StoredWeight = "mt";
			        break;
			    case "MO":
			    	StoredWeight = "mt";
			        break;
			    case "SN":
			        StoredWeight = "mt";
			        break;
			    case "ZS":
			        StoredWeight = "mt";
			        break;
			    case "GC":
			        StoredWeight = "oz";
			        break;
			    case "SI":
			        StoredWeight = "oz";
			        break;
			    case "PA":
			        StoredWeight = "oz";
			        break;
			    case "PL":
			        StoredWeight = "oz";
			        break;
			    case "NG":
			        StoredWeight = "mm";
			        break;
			    case "CL":
			        StoredWeight = "mm";
			        break;
			    case "FF":
			    case "FM":
			    	StoredWeight = "mt";
			    	break;
			  case "SAL":
			  case "SCU":
			  case "SZN":
			  case "SRU":
			  case "SFU":
			  case "SPB":
			  case "SWR":
			  case "SRB":
				StoredWeight = "mt";
				break;
			}
			
			var DesiredUnits;
			if (Market == "COMEX")
			    DesiredUnits = DesiredCOMEX;
			else if (Market == "Shanghai") {
				DesiredUnits = DesiredCOMEX;
				if (DesiredUnits == "mt")
					dPrec = 2;
				else
					dPrec = 4;
			}
			else { 
			    DesiredUnits = DesiredLME;
			}
			   
			    
			// Override dPrec is DesiredUnits == "mt"
			if (DesiredUnits == "mt")
			    dPrec = 2;
			    
			 //override dPrec for Officials / Unofficials
			 if ((sSymbol.indexOf('LMO') > 0) || (sSymbol.indexOf('LMU') > 0))
			    if (DesiredUnits == "mt") 
			            dPrec = 2;
			    else
			        dPrec = iDecPrec;
			    
			 // override dPrec for Warehouse
			 if (sSymbol.indexOf("WLMT") > 0)
			    dPrec = 0;
			    
			var weightFactor;  
			
			if ((StoredWeight == "oz") || (StoredWeight == "mm")) {
			    weightFactor = 1;
			    if (Metal == "NG")
			        dPrec = 4;
			    else if (Metal == "SI")
			        dPrec = 3;
			    else
			        dPrec = 2;
			}
			else {
			        if (StoredWeight != DesiredUnits)
			            weightFactor = ConvertValue(1,StoredWeight,DesiredUnits);
			        else
			            weightFactor = 1;
			}
			// End Weights Correction
                        if (testIndex(sSymbol)) {
			    dPrec = 2;
			    weightFactor = 1;
			    }
			    
			// Correct for incorrectly stored values
			var divisor = 1;
			switch(Metal) {
				case "HG" :
					divisor = CopperDivisor;
					//if (sSymbol.indexOf("HG") > 0)
					//    alert("Vale = " + value + " - Divisor = " + divisor);
					//alert(CopperDivisor); = .01
					if (CopperDivisor < 1)
					    dPrec = 2;
	
					break;
				case "SI" :
					divisor = SilverDivisor;
					if (SilverDivisor < 1)
					    dPrec = 2;
					break;
			}
			// End value correction
			
			var thisNum = parseFloat(value * weightFactor / divisor);
			thisNum = thisNum.toFixed(dPrec);
		}
		else {
		    //alert("Found non number for " + sSymbol + " - " + value);
			thisNum = value;
		}
			
		return thisNum;
	}
	/* ************************************************************/
	// Tests if the passed text is numeric or text.  Returns bool
	/* ************************************************************/
	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;
	}
	/* ************************************************************/
	// Defining the ESTTime using the variables from the params
	/* ************************************************************/
	// Format as 24Hr
	var oldTimeArr = ESTTime.split(" ");
	ESTTime = oldTimeArr[0] + " " + MakeTime24Hr(oldTimeArr[1],oldTimeArr[2]);
	// Set clock to increment the ESTTime value
	setTimeout("incrementTime(ESTTime)",1000);
	
	/*************************************************************/
	// Define Weight Conversion functions
	/************************************************************/
	function convertLBtoMT(OriginalValue) 
	{
		var NewValue = convertLBtoKG(OriginalValue);
		NewValue = NewValue * 1000;
		return NewValue;
	}
	function convertLBtoKG(OriginalValue) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		var NewValue = OriginalValue * 2.20462262;
		return NewValue;
	}
	function convertMTtoKG(OriginalValue) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		return OriginalValue/1000;
	}
	function convertMTtoLB(OriginalValue) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		var NewValue = convertMTtoKG(OriginalValue);
		NewValue = convertKGtoLB(NewValue);
		return NewValue;
	}
	function convertKGtoLB(OriginalValue) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		return OriginalValue/2.20462;
	}
	function convertKGtoMT(OriginalValue) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		return OriginalValue * 1000;
	}
	function ConvertValue(OriginalValue,thisStoredUnit,thisDesiredUnit) 
	{
	    //OriginalValue = parseFloat(OriginalValue);
		var NewValue = 1;

		if (thisStoredUnit == "mt")
		{
			if (thisDesiredUnit == "kg")
			{
				NewValue = convertMTtoKG(OriginalValue);
			}
			else if (thisDesiredUnit == "lb")
			{
				NewValue = convertMTtoLB(OriginalValue);
			}
		}
		else if (thisStoredUnit == "lb")
		{
			if (thisDesiredUnit == "kg")
			{
				NewValue = convertLBtoKG(OriginalValue);
			}
			else if (thisDesiredUnit == "mt")
			{
				NewValue = convertLBtoMT(OriginalValue);
			}
		}
		else if (thisStoredUnit == "kg")
		{
			if (thisDesiredUnit == "mt")
			{
				NewValue = convertKGtoMT(OriginalValue);
			}
			else if (thisDesiredUnit == "lb")
			{
				NewValue = convertKGtoLB(OriginalValue);
			}
		}

		return NewValue;
	}
	
function findXMLValue(XMLText, ssymbolName, Value) {
    var Collection = XMLText.documentElement.getElementsByTagName("quote");
    //alert("Found " + Collection.length + " elements");
    var returnVal = 0;
    for (var l=0; l<Collection.length; l++) {
	    
	    // alert(Collection.nodeName + " " + Collection.nodeValue);
	    
		var XMLsymbolNameArr = Collection[l].getElementsByTagName("dispname");
		var XMLsymbolName = XMLsymbolNameArr[0].firstChild.nodeValue;
		
		if (XMLsymbolName == ssymbolName) {
    		var valueArr = Collection[l].getElementsByTagName("" + Value + "");
   		    var valueNum = 0;
   		    try { valueNum = valueArr[0].firstChild.nodeValue;    }
   		    catch (e) { }
		    returnVal = valueNum;
		    l = Collection.length; // to exit for loop
		}								                
    }
    
    return returnVal;
}
function isLMESymbol(symbolName) {
	var isLME = false;
	if ((symbolName.substring(0,1) == "L") || (symbolName.substring(0,2) == "FF") || (symbolName.substring(0,2) == "FM"))
		isLME = true;
	return isLME 
}
