/*

 !!DEPRECIATED!! -- SHOULD BE USING NEW LoopNet JS CORE

 * -------------------------------------------------------------------------------------------------
 * LoopNet XML Library Version 1.01
 * -------------------------------------------------------------------------------------------------
 * Change Log
 * -------------------------------------------------------------------------------------------------
 * 11/3/2004	Added support for Netscape 6 select nodes (by using getElementsByTagName) - DLamb
 * 11/2/2004	Improved the error handling and checking in the RemoteScriptingCall function - DLamb
 * 11/1/2004	File Created - DLamb
 * -------------------------------------------------------------------------------------------------
 * Current Browser Support:
 * -------------------------------------------------------------------------------------------------
 *	Internet Explorer
 *		6+ (5.0 and 5.5 need a manual installation of MSXML 3+)
 *	Mozilla/Gecko:
 *		0.9.4+ (1.4+ recommended)
 *	Netscape
 *		6+ select nodes not fully supported
 *		7+ (Mozilla 1.4) full support
 *	Firefox
 *		0.10.1+
 *	Opera
 *		7.60+
 *	Safari
 *		1.2+ (I don't think xslt is supported yet)
 *	Konqueror
 *		unknown (guessing no)
 *	IE Macintosh
 *		not supported
 */

//	 some basic browser detection TODO: update this
var _LNXML_IS_IE = (navigator.userAgent.toLowerCase().indexOf("msie") > -1)?true:false;
var _LNXML_IS_MOZ = (document.implementation && document.implementation.createDocument)?true:false;
var _LNXML_iNsCounter = 0;
var _LNXML_IEPREFIX4XSLPARAM = "";
if (_LNXML_IS_MOZ)
{
	//XMLDocument not supported in NS6.1 :(
	if(typeof XMLDocument == 'undefined')
		var XMLDocument = Document;

	/*
	 * Method to obtain a new DOM Document object
	 * @argument sUri the namespace of the root node (if any)
	 * @argument sUri the local name of the root node (if any)
	 * @returns a new DOM Document
	 */
	LNXML.getDomDocument = function(sUri, sName)
	{
		var oDoc = document.implementation.createDocument(sUri, sName, null);
		oDoc.addEventListener("load", _LNXML_XMLDocument_onload, false);
		return oDoc;
	};
	/*
	 * Method to obtain a new XMLHTTP Request object
	 * @returns a new XMLHTTP Request object
	 */
	LNXML.getXmlHttpRequest = function()
	{
		return new XMLHttpRequest();
	};
	/*
	 * Attached by an event handler to the load event. Internal use.
	 * @private
	 */
	function _LNXML_XMLDocument_onload()
	{
		_LNXML_loadHandler(this);
	};
	/*
	 * Ensures the document was loaded correctly, otherwise sets the
	 * parseError to -1 to indicate something went wrong. Internal use
	 * @private
	 */
	function _LNXML_loadHandler(oDoc)
	{
		if (!oDoc.documentElement || oDoc.documentElement.tagName == "parsererror")
			oDoc.parseError = -1;
		_LNXML_setReadyState(oDoc, 4);
	};
	/*
	 * Sets the readyState property of the given DOM Document object.
	 * Internal use.
	 * @private 
	 * @argument oDoc the DOM Document object to fire the
	 *          readystatechange event
	 * @argument iReadyState the number to change the readystate property to
	 */
	function _LNXML_setReadyState(oDoc, iReadyState) 
	{
		//oDoc.readyState = iReadyState;
		if (oDoc.onreadystatechange != null && typeof oDoc.onreadystatechange == "function")
			oDoc.onreadystatechange();
	};
	/*
	 * Deletes all child Nodes of the Document. Internal use
	 * @private
	 */
	XMLDocument.prototype._LNXML_clearDOM = function()
	{
		while(this.hasChildNodes())
			this.removeChild(this.firstChild);
	};
	/*
	 * Replaces the childNodes of the Document object with the childNodes of
	 * the object given as the parameter
	 * @private 
	 * @argument oDoc the Document to copy the childNodes from
	 */
	XMLDocument.prototype._LNXML_copyDOM = function(oDoc)
	{
		this._LNXML_clearDOM();
		if(oDoc.nodeType == Node.DOCUMENT_NODE || oDoc.nodeType == Node.DOCUMENT_FRAGMENT_NODE)
		{
			var oNodes = oDoc.childNodes;
			for(var i=0;i<oNodes.length;i++)
				this.appendChild(this.importNode(oNodes[i], true));
		}
		else if(oDoc.nodeType == Node.ELEMENT_NODE)
			this.appendChild(this.importNode(oDoc, true));
	};
	// used to normalise text nodes (for IE's innerText emulation)
	var _LNXML_WSMULT = new RegExp("^\\s*|\\s*$", "g");
	var _LNXML_WSENDS = new RegExp("\\s\\s+", "g");
	/*
	 * Used to "normalize" text (trim white space mostly). Internal use
	 * @private
	 */
	function _LNXML_normalizeText(sIn)
	{
		return sIn.replace(_LNXML_WSENDS, " ").replace(_LNXML_WSMULT, " ");
	};
	/*
	 * Parses the String given as parameter to build the document content
	 * for the object, exactly like IE's loadXML()
	 * @argument strXML The XML String to load as the Document's childNodes
	 * @returns the old Document structure serialized as an XML String
	 */
	XMLDocument.prototype.loadXML = function(strXML) 
	{
		_LNXML_setReadyState(this, 1);
		var sOldXML = this.xml;
		var oDoc = (new DOMParser()).parseFromString(strXML, "text/xml");
		_LNXML_setReadyState(this, 2);
		this._LNXML_copyDOM(oDoc);
		_LNXML_setReadyState(this, 3);
		_LNXML_loadHandler(this);
		return sOldXML;
	};
	/*
	 * Emulates IE's xml property, giving read-only access to the XML tree
	 * in it's serialized form (in other words, an XML string)
	 * @uses Mozilla's XMLSerializer class.
	 */
	XMLDocument.prototype.__defineGetter__("xml", function ()
	{
		return (new XMLSerializer()).serializeToString(this);
	});
	/*
	 * Emulates IE's xml property, giving read-only access to the XML tree
	 * in it's serialized form (in other words, an XML string)
	 * @uses Mozilla's XMLSerializer class.
	 */
	Node.prototype.__defineGetter__("xml", function ()
	{
		return (new XMLSerializer()).serializeToString(this);
	});
	/*
	 * Ensures and informs the xml property is read only
	 * @throws an &quot;Invalid assignment on read-only property&quot; error.
	 */
	XMLDocument.prototype.__defineSetter__("xml", function ()
	{
		throw "Invalid assignment on read-only property 'xml'. Hint: Use the 'loadXML(String xml)' method instead. (original exception: "+e+")";
	});
	/*
	 * Emulates IE's innerText (read/write). Note that this removes all
	 * childNodes of an HTML Element and just replaces it with a textNode
	 */
	HTMLElement.prototype.innerText;
	HTMLElement.prototype.__defineSetter__("innerText", function (sText)
	{
		var s = "" + sText;
		this.innerHTML = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
	});
	HTMLElement.prototype.__defineGetter__("innerText", function ()
	{
	    try
	    {
		return _LNXML_normalizeText(this.innerHTML.replace(/<[^>]+>/g,""));
		}
		catch(e)
		{
		return "";
		}
	});
	/*
	 * Emulate IE's onreadystatechange attribute
	 */ 
	Document.prototype.onreadystatechange = null;
	/*
	 * Emulate IE's parseError attribute
	 */
	Document.prototype.parseError = 0;
	/*
	 * Emulates IE's readyState property, which always gives an integer from 0 to 4:
	 * 1 == LOADING,
	 * 2 == LOADED,
	 * 3 == INTERACTIVE,
	 * 4 == COMPLETED
	 */
	//XMLDocument.prototype.readyState = 0;
	// NOTE: setting async to false will only work with documents
	// called over HTTP (meaning a server), not the local file system,
	// unless you are using Moz 1.4+.
	// BTW the try>catch block is for 1.4; I haven't found a way to check if
	// the property is implemented without
	// causing an error and I dont want to use user agent stuff for that...
	var _LNXML_SYNC_NON_IMPLEMENTED = false; 
	try
	{
		/*
		 * Emulates IE's async property for Moz versions prior to 1.4.
		 * It controls whether loading of remote XML files works
		 * synchronously or asynchronously.
		 */
		XMLDocument.prototype.async = true;
		_LNXML_SYNC_NON_IMPLEMENTED = true;
	}catch(e){/* trap */}
	/*
	 * Keeps a handle to the original load() method. Internal use and only
	 * if Mozilla version is lower than 1.4
	 * @private
	 */ 
	XMLDocument.prototype._LNXML_load = XMLDocument.prototype.load;
	/*
	 * Overrides the original load method to provide synchronous loading for
	 * Mozilla versions prior to 1.4, using an XMLHttpRequest object (if
	 * async is set to false)
	 * @returns the DOM Object as it was before the load() call (may be  empty)
	 */
	XMLDocument.prototype.load = function(sURI)
	{
		var oDoc = document.implementation.createDocument("", "", null);
		oDoc._LNXML_copyDOM(this);
		this.parseError = 0;
		_LNXML_setReadyState(this, 1);
		try
		{
			if(this.async == false && _LNXML_SYNC_NON_IMPLEMENTED)
			{
				var tmp = new XMLHttpRequest();
				tmp.open("GET", sURI, false);
				tmp.send(null);
				_LNXML_setReadyState(this, 2);
				this._LNXML_copyDOM(tmp.responseXML);
				_LNXML_setReadyState(this, 3);
			}
			else
				this._LNXML_load(sURI);
		}
		catch (objException)
		{
			this.parseError = -1;
		}
		finally
		{
			if(this.async == false)
				_LNXML_loadHandler(this);
		}
		return oDoc;
	}; 
	/*
	 * Extends the Element class to emulate IE's transformNodeToObject.
	 * Note: The transformation result <i>must </i> be well formed,
	 * otherwise an error will be thrown
	 * @uses Mozilla's XSLTProcessor
	 * @argument xslDoc The stylesheet to use (a DOM Document instance)
	 * @argument oResult The Document to store the transformation result
	 */
	Element.prototype.transformNodeToObject = function(xslDoc, oResult)
	{
		var oDoc = document.implementation.createDocument("", "", null);
		oDoc._LNXML_copyDOM(this);
		oDoc.transformNodeToObject(xslDoc, oResult);
	};
	/*
	 * Extends the Document class to emulate IE's transformNodeToObject
	 * @uses Mozilla's XSLTProcessor
	 * @argument xslDoc The stylesheet to use (a DOM Document instance)
	 * @argument oResult The Document to store the transformation result
	 * @throws Errors that try to be informative
	 */
	Document.prototype.transformNodeToObject = function(xslDoc, oResult)
	{
		var xsltProcessor = null;
		try
		{
			xsltProcessor = new XSLTProcessor();
			if(xsltProcessor.reset)// new nsIXSLTProcessor is available
			{
				xsltProcessor.importStylesheet(xslDoc);
				var newFragment = xsltProcessor.transformToFragment(this, oResult);
				oResult._LNXML_copyDOM(newFragment);
			}
			else // only nsIXSLTProcessorObsolete is available
			{
				xsltProcessor.transformDocument(this, xslDoc, oResult, null);
			}
		}
		catch(e)
		{
			if(xslDoc && oResult)
				throw "Failed to transform document. (original exception: "+e+")";
			else if(!xslDoc)
				throw "No Stylesheet Document was provided. (original exception: "+e+")";
			else if(!oResult)
				throw "No Result Document was provided. (original exception: "+e+")";
			else if(xsltProcessor == null)
				throw "Could not instantiate an XSLTProcessor object. (original exception: "+e+")";
			else
				throw e;
		}
	};
	/*
	 * Extends the Element class to emulate IE's transformNode. 
	 * Note: The result of your transformation must be well formed,
	 * otherwise you will get an error
	 * @uses Mozilla's XSLTProcessor
	 * @argument xslDoc The stylesheet to use (a DOM Document instance)
	 * @returns the result of the transformation serialized to an XML String
	 */
	Element.prototype.transformNode = function(xslDoc)
	{
		var oDoc = document.implementation.createDocument("", "", null);
		oDoc._LNXML_copyDOM(this);
		return oDoc.transformNode(xslDoc);
	};
	/*
	 * Extends the Document class to emulate IE's transformNode.
	 * Note: The result of your transformation must be well formed,
	 * otherwise you will get an error
	 * @uses Mozilla's XSLTProcessor
	 * @argument xslDoc The stylesheet to use (a DOM Document instance)
	 * @returns the result of the transformation serialized to an XML String
	 */
	Document.prototype.transformNode = function(xslDoc)
	{
		var out = document.implementation.createDocument("", "", null);
		this.transformNodeToObject(xslDoc, out);
		var str = null;
		try
		{
			var serializer = new XMLSerializer();
			str = serializer.serializeToString(out);
		}
		catch(e)
		{
			throw "Failed to serialize result document. (original exception: "+e+")";
		}
		return str;
	};
	/*
	 * LNXMLNodeList behaves as a NodeList but is only used as a result to selectNodes, 
	 * so it also has some properties IEs proprietery object features.
	 * @private
	 * @constructor
	 * @argument i the (initial) list size
	 */
	 function LNXMLNodeList(i)
	 {
	 	this.length = i;
	 };
	 /* Set an Array as the prototype object */
	 LNXMLNodeList.prototype = new Array(0);
	 /* Inherit the Array constructor  */
	 LNXMLNodeList.prototype.constructor = Array;
	 /* 
	 * Returns the node at the specified index or null if the given index 
	 * is greater than the list size or less than zero 
	 * Note that in ECMAScript you can also use the square-bracket 
	 * array notation instead of calling item
	 * @argument i the index of the member to return
	 * @returns the member corresponding to the given index
	 */
	 LNXMLNodeList.prototype.item = function(i)
	 {
	 	return (i < 0 || i >= this.length)?null:this[i];
	 };
	/*
	 * Emulate IE's expr property
	 * (Here the LNXMLNodeList object is given as the result of selectNodes).
	 * @returns the XPath expression passed to selectNodes that resulted in
	 *          this LNXMLNodeList
	 */
	LNXMLNodeList.prototype.expr = "";
	/* dummy, used to accept IE's stuff without throwing errors */
	XMLDocument.prototype.setProperty  = function(x,y){};
	/*
	 * Programmatically control namespace URI/prefix mappings for XPath
	 * queries.
	 * This method comes especially handy when used to apply XPath queries
	 * on XML documents with a default namespace, as there is no other way
	 * of mapping that to a prefix.
	 * Using no namespace prefix in DOM Level 3 XPath queries, implies you
	 * are looking for elements in the null namespace. If you need to look
	 * for nodes in the default namespace, you need to map a prefix to it
	 * first like:
	 * LNXML.setXpathNamespaces(oDoc, "xmlns:myprefix='http://mynsURI'");
	 * Note 1: Use this method only if the source document features
	 * a default namespace (without a prefix). You will need to map that
	 * namespace to a prefix for queries to work.
	 * Note 2: This method calls IE's setProperty method to set the
	 * appropriate namespace-prefix mappings, so you dont have to do that.
	 * @param oDoc The target XMLDocument to set the namespace mappings for.
	 * @param sNsSet A whilespace-seperated list of namespace declarations as
	 *            those would appear in an XML document. E.g.:
	 *            "xmlns:xhtml='http://www.w3.org/1999/xhtml' 
	 *			   xmlns:'http://www.w3.org/1999/XSL/Transform'"
	 * @throws An error if the format of the given namespace declarations is bad.
	 */
	LNXML.setXpathNamespaces = function(oDoc, sNsSet)
	{
		//oDoc._LNXML_setXpathNamespaces(sNsSet);
		oDoc._LNXML_useCustomResolver = true;
		var namespaces = sNsSet.indexOf(" ")>-1?sNsSet.split(" "):new Array(sNsSet);
		oDoc._LNXML_xpathNamespaces = new Array(namespaces.length);
		for(var i=0;i < namespaces.length;i++)
		{
			var ns = namespaces[i];
			var colonPos = ns.indexOf(":");
			var assignPos = ns.indexOf("=");
			if(colonPos == 5 && assignPos > colonPos+2)
			{
				var prefix = ns.substring(colonPos+1, assignPos);
				var uri = ns.substring(assignPos+2, ns.length-1);
				oDoc._LNXML_xpathNamespaces[prefix] = uri;
			}
			else
			{
				throw "Bad format on namespace declaration(s) given";
			}
		}
	};
	/*
	 * @private Flag to control whether a custom namespace resolver should
	 *          be used, set to true by LNXML.setXpathNamespaces
	 */
	XMLDocument.prototype._LNXML_useCustomResolver = false;
	XMLDocument.prototype._LNXML_xpathNamespaces = new Array();
	/*
	 * Extends the XMLDocument to emulate IE's selectNodes.
	 * @argument sExpr the XPath expression to use
	 * @argument contextNode this is for internal use only by the same
	 *           method when called on Elements
	 * @returns the result of the XPath search as a LNXMLNodeList 
	 * @throws An error if no namespace URI is found for the given prefix.
	 */
	XMLDocument.prototype.selectNodes = function(sExpr, contextNode)
	{
		if(this._LNXML_useCustomResolver || typeof this.createNSResolver == 'function')
		{	//createNSResolver not supported in NS6
			var nsDoc = this;
			var nsresolver = this._LNXML_useCustomResolver
			? function(prefix)
			{
				var s = nsDoc._LNXML_xpathNamespaces[prefix];
				if(s)return s;
				else throw "No namespace URI found for prefix: '" + prefix+"'";
			}
			: this.createNSResolver(this.documentElement);
					var oResult = this.evaluate(sExpr, 
							(contextNode?contextNode:this), 
							nsresolver, 
							XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);	
				var nodeList = new LNXMLNodeList(oResult.snapshotLength);
				nodeList.expr = sExpr;
				for(var i=0;i<nodeList.length;i++)
					nodeList[i] = oResult.snapshotItem(i);
				return nodeList;
		}
		else if(typeof this.getElementsByTagName == 'function')
		{	//for NS6 we hack this by using getElementsByTagName
			//this means we have to be VERY careful what node names we use!!
				return this.getElementsByTagName(sExpr.substring(2,(sExpr.length-3)));
		}
	};
	/*
	 * Extends the Element to emulate IE's selectNodes
	 * @argument sExpr the XPath expression to use
	 * @returns the result of the XPath search as an (LNXML)NodeList
	 * @throws An
	 *             error if invoked on an HTML Element as this is only be
	 *             available to XML Elements.
	 */
	Element.prototype.selectNodes = function(sExpr)
	{
		var doc = this.ownerDocument;
		if(doc.selectNodes)
			return doc.selectNodes(sExpr, this);
		else
			throw "Method selectNodes is only supported by XML Elements";
	};
	/*
	 * Extends the XMLDocument to emulate IE's selectSingleNodes.
	 * @argument sExpr the XPath expression to use
	 * @argument contextNode this is for internal use only by the same
	 *           method when called on Elements
	 * @returns the result of the XPath search as an (LNXML)NodeList
	 */
	XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode)
	{
		var ctx = contextNode?contextNode:null;
		sExpr += "[1]";
		var nodeList = this.selectNodes(sExpr, ctx);
		if(nodeList != null && nodeList.length > 0)
			return nodeList.item(0);
		else 
			return null;
	};
	/*
	 * Extends the Element to emulate IE's selectNodes.
	 * @argument sExpr the XPath expression to use
	 * @returns the result of the XPath search as an (LNXML)NodeList
	 * @throws An error if invoked on an HTML Element as this is only be
	 *             available to XML Elements.
	 */
	Element.prototype.selectSingleNode = function(sExpr)
	{
		var doc = this.ownerDocument;
		if(doc.selectSingleNode)
			return doc.selectSingleNode(sExpr, this);
		else
			throw "Method selectNodes is only supported by XML Elements";
	};
	/*
	 * Returns a human readable description of the parsing error. Usefull
	 * for debugging. Tip: append the returned error string in a <pre>
	 * element if you want to render it.
	 * Many thanks to Christian Stocker for the reminder and code.
	 * @argument oDoc The target DOM document
	 * @returns The parsing error description of the target Document in
	 *          human readable form (preformated text)
	 */
	LNXML.getParseErrorText = function (oDoc) 
	{
		if (oDoc.documentElement.tagName == "parsererror") 
		{
			var parseErrorText = oDoc.documentElement.firstChild.data;
			parseErrorText += "\n" +  oDoc.documentElement.firstChild.nextSibling.firstChild.data;
			return parseErrorText;
		}
	};
	
}
else if (_LNXML_IS_IE)
{
	// Add NodeType constants; missing in IE4, 5 and 6
	if(!window.Node)
	{
		var Node = {
				ELEMENT_NODE: 1,
				ATTRIBUTE_NODE: 2,
				TEXT_NODE: 3,
				CDATA_SECTION_NODE: 4,
				ENTITY_REFERENCE_NODE: 5,
				ENTITY_NODE: 6,
				PROCESSING_INSTRUCTION_NODE: 7,
				COMMENT_NODE: 8,
				DOCUMENT_NODE: 9,
				DOCUMENT_TYPE_NODE: 10,
				DOCUMENT_FRAGMENT_NODE: 11,
				NOTATION_NODE: 12
		}
	}
	// implement importNode for IE
	if(!document.importNode)
	{
		/*
		 * Implements importNode for IE using innerHTML. Main purpose it to
		 * be able to append Nodes from XMLDocuments to the current page in
		 * IE.
		 * 
		 * @param oNode
		 *            the Node to import
		 * @param bChildren
		 *            whether to include the children of oNode
		 * @returns the imported node for further use
		 */
		document.importNode = function(oNode, bChildren)
		{
			var importNode = document.createElement("div");
			if(bChildren)
				importNode.innerHTML = oNode.xml;
			else
				importNode.innerHTML = oNode.cloneNode(false).xml;
			return importNode.firstChild;
		};
	}//if(!document.importNode)
	
	// for XSLT parameter names, prefix needed by IE
	_LNXML_IEPREFIX4XSLPARAM = "xsl:";
	// used to store the most recent ProgID available out of the above
	var _LNXML_DOM_PROGID = "";
	var _LNXML_XMLHTTP_PROGID = "";
	/*
	 * Called when the LNXML.js file is parsed, to pick most recent
	 * ProgIDs for IE, then gets destroyed.
	 */
	function pickRecentProgID(idList)
	{
		// found progID flag
		var bFound = false;
		for(var i=0; i < idList.length && !bFound; i++)
		{
			try
			{
				var oDoc = new ActiveXObject(idList[i]);
				o2Store = idList[i];
				bFound = true;
			}
			catch (objException)
			{
				// trap; try next progID
			}
		}
		if (!bFound)
			throw "Could not retreive a valid progID of Class: " + idList[idList.length-1]+". (original exception: "+e+")";
		idList = null;
		return o2Store;
	};
	// store proper progIDs
    _LNXML_DOM_PROGID = pickRecentProgID(["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.4.0", "Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"], [["SELECT_NODES", 2],["TRANSFORM_NODE", 2]]);
    _LNXML_XMLHTTP_PROGID = pickRecentProgID(["Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"], [["XMLHTTP", 4]]);
    _LNXML_THREADEDDOM_PROGID = pickRecentProgID(["Msxml2.FreeThreadedDOMDocument.6.0", "MSXML2.FreeThreadedDOMDocument.4.0", "MSXML2.FreeThreadedDOMDocument.3.0"]);
    _LNXML_XSLTEMPLATE_PROGID = pickRecentProgID(["Msxml2.XSLTemplate.6.0", "Msxml2.XSLTemplate.4.0", "MSXML2.XSLTemplate.3.0"], [["XSLTPROC", 2]]);
	// we dont need this function anymore
	pickRecentProgID = null;
	//============================================
	// Methods (IE)
	//============================================
	// see mozilla version
	LNXML.getDomDocument = function(sUri, sName)
	{
		var oDoc = new ActiveXObject(_LNXML_DOM_PROGID);
		// if a root tag name was provided, we need to load it in the DOM
		// object
		if (sName)
		{
			// if needed, create an artifical namespace prefix the way Moz
			// does
			if (sUri)
			{
				oDoc.loadXML("<a" + _LNXML_iNsCounter + ":" + sName + " xmlns:a" + _LNXML_iNsCounter + "=\"" + sUri + "\" />");
				// don't use the same prefix again
				++_LNXML_iNsCounter;
			}
			else
				oDoc.loadXML("<" + sName + "/>");
		}
		return oDoc;
	};
	// see mozilla version
	LNXML.getXmlHttpRequest = function()
	{
		return new ActiveXObject(_LNXML_XMLHTTP_PROGID);
	};
	// see mozilla version
	LNXML.getParseErrorText = function (oDoc) 
	{
		var parseErrorText = "XML Parsing Error: " + oDoc.parseError.reason +" \n";
		parseErrorText += "Location: " + oDoc.parseError.url + "\n";
		parseErrorText += "Line Number " + oDoc.parseError.line ;
		parseErrorText += ", Column " + oDoc.parseError.linepos + ":\n";
		parseErrorText += oDoc.parseError.srcText + "\n";
		for(var i = 0;  i < oDoc.parseError.linepos;i++)
			parseErrorText += "-";
		parseErrorText +=  "^\n";
		return parseErrorText;
	};
	// see mozilla version
	LNXML.setXpathNamespaces = function(oDoc, sNsSet)
	{
		oDoc.setProperty("SelectionLanguage", "XPath");
		oDoc.setProperty("SelectionNamespaces", sNsSet);
	};
	/*
	 * Basic implementation of Mozilla's XSLTProcessor for IE. 
	 * Reuses the same XSLT stylesheet for multiple transforms
	 * @constructor
	 */
	function XSLTProcessor()
	{
		this.template = new ActiveXObject(_LNXML_XSLTEMPLATE_PROGID);
		this.processor = null;
	};
	/*
	 * Impoprts the given XSLT DOM and compiles it to a reusable transform
	 * @argument xslDoc The XSLT DOMDocument to import
	 */
	XSLTProcessor.prototype.importStylesheet = function(xslDoc)
	{
		// convert stylesheet to free threaded
		var converted = new ActiveXObject(_LNXML_THREADEDDOM_PROGID); 
		converted.loadXML(xslDoc.xml);
		this.template.stylesheet = converted;
		this.processor = this.template.createProcessor();
		// (re)set default param values
		this.paramsSet = new Array();
	};
	/*
	 * Transform the given XML DOM
	 * @argument sourceDoc The XML DOMDocument to transform
	 * @return The transformation result as a DOM Document
	 */
	XSLTProcessor.prototype.transformToDocument = function(sourceDoc)
	{
		this.processor.input = sourceDoc;
		var outDoc = new ActiveXObject(_LNXML_DOM_PROGID);
		this.processor.output = outDoc; 
		this.processor.transform();
		return outDoc;
	};
	/*
	 * Set global XSLT parameter of the imported stylesheet
	 * @argument nsURI The parameter namespace URI
	 * @argument name The parameter base name
	 * @argument value The new parameter value
	 */
	XSLTProcessor.prototype.setParameter = function(nsURI, name, value)
	{
		// nsURI is optional and cannot be null
		if(nsURI)
			this.processor.addParameter(name, value, nsURI);
		else
			this.processor.addParameter(name, value);
			
		// update updated params for getParameter
		if(!this.paramsSet[""+nsURI])
			this.paramsSet[""+nsURI] = new Array();
			
		this.paramsSet[""+nsURI][name] = value;
	};
	
	/*
	 * Gets a parameter if previously set by setParameter. Returns null
	 * otherwise
	 * @argument name The parameter base name
	 * @argument value The new parameter value
	 * @return The parameter value if reviously set by setParameter, null otherwise
	 */
	XSLTProcessor.prototype.getParameter = function(nsURI, name)
	{
		if(this.paramsSet[""+nsURI] && this.paramsSet[""+nsURI][name])
			return this.paramsSet[""+nsURI][name];
		else
			return null;
	};
}
/*
 * @constructor
 */
