///////////////////////////////////////////////////////////////////////////////
// --------- //
// jsWS      //
// --------- //
// basic wrapper for making a webservice call

jsWS = function(url, wsMethod)
{
	this.wsUrl = url;
	this.wsMethod = wsMethod;
	this.argName	= [];
	this.argValue	= [];
	this.running = false;
	this.response=null;
	this.responseText = null;
	this.requestType='FORM';
	this.isAsync=true;
	this.method = "POST"; 
	this.readyStateChangeFired = false;
	this.onReadyStateChange = null;
}
jsWS.prototype.SetSync = function()
{
	this.isAsync=false;
}

jsWS.prototype.SetAsync = function()
{
	this.isAsync=true;
}

jsWS.prototype.addArg = function(argName, argValue)
{
	this.argName[this.argName.length]   = argName;
	this.argValue[this.argValue.length] = argValue;
	return true;
}

/*************************
Adds the standard set of UserInfo parameters (requires that Common.js is included)
**************************/
jsWS.prototype.addUserInfoParms = function()
{
	this.addArg("DSN", GetCookie(g_LoginCookieName, "DSN"));
	this.addArg("UserID", GetCookie(g_SessionCookieName, "UserID"));
	this.addArg("LanguageID", GetCookie(g_LoginCookieName, "LanguageID"));
	this.addArg("SecurityToken", GetCookie(g_SessionCookieName, "SecurityToken"));
}

jsWS.prototype.addArgs=function(args)
{
	var argsArray=args.split('&');
	for(var i=0;i<argArray.length;i++)
	{
		var argArray=argsArray[i].split('=');
		addArg(argArray[0],argArray[1]);
	}
}



jsWS.prototype.envelopeSoap = function()
{
	var xdoc = new XMLDocument('', '');
	xdoc.appendChild(xdoc.createNode(1,'SOAP:Envelope','http://schemas.xmlsoap.org/soap/envelope/'));
	
	xdoc.documentElement.appendChild(xdoc.createElement('SOAP:Header'));
	var body=xdoc.documentElement.appendChild(xdoc.createElement('SOAP:Body'));
	var method=body.appendChild(xdoc.createNode(1,'m:'+this.wsMethod,'http://tempuri.org/'));
	
	for (var i = 0; i < this.argName.length; i++)
	{
		var arg = xdoc.createElement(this.argName[i]);
		arg.appendChild(xdoc.createTextNode(this.argValue[i]));
		method.appendChild(arg);
	}	
	return xdoc;
}
jsWS.prototype.envelopeForm = function()
{
	var result='';
    for (var i = 0; i < this.argName.length; i++)
	{
		result+=this.argName[i]+"="+this.argValue[i];
		if(i<this.argName.length-1)
			result+="&";
	}
	return result;
}