function LNXML(){}
/*
 * Method, used to set xslt parameters.
 * Note that this method can only work for the main stylesheet and
 * not any included/imported files.
 * 
 * @argument oXslDoc the target XSLT DOM Document
 * @argument sParamName the name of the XSLT parameter
 * @argument sParamValue the value of the XSLT parameter
 * @returns whether the parameter was set succefully
 */
LNXML.setXslParameter = function(oXslDoc, sParamQName, sParamValue)
{
	try
	{
		var params = oXslDoc.getElementsByTagName(_LNXML_IEPREFIX4XSLPARAM+"param");
		var iLength = params.length;
		var bFound = false;
		var param;
		
		if(sParamValue)
		{
			for(var i=0; i < iLength && !bFound;i++)
			{
				// match a param name attribute with the name given as
				// argument
				if(params[i].getAttribute("name") == sParamQName)
				{
						param = params[i];
					// clean up the parameter
					while(param.firstChild)
						param.removeChild(param.firstChild);
					if(!sParamValue || sParamValue == null)
					{
						// do nothing; we've cleaned up the parameter anyway
					}
					// if String
					else if(typeof sParamValue == "string")
					{ 
						param.setAttribute("select", sParamValue);
						bFound = true;
					}
					// if node
					else if(sParamValue.nodeName)
					{
						param.removeAttribute("select");
						param.appendChild(sParamValue.cloneNode(true));
						bFound = true;
					}
					// if NodeList
					else if (sParamValue.item(0)
							&& sParamValue.item(0).nodeType)
					{
						for(var j=0;j < sParamValue.length;j++)
							if(sParamValue.item(j).nodeType) // check if this is a Node
								param.appendChild(sParamValue.item(j).cloneNode(true));
						bFound = true;
					}
					// if Array or IE's IXMLDOMNodeList
					else
						throw "Failed to set xsl:param "+sParamQName+" (original exception: "+e+")";
				}
			}
		}
		return bFound;
	}
	catch(e)
	{
		throw e;
		return false;
	}
}
function RemoteAJAXCall(fCallBack, sUrl,sXml,sMethodName,sNamespace,iErrorSource,sServiceSource,bTrace)
{
	//alert('a');
	var self = this;
	//alert('b');
		
	//put this in here so that the JSTrace text call to a webservice wouldn't go recursive
	//any other caller should not pass the bTrace argument!  see me if questions RH
	if (bTrace == null)
		bTrace = true;

	if (typeof jsTrace == "function" && bTrace)
		jsTrace("Starting remote ajax scripting call");
		
		
	//alert('c');
		
	var xdReturn = null;
	var xdToPost = LNXML.getDomDocument();
	var sSOAPAction = sNamespace + '/' + sMethodName;
	var sSOAPInput = GetSoapInput(sXml,sMethodName,sNamespace,sServiceSource,bTrace);		
		
	
	//alert(sSOAPInput);
		
	xdToPost.loadXML(sSOAPInput);
	
	
	//alert('e');
	
	try
	{
		//check for parsing error
		if(xdToPost.parseError != 0)
		{
			if (typeof jsTrace == "function" && bTrace)
			{
				jsTrace(xdToPost.parseError);
				jsTrace("The post input xml is not formed");
			}
				
			var e = new Error(xdToPost.parseError,"The post input xml is not formed\n");
			e.name = "parseError"
			e.message += LNXML.getParseErrorText(xdToPost);
			throw(e)
		}

		try
		{	//try to create the self.AJAX object
			//alert('getting xml http request');
			self.AJAX = LNXML.getXmlHttpRequest();
		}
		catch(eX)
		{
			//alert("An error occured: Message="+eX.message+"; Error Number="+(eX.number & 0xFFFF)+"; File="+eX.fileName+"; Line="+eX.lineNumber+"; Name="+eX.name);
			//if you can't create the self.AJAX object and we thought you were able to do this,
			//redirect to our error handling page
			top.location = '/xNet/MainSite/Error/RemoteScriptingError.aspx';
		}

		if (typeof jsTrace == "function" && bTrace)
			jsTrace("Posting to " + FixUrl(sUrl));
		
		
		if (fCallBack != null)
		{
			self.process = fCallBack;
			
			//set call back
			self.AJAX.onreadystatechange = function( ) {self.process(self.AJAX)};
		}
		self.AJAX.open('POST', FixUrl(sUrl), true);		
		//setting this doubles up the content type in NS6 - we can put this back if we need to
		//RC 10/31/06 - Added this hack just like VP did in the RemoteScriptingCall method to support FF.
		if(_LNXML_IS_MOZ)
			self.AJAX.setRequestHeader('Content-Type', 'text/xml');
		self.AJAX.setRequestHeader('SOAPAction', sSOAPAction);
		
		//alert('Post Url:\n'+FixUrl(sUrl)+'\nInput Xml:\n'+xdToPost.xml);
		self.AJAX.send(xdToPost);
	}
	catch(e)
	{	//log error in the database
		alert(e.message);	
//		var sModule = "JavascriptXHTMLPost";
//		var sMethod = "RemoteScriptingCall";
//		var iErrorType = 60; //SystemError
//		if(iErrorSource == null)iErrorSource = 480; //ClientSideJavaScriptError
//		var sInputData = "self.AJAXPost URL="+sUrl+"; InputXML="+(sSOAPInput);
//		var sErrorDetails = "An error occured: Message="+e.message+"; Error Number="+(e.number & 0xFFFF)+"; File="+e.fileName+"; Line="+e.lineNumber+"; Name="+e.name;
//		if(typeof TrackWebErrors == 'function')//make sure LogErrorJS is on the page
//		{
//			//alert('Calling TrackWebErrors\nsModule: '+sModule+'\nsMethod: '+sMethod+'\niErrorType: '+iErrorType+'\niErrorSource: '+iErrorSource+'\nsInputData: '+sInputData+'\nsErrorDetails: '+sErrorDetails)
//			TrackWebErrors(sModule,sMethod,iErrorType,iErrorSource,sInputData,sErrorDetails);
//		}
	}
		
	return self.AJAX;
}
function GetAJAXResponse(oAJAX, sRootNodeToSelect,iErrorSource,bTrace)
{
	if (bTrace == null)
		bTrace = true;

	var xdReturn = null;
	
	try
	{
		if (typeof jsTrace == "function" && bTrace)
		{
			jsTrace("Remotecall response");
			jsTrace(oAJAX.responseXML);
		}
		
		if(oAJAX.status == 200)
		{
			if(oAJAX.responseXML != null && oAJAX.responseXML.xml.length > 0)
			{	//load the response xml into the return dom...
				var xdReturn = LNXML.getDomDocument();
				if(sRootNodeToSelect != null)
				{	//...by selecting the root node requested
					xdRootNode = oAJAX.responseXML.selectSingleNode("//" + sRootNodeToSelect)
					if(xdRootNode != null)
						xdReturn.loadXML(xdRootNode.xml);
				}
				else
				{
					//...return complete xml
					xdReturn.loadXML(oAJAX.responseXML.xml);
				}
				
				//check for parsing error
				if(xdReturn.parseError != 0)
				{
					if (typeof jsTrace == "function" && bTrace)
					{
						jsTrace(xdReturn.parseError);
						jsTrace("The responseXML is not formed");
					}
					var e = new Error(xdReturn.parseError,"The responseXML is not formed\n");
					e.name = "parseError"
					e.message += LNXML.getParseErrorText(xdReturn);
					throw(e)
					return null; //no valid dom to return
				}
			}
		}
		else
		{	//return status code was not 200
			var e = new Error(oAJAX.status,"There was a problem retrieving the XML data. Status Code: "+oAJAX.status+"\n");
			e.name = "Error"
			e.message += oAJAX.responseXML.xml;
			throw(e)
		}
	}
	catch(e)
	{	//log error in the database
		var sModule = "JavascriptXHTMLPost";
		var sMethod = "RemoteScriptingCall";
		var iErrorType = 60; //SystemError
		if(iErrorSource == null)iErrorSource = 480; //ClientSideJavaScriptError
		var sInputData = "Error on remote call response";
		var sErrorDetails = "An error occured: Message="+e.message+"; Error Number="+(e.number & 0xFFFF)+"; File="+e.fileName+"; Line="+e.lineNumber+"; Name="+e.name;
		if(typeof TrackWebErrors == 'function')//make sure LogErrorJS is on the page
		{
			//alert('Calling TrackWebErrors\nsModule: '+sModule+'\nsMethod: '+sMethod+'\niErrorType: '+iErrorType+'\niErrorSource: '+iErrorSource+'\nsInputData: '+sInputData+'\nsErrorDetails: '+sErrorDetails)
			TrackWebErrors(sModule,sMethod,iErrorType,iErrorSource,sInputData,sErrorDetails);
		}
	}
	
	
	if (typeof jsTrace == "function" && bTrace)
	{
		jsTrace(xdReturn.xml);
		jsTrace("completing remotecall response");
	}
		
	return xdReturn;
}
function GetSoapInput(sXml,sMethodName,sNamespace,sServiceSource,bTrace)
{
	var sSOAPHeader = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body>';
	sSOAPHeader += '<' + sMethodName + ' xmlns="' + sNamespace + '"><svcRequest>';
	var sSOAPFooter ='</svcRequest></' + sMethodName + '>';
	sSOAPFooter += '</soap:Body></soap:Envelope>';
	var sSOAPAction = sNamespace + '/' + sMethodName;

	var credInsert = '';
	try{
	    if (lopid + '' != '') {
	        credInsert = '<LoggedOnUserPersonID><![CDATA[' + lopid + ']]></LoggedOnUserPersonID>"';
	    }
	}
	catch(e){}

	var sInputXml = "<ServiceRequest><BBSCredentials>" + credInsert + "</BBSCredentials><RequestData>" + sXml + "</RequestData></ServiceRequest>";

	if (typeof jsTrace == "function" && bTrace)
		jsTrace(sSOAPHeader + sInputXml + sSOAPFooter);
		
	//alert(sSOAPHeader + sInputXml + sSOAPFooter)
		
	return sSOAPHeader + sInputXml + sSOAPFooter;
	
}
/*
 * Method, used to create an xmlhttp post to a webservice (or page).
 * 
 * @argument sUrl the URL of the webservice or page to post to.
 * @argument sXml the input xml, the PFRequestData node and any children nodes your method
   needs to process the request
 * @argument sMethodName the used in the SOAP Header
 * @argument sNamespace the used in the SOAP Header
 * @argument sRootNodeToSelect the name of the node you want as the root node when the xml
   dom is returned.
 * @argument iErrorSource the error source id, gets inserted into the database for tracking
   when an error happens. Note: the id is defaulted to 480 (Client Side JavaScript Error)
   when not passed in
 * @returns a DOM Document with the responseXML loaded into it
 */