jsWS.prototype.send = function(handler,arg1,arg2,arg3,arg4,arg5)
{
	// Send Request
	var req = new XMLHttpRequest();
	var xmlrpc = this;
	this.xmlhttp=req;

	//Defect #238007
	var result = new Object();
	
	this.onReadyStateChange = function()
	{			
	
		if(req.readyState==4)//Complete
		{		   		
			xmlrpc.readyStateChangeFired = true;
			xmlrpc.running = false;  					
			try
			{
				if(req.status == 200)//Normal
				{		
				    xmlrpc.responseText = req.responseText;
			        xmlrpc.responseXML = req.responseXML;
				    if(IsMac())
					{
						if(xmlrpc.responseXML)
							xmlrpc.response = req.responseXML.documentElement;
						else
						{
							xmlrpc.response = null;
						}
					}					
					else
					{
						if (req.responseXML)
						{
							if(req.responseXML.documentElement == null)
							{
								req.responseXML.async=false;
								req.responseXML.load(req.responseStream);
							}
							xmlrpc.response = req.responseXML.documentElement;
						}
						else
							xmlrpc.response = null;
						
					}
					if(handler!=null)
						handler(xmlrpc, arg1,arg2,arg3,arg4,arg5);					
				}					
				else if( req.status == 404)
					alert("Error Code: " +  req.status + "\nError Detials: " +  req.statusText + "\nCheck if the requesting URL is correct.");										
				else //other error	
				{	
					var e;
					if(req.responseXML)	
					{				
						e = req.responseXML.getElementsByTagName("ProcessError");		
					}
					
					if(e && e.length > 0)
				        alert(e[0].firstChild.nodeValue);				
				    else if(!IsMac() || typeof(req.status)!='undefined')
					{
						if(req.responseText && req.responseText.indexOf("<?xml")!=0)
							alert("There was a problem the web service call " + xmlrpc.wsMethod + ":\n" + "Status: " + req.status + "\nDetails: " + req.responseText);										
						else
							alert("There was a problem the web service call " + xmlrpc.wsMethod + ":\n" + "Status: " + req.status + "\nDetails: " + req.statusText);										
					}			   		   		    																																				
				}				
			}
			finally
			{
				//Defect #238007
				result.responseText = req.responseText;
			    result.responseXML = req.responseXML;
				
				//req = null;
				//xmlrpc.xmlhttp = null;
			}
		}
	}	
	req.onreadystatechange = this.onReadyStateChange;
	
	if(this.method == "GET")	
    {   
        req.open(this.method, this.wsUrl, false);       
		req.send(null);
		return;							
	}		
	if(this.requestType=='SOAP')
    {     
        req.open(this.method, this.wsUrl, this.isAsync);
        req.setRequestHeader('User-Agent', "XMLHttpRequest");
        req.setRequestHeader('Content-Type', 'text/xml; charset=utf-8'); 
        if(this.wsUrl == "WebService/WS.asmx")
            req.setRequestHeader('SOAPAction', 'http://aprimo.com/'+ this.wsMethod);                          		       
        else
	        req.setRequestHeader('SOAPAction', 'http://tempuri.org/'+ this.wsMethod);
	    req.send(this.envelopeSoap());		    	  
    }
    else
    {       
	    var fullURL = this.wsUrl;
	    if(this.wsMethod)
		    fullURL += '/' + this.wsMethod;
	    req.open(this.method, fullURL, this.isAsync);
	    req.setRequestHeader('User-Agent', "XMLHttpRequest");
	    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    req.send(this.envelopeForm());		   
    }	
	
	
	this.running = true;
	this.enforceOnReadyStateChangeEvent();
	//Defect #238007
	//return req;
	return result;
}

jsWS.prototype.enforceOnReadyStateChangeEvent = function()
{
	// Since Firefox has a bug with synchronous calls and the onreadystatechange event, we need to make sure
	// that the method bound to the event gets fired.
		
	// If we're synchronous and we've completed our request but have not fired the readystatechange method, do that now.
	if (!this.isAsync)
	{
		if (this.xmlhttp.readyState == 4 && !this.readyStateChangeFired)
			this.onReadyStateChange();
		else if (!this.readyStateChangeFired)
			this.enforceOnReadyStateChangeEvent();
	}
}

jsWS.prototype.value = function(key)
{	
	try
	{
		return this.response.childNodes[0].nodeValue;
	}
	catch(e)
	{
		return '';
	}
}
jsWS.prototype.complexValue = function(key)
{	
	if(IsMac())		
		return this.response.selectNodeText("/" + key)
	else		
	{
		try
		{
			return this.response.getElementsByTagName(key)[0].nodeValue;
		}
		catch(e)
		{
			return '';
		}
	}
	return '';
}

jsWS.prototype.status = function() 
{		
	//This will not work if you're calling this method after the send method has been called on the same instance of jsWS
	return this.xmlhttp.status;
}

jsWS.prototype.statusDescription = function()
{	
	//This will not work if you're calling this method after the send method has been called on the same instance of jsWS
	return this.xmlhttp.responseText;
}