function RemoteScriptingCall(sUrl,sXml,sMethodName,sNamespace,sRootNodeToSelect,iErrorSource,sServiceSource,bTrace)
{
   
    //alert('here');
	//put this in here so that the JSTrace text call to a webservice wouldn't go recursive
	//any other caller should not pass the bTrace argument!  see me if questions RH
	if (bTrace == null)
		bTrace = true;

	if (typeof jsTrace == "function" && bTrace)
		jsTrace("Starting remote scripting call");
		
	var xdReturn = null;
	var xdToPost = LNXML.getDomDocument();
	var sSOAPAction = sNamespace + '/' + sMethodName;
	var sSOAPInput = GetSoapInput(sXml,sMethodName,sNamespace,sServiceSource,bTrace);		
	
	//alert(sSOAPInput);
		
	xdToPost.loadXML(sSOAPInput);
	
	try
	{
		//check for parsing error
		if(xdToPost.parseError != 0)
		{
			if (typeof jsTrace == "function" && bTrace)
			{
				jsTrace(xdToPost.parseError);
				jsTrace("The post input xml is not formed");
			}
				
			var e = new Error(xdToPost.parseError,"The post input xml is not formed\n");
			e.name = "parseError"
			e.message += LNXML.getParseErrorText(xdToPost);
			throw(e)
		}

		try
		{	//try to create the xmlhttp object
			var xmlHttp = LNXML.getXmlHttpRequest();
		}
		catch(eX)
		{
			//if you can't create the xmlhttp object and we thought you were able to do this,
			//redirect to our error handling page
		//	top.location = '/xNet/MainSite/Error/RemoteScriptingError.aspx';
		}

		if (typeof jsTrace == "function" && bTrace)
			jsTrace("Posting to " + FixUrl(sUrl));
				
		xmlHttp.open('POST', FixUrl(sUrl), false);		
		
		//setting this doubles up the content type in NS6 - we can put this back if we need to
		//VP put it back 12/19/2005 fix for firefox
		if(_LNXML_IS_MOZ)
			xmlHttp.setRequestHeader('Content-Type', 'text/xml');
	        xmlHttp.setRequestHeader('SOAPAction', sSOAPAction);
		
		//alert('Post Url:\n'+FixUrl(sUrl)+'\nInput Xml:\n'+xdToPost.xml);
		xmlHttp.send();
		
		//alert(xmlHttp.responseXML.xml);
		
		if (typeof jsTrace == "function" && bTrace)
		{
			jsTrace("Remotecall response");
			jsTrace(xmlHttp.responseXML.xml);
		}
				   
		var xdReturn = xmlHttp.responseText;
		return xdReturn;
		
		if(xmlHttp.status == 200)
		{
		    var xdReturn = xmlHttp.responseText;
		
			if(xmlHttp.responseXML != null && xmlHttp.responseXML.xml.length > 0)
			{	
			
			    //load the response xml into the return dom...
				//var xdReturn = xmlHttp.responseXML;
				//var xdReturn = LNXML.getDomDocument();
				//if(sRootNodeToSelect != null)
				//{	//...by selecting the root node requested
				//	xdRootNode = xmlHttp.responseXML.selectSingleNode("//" + sRootNodeToSelect)
				//	if(xdRootNode != null)
				//		xdReturn.loadXML(xdRootNode.xml);
				//}
				//else
				//{
					//...return complete xml
					//xdReturn.loadXML(xmlHttp.responseXML.xml);
				//}
				
				//check for parsing error
				if(xdReturn.parseError != 0)
				{
					if (typeof jsTrace == "function" && bTrace)
					{
						jsTrace(xdReturn.parseError);
						jsTrace("The responseXML is not formed");
					}
					var e = new Error(xdReturn.parseError,"The responseXML is not formed\n");
					e.name = "parseError"
					e.message += LNXML.getParseErrorText(xdReturn);
					throw(e)
					return null; //no valid dom to return
				}
			}
		}
		else
		{	//return status code was not 200
			var e = new Error(xmlHttp.status,"There was a problem retrieving the XML data. Status Code: "+xmlHttp.status+"\n");
			e.name = "Error"
			e.message += xmlHttp.responseXML.xml;
			throw(e)
		}
	}
	catch(e)
	{	//log error in the database
		var sModule = "JavascriptXHTMLPost";
		var sMethod = "RemoteScriptingCall";
		var iErrorType = 60; //SystemError
		if(iErrorSource == null)iErrorSource = 480; //ClientSideJavaScriptError
		var sInputData = "XmlHttpPost URL="+sUrl+"; InputXML="+(sSOAPInput);
		var sErrorDetails = "An error occured: Message="+e.message+"; Error Number="+(e.number & 0xFFFF)+"; File="+e.fileName+"; Line="+e.lineNumber+"; Name="+e.name;
		if(typeof TrackWebErrors == 'function')//make sure LogErrorJS is on the page
		{
			//alert('Calling TrackWebErrors\nsModule: '+sModule+'\nsMethod: '+sMethod+'\niErrorType: '+iErrorType+'\niErrorSource: '+iErrorSource+'\nsInputData: '+sInputData+'\nsErrorDetails: '+sErrorDetails)
			TrackWebErrors(sModule,sMethod,iErrorType,iErrorSource,sInputData,sErrorDetails);
		}
	}
	
	
	if (typeof jsTrace == "function" && bTrace)
	{
		jsTrace(xdReturn.xml);
		jsTrace("completing remote scripting call");
	}
		
	return xdReturn;
}

/*
 * This method is used to display (and optionally center) a message to the user that 
 * that we are getting data from the server (usually a "loading" or "please wait" message)
 */
function ShowRemoteScriptingMsg(sFunctionCall, sMessage, sMessageElement, bCenterInPage)
{
	try
	{		
		try
		{		
			var el = document.getElementById(sMessageElement);
			el.innerHTML = sMessage;
					
			if (bCenterInPage)
			{
				var myWidth = 0, myHeight = 0;
				if( typeof( window.innerWidth ) == 'number' ) {
					//Non-IE
					myWidth = window.innerWidth;
					myHeight = window.innerHeight;
				} else if( document.documentElement &&
					( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
					//IE 6+ in 'standards compliant mode'
					myWidth = document.documentElement.clientWidth;
					myHeight = document.documentElement.clientHeight;
				} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
					//IE 4 compatible
					myWidth = document.body.clientWidth;
					myHeight = document.body.clientHeight;
				}
				
				var myDivWidth = parseInt(el.style.width.replace("px", ""));
				var myDivHeight = parseInt(el.style.height.replace("px", ""));
						
				el.style.left = (myWidth - myDivWidth) / 2;
				el.style.top = (myHeight - myDivHeight) / 2;
				
				el.style.display = 'block';
			}
			else
			{
				el.style.display = 'inline';
			}
		}
		catch(exinternal)
		{/*trap*/}

		try
		{
		    setTimeout(
		        sFunctionCall, 
		        20);
		}
		catch (ex)
		{/*trap*/}
	}
	catch(ex)
	{/*trap*/}
}