///////////////////////////////////////////////////////////////////////////////
jsGet=function(url)
{
	var xmlhttp = new XMLHttpRequest();
	this.xmlhttp=xmlhttp;
	xmlhttp.open('GET', url, false);
	xmlhttp.send(null);
	return xmlhttp.responseText;
}

///////////////////////////////////////////////////////////////////////////////
// --------------------- //
// XMLHttpRequest Helper //
// --------------------- //
	
// Version stored to help with debugging so that we know 
// what XMLHttpRequest is in use on the client browser.
window.XMLHttpRequestSupported	= false;
window.XMLHttpRequestVersion	= 'Unknown';
	
// Mozilla, Safari and Opera 8 Beta.
if (window.XMLHttpRequest)
{
	window.XMLHttpRequestVersion	= 'XMLHttpRequest';
	window.XMLHttpRequestSupported	= true;
}

// Internet Explorer.
if (window.ActiveXObject && !window.XMLHttpRequest)
{
	var test = null;
	
	try
	{
		test = new ActiveXObject("Msxml2.XMLHTTP");
		
		window.XMLHttpRequestVersion	= 'Msxml2.XMLHTTP';
		window.XMLHttpRequestSupported	= true;
		window.XMLHttpRequest			= function()
		{
			return new ActiveXObject("Msxml2.XMLHTTP");
		}
	}
	catch (e)
	{
		try
		{
			test = new ActiveXObject("Microsoft.XMLHTTP");
			
			window.XMLHttpRequestVersion	= 'Microsoft.XMLHTTP';
			window.XMLHttpRequestSupported	= true;
			window.XMLHttpRequest			= function()
			{
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		catch (E) {}
	}
}

// XMLHttpRequest unsupported in browser.
if(!window.XMLHttpRequest || typeof(window.XMLHttpRequest) == "undefined")
{
	window.XMLHttpRequestVersion	= 'Not Supported';
	window.XMLHttpRequestSupported	= false;
}

///////////////////////////////////////////////////////////////////////////////
// ------------------ //
// XMLDocument Helper //
// ------------------ //

// Version stored to help with debugging so that we know 
// what XMLDocument is in use on the client browser.
window.XMLDocumentSupported		= false;
window.XMLDocumentVersion		= 'Unknown';
	
// Safari. - basic support at the moment but it does what we need!
if(navigator.userAgent.toLowerCase().indexOf('safari') > -1 && document.implementation && document.implementation.createDocument)
{
	window.XMLDocumentSupported	= true;
	window.XMLDocumentVersion	= 'document.implementation (Safari)';
	window.XMLDocument			= function(namespaceUri, rootName)
	{
		var xdoc = document.implementation.createDocument(namespaceUri, rootName, null);		
		if (xdoc.documentElement == null) // Safari 1.2 bug 
		{ 
			xdoc.appendChild(xdoc.createElement(rootName));
		}		
		xdoc.loadXML = function(xmlString)
		{		
		    var doc;
		    if(DOMParser)//new safari support DOMParser now
		    {
		        var domParser = new DOMParser();		   
			    doc = domParser.parseFromString(xmlString, "text/xml");	
			}
		    else
	        {
			    var req = new XMLHttpRequest();		
			    url = "data:text/xml;charset=utf-8," + encodeURIComponent(xmlString);						
    			req.open("GET", url, false);																		    
			    req.send(null);				
			    doc = req.responseXML;	
			}			
			while (this.hasChildNodes())
			{			
				this.removeChild(this.lastChild);
			}			
			for (var i=0; i < doc.childNodes.length; i++)
			{		
				var importedNode = this.importNode(doc.childNodes[i], true);
				this.appendChild(importedNode);
			}				
			handleOnLoad(this);	
			return doc;																
		}
		xdoc.getXML = function()
		{
		    if(window.XMLSerializer)	
		    {
		        s = new window.XMLSerializer();		    
		        return s.serializeToString(this);
		    }
		}
		return xdoc
	}
}

// Internet Explorer.
else if (window.ActiveXObject)
{
	window.XMLDocumentSupported	= true;
	window.XMLDocumentVersion	= 'Microsoft.XMLDOM';
	window.XMLDocument			= function(namespaceUri, rootName)
	{
		var xdoc = new ActiveXObject("Microsoft.XMLDOM");
			
		if (rootName)
		{
			if (namespaceUri)
			{
				xdoc.loadXML("<a0:" + rootName + " xmlns:a0=\"" + namespaceUri + "\" />");
			}
			else
			{
				xdoc.loadXML("<" + rootName + "/>");        
			}
		}
		
		return xdoc;
	}
}

// Mozilla.
else if (document.implementation && document.implementation.createDocument)
{
	window.XMLDocumentSupported	= true;
	window.XMLDocumentVersion	= 'document.implementation';
	window.XMLDocument			= function(namespaceUri, rootName)
	{
		var xdoc = document.implementation.createDocument(namespaceUri, rootName, null);
		xdoc.addEventListener("load", _Document_onload, false);
		xdoc.__defineGetter__("xml", _Node_getXML);
		xdoc.loadXML = function(xmlString)
		{
			changeReadyState(this, 1);			
			var domParser = new DOMParser();
			var doc = domParser.parseFromString(xmlString, "text/xml");		
			while (this.hasChildNodes())
			{
				this.removeChild(this.lastChild);
			}			
			for (var i=0; i < doc.childNodes.length; i++)
			{
				var importedNode = this.importNode(doc.childNodes[i], true);
				this.appendChild(importedNode);
			}				
			handleOnLoad(this);
		}
		return xdoc
	}
	
	Document.prototype.loadXML = function(xmlString)
	{
		changeReadyState(this, 1);
		
		var domParser = new DOMParser();
		var doc = domParser.parseFromString(xmlString, "text/xml");
		
		while (this.hasChildNodes())
		{
			this.removeChild(this.lastChild);
		}
		
		for (var i=0; i < doc.childNodes.length; i++)
		{
			var importedNode = this.importNode(doc.childNodes[i], true);
			this.appendChild(importedNode);
		}
		
		handleOnLoad(this);
	}

	Document.prototype.readyState			= "0";
	Document.prototype.__load__				= Document.prototype.load;
	Document.prototype.load					= _Document_load;
	Document.prototype.onreadystatechange	= null;
	Document.prototype.parseError			= 0;
	Document.prototype.__defineGetter__("xml", _Node_getXML);

	Node.prototype.__defineGetter__("xml", _Node_getXML);
}

// Not Supported.
else
{
	window.XMLDocumentSupported	= false;
	window.XMLDocumentVersion	= 'Not Supported';
}

// ------------------------------------------------------ //
// XMLDocument (document.implementation) Helper Functions //
// ------------------------------------------------------ //

function _Node_getXML()
{
	var serializer = new XMLSerializer();
	return serializer.serializeToString(this);
}

function _Document_load(urlString)
{
	this.parseError = 0;
	changeReadyState(this, 1);
	
	try 
	{
		this.__load__(urlString);
	}
	catch (e)
	{
		this.parseError = -9999999;
		changeReadyState(this, 4);
	}
}

function _Document_onload()
{
	handleOnLoad(this);
}

function handleOnLoad(xmlDocument)
{
	if (!xmlDocument.documentElement || xmlDocument.documentElement.tagName == "parsererror")
		xmlDocument.parseError = -9999999;

	changeReadyState(xmlDocument, 4);
}

function changeReadyState(xmlDocument, state)
{
	xmlDocument.readyState = state;
	
	if (xmlDocument.onreadystatechange != null && typeof xmlDocument.onreadystatechange == "function")
		xmlDocument.onreadystatechange();
}
//global function for select single node from a xmlnode
function selectSingleNode(parentNode, childNodeName)
{
	if( parentNode == null)
		return null;
	var node = null;
	for(var i = 0; i < parentNode.childNodes.length; i++)
	{
		node = parentNode.childNodes[i];
		if(node.tagName == childNodeName)			
			return node;	
	}	
	return null;
}