/*
 * This method is used to hide the message to the user that that we are
 * getting data from the server (usually a "loading" or "please wait" message)
 */
function HideRemoteScriptingMsg(sMessageElement)
{
	try
	{
		//return;
	    var el = document.getElementById(sMessageElement);

	    if (el != null)
	    {
	        el.style.display = 'none';
	    }
	}
	catch(ex)
	{/*trap*/}
}

/*
 *This method is used to fix relative URLs and make them
 *absolute based on the URL in the address bar
 */
function FixUrl(sUrl)
{
	var sActualUrl = sUrl;
	
	if (sUrl.toLowerCase().indexOf("http://", 0) == -1 && sUrl.toLowerCase().indexOf("https://", 0) == -1)
	{	//fix URL so that it is not relative
		if (sUrl.substring(0,1) == "/")
		{
			sActualUrl = document.URL.substring(0, document.URL.indexOf("/", 7)) + sUrl;
		}
		else
		{
			sActualUrl = document.URL.substring(0, document.URL.indexOf("/", 7)) + "/" + sUrl;
		}
	}
	return sActualUrl;
}
function ClearDropDown(
    dropdown,
    emptyText)
{
	if (dropdown != null)
	{
		if (dropdown.options.length > 0)
		{
			if (dropdown.options[0].value == '')
			{
			    if (typeof (emptyText) != 'undefined')
			    {
			        dropdown.options[0].text = emptyText;
			    }
			    
				dropdown.options.length = 1;
			}
			else
			{
				dropdown.options.length = 0;
			}	
		}
	}
}
