/// <reference path="../../CTWebScripts/General.js" />

AJAXRequestControl.prototype.toString = function() { return '[AJAX Request Control]';  }
CTWebParameter.prototype.toString     = function() { return '[CTWebParameter Object]'; }


// CTWebParameter Object
function CTWebParameter(name, value) {
    /// <field name="Name" type="String" />
    /// <field name="Value" type="Object" />
    /// <field name="ExtendedParameters" type="ICTWebParameterCollection" />
    /// <field name="Nodes" type="ICTWebParameterCollection" />
			
	
	/* Parameter properties */
	this.Name  = name;
	this.Value = (value != undefined && value != null) ? value : "";	

    /* Extended Parameters Collection */			
	this.ExtendedParameters = new CTWebParameterCollection();	
		
	// Extended parameters alias
	this.Nodes = this.ExtendedParameters;		
}
CTWebParameter.prototype.Clone = CTWebParam_Clone;

function CTWebParameterCollection()
{
    this.Inherits(Collection);
    delete this.Add;
    
    this.DefaultCollectionObject = CTWebParameter;
}
CTWebParameterCollection.prototype.Add = function(name, value) 
{
	/// <returns type="CTWebParameter" />
	
	if (typeof(this.Add.arguments[0]) == 'object') {
		var o = this.Add.arguments[0];
	} else {
 		var o = new CTWebParameter(this.Add.arguments[0], this.Add.arguments[1]);
	}
	
	this.Items.splice(this.Items.length, 0, o);
	return o;
}
CTWebParameterCollection.prototype.CloneFrom = function(collectionToCloneFrom)
{
    /// <summary>Clones nodes from another collection</summary>
    for (var i = 0; i < collectionToCloneFrom.Items.length; i++)
    {
        this.Items[this.Items.length] = collectionToCloneFrom.Items[i].Clone();
    }
}    
    
function ICTWebParameterCollection() {
    /// <summary>Do not instaniate this object, it is merely used for type casting Collections that use CTWebParameters</summary>
    /// <field name="Items" type="Array" elementType="CTWebParameter" />
}
ICTWebParameterCollection.prototype.Add = function(name, value) {
/// <returns type="CTWebParameter" />
}
ICTWebParameterCollection.prototype.Remove = function(name) {
    /// <returns type="Boolean" />
}
ICTWebParameterCollection.prototype.Remove = function(name) {
    /// <returns type="Boolean" />
}
ICTWebParameterCollection.prototype.Find = function(Attribute, Value, SingleOnly) {
/// <param name="Attribute" type="String">Attribute to compare</param>
/// <param name="Value" type="Object">Value to test for</param>
/// <param name="SingleOnly" type="Boolean">Default is false, when set to true returns the first found matching object</param>
/// <returns type="Array" elementType="CTWebParameter" />    
}

function CTWebParam_Clone() {
    /// <returns type="CTWebParameter" />
    var p = new CTWebParameter(this.Name, this.Value);
   
    var itms = this.Nodes.Items;
    
    for (var i = 0; i < itms.length; i++) {
        p.Nodes.Items[p.Nodes.Items.length] = itms[i].Clone();        
    }
    
    return p;
}

RC_Response.prototype.ShowDebugMessages = __RC_Response_ShowDebugMessages;
function RC_Response() {
    /// <field name="ErrorName" type="String" />
    /// <field name="ErrorNumber" type="Number" />
    /// <field name="ErrorType" type="String" />
    /// <field name="ErrorDescription" type="String" />
    /// <field name="ErrorData" type="Array" elementType="String" />
    /// <field name="SessionID" type="String" />
    /// <field name="DebugMessages" type="Array" elementType="String" />
    /// <field name="Parameters" type="ICTWebParameterCollection" />
    /// <field name="Nodes" type="ICTWebParameterCollection">Same as parameters</param>
    
	this.ErrorName   = "";
	this.ErrorNumber = 0;
	this.ErrorType   = "";
	this.ErrorDescription = "";
	this.ErrorData   = new Array(0);
	 
	this.SessionID = "";
	
	this.DebugMessages = new Array();
	

	this.Parameters = new Collection();
    this.Parameters.DefaultCollectionObject = CTWebParameter;
    
    this.Nodes = this.Parameters;
    
    /* Add() Overload */   
    this.Parameters.Add = function(name, value) 
    {
		if (typeof(this.Add.arguments[0]) == 'object') {
			var o = this.Add.arguments[0];
		} else {
     		var o = new CTWebParameter(this.Add.arguments[0], this.Add.arguments[1]);
		}
		
		this.Items.splice(this.Items.length, 0, o);
		return o;
    }    
}

function __RC_Async_Class(pAJAXRequest) {
    this.__Parent = pAJAXRequest;
    
    this.Enabled        = false;                /* Whether the transaction is run asynchronously (for running long transactions) */
    this.ID             = null;                 /* Call back id for an async transaction */
    this.Timeout        = 300;                  /* Max time to wait for the async transaction to return */
    this.PollInterval   = 1;                /* Time to wait between completion polls */
    
    this.__TimeoutCallback      = function () { __RC_Async_Timedout(pAJAXRequest); } ;
    this.__TimeoutHandle        = null;
    
    this.__StatusCheckCallback  = function() { __RC_Async_StatusCheck(pAJAXRequest); }; 
    this.__StatusCheckHandle    = null;
    
}
__RC_Async_Class.prototype.Clear    = __RCAsync_Clear;
__RC_Async_Class.prototype.Cancel   = __RCAsync_Cancel;


function __RCAsync_Clear() 
{
    this.Enabled = false;
    this.ID = null;
    
    if (this.__TimeoutHandle != null)       clearTimeout(this.__TimeoutHandle);
    if (this.__StatusCheckHandle != null)   clearTimeout(this.__StatusCheckHandle);  
}

function __RCAsync_Cancel()
{
    if (this.ID == null)
    {
        this.__Parent.Events.RaiseEvent("TRANSFERCANCELLED", oJSCtl);
        return;
    }
}

function __RC_Async_Timedout(oJSCtl) 
{
    if (oJSCtl.Async.__StatusCheckHandle != null) clearTimeout(oJSCtl.Async.__StatusCheckHandle);
    if (oJSCtl.Async.__TimeoutHandle     != null) clearTimeout(oJSCtl.Async.__TimeoutHandle);
    
    oJSCtl.Async.__StatusCheckHandle    = null;
    oJSCtl.Async.__TimeoutHandle        = null;
    
    oJSCtl.Downloader.abort();
    oJSCtl.Events.RaiseEvent("ASYNCTRANSFERTIMEDOUT", oJSCtl);  
    oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);    
}

function __RC_RequestAsyncResponseBuilder() {
    this.Clear();

    this.Library        = 'SERVICES';
    this.RequestHandler = 'ASYNCTRANSACTION';
    this.RequestAction  = 'GETASYNCRESPONSE';
    
    var Args = this.RequestParameters.Add("Arguments");
   
    Args.Nodes.Add("TransactionID", this.Async.ID);       
    
    this.Async.Clear();
    this.SendRequest();
}

function __RC_Async_StatusCheck(oJSCtl) {
    if (oJSCtl.Async.__StatusCheckHandle != null) clearTimeout(oJSCtl.Async.__StatusCheckHandle);
    oJSCtl.Async.__StatusCheckHandle = null;
  
    if (oJSCtl.Downloader.readyState != 0 && oJSCtl.Downloader.readyState != 4) {
        // Control is busy
        return;
    }

    oJSCtl.Clear();
    
    // Setup Status Check Request
    oJSCtl.Library = 'SERVICES';
    oJSCtl.RequestHandler = 'ASYNCTRANSACTION';
    oJSCtl.RequestAction  = 'VIEW-LIST';
    
    oJSCtl.RequestParameters.Add("Restrictions", "ID='" + oJSCtl.Async.ID + "'");
    oJSCtl.RequestParameters.Add("Fields", "ID, NumericStatus, TextStatus");

    oJSCtl.Events.RaiseEvent("CHECKING_ASYNCTRANSACTION_STATUS", oJSCtl);
     
    oJSCtl.SendRequest();
}

// RequestControl Object
function AJAXRequestControl() {
    /// <field name="Name" type="String">Not Used</field>
    /// <field name="Response" type="RC_Response" />
    /// <field name="RequestParameters" type="ICTWebParameterCollection">Same as Nodes</field>
    /// <field name="Nodes" type="ICTWebParameterCollection">Same as RequestParameters</field>
    /// <field name="Server" type="String">Server to point to (auto-filled by QueueSystem)</field>
    /// <field name="AJAXEntryPoint" type="String">AJAX Entrypoint location (defaulted)</field>
    /// <field name="Async" type="__RC_Async_Class" />
    /// <field name="Downloader" type="IXMLHTTP" />
    /// <field name="XMLDocument" type="IXMLDOMDocument" />
    /// <field name="XMLResponse" type="IXMLDOMDocument" />
    /// <field name="RequestAction" type="String" />
    /// <field name="RequestHandler" type="String" />
    /// <field name="Library" type="String" />
    /// <field name="EncodeRequest" type="Boolean" />
    /// <field name="DecodeResponse" type="Boolean" />
    /// <field name="AutoParseParams" type="Boolean" />
    /// <field name="CallbackFunction" type="Function" />
    
	GarbageHeap.Add(this);
   
    this.Inherits(WebControl);
   
    this.Name			  = "";
   
    this.Response          = new RC_Response();
      
    this.RequestParameters = new CTWebParameterCollection();
   
    this.Nodes = this.RequestParameters;
   
    this.Server   = "";

    this.AJAXEntryPoint = '/CTWebInterface/CTWebEntryPoints/RequestHandler.aspx';
   
    this.Async = new __RC_Async_Class(this);
        
   
   
    this.b_cancel = false;   
		
    /* Add() Overload */
       
    this.RequestParameters.Add = function(name, value) 
    {
        if (typeof(this.Add.arguments[0]) == 'object') {
	        var o = this.Add.arguments[0];
        } else {
	        var o = new CTWebParameter(this.Add.arguments[0], this.Add.arguments[1]);
        }
    	
        this.Items.splice(this.Items.length, 0, o);
        return o;
    }
		
		
    try { 	 
	    this.Downloader     = new ActiveXObject("MSXML2.XMLHTTP.4.0");
	    this.XMLDocument	= new ActiveXObject("MSXML2.DOMDocument.4.0");
	    this.XMLResponse	= new ActiveXObject("MSXML2.DOMDocument.4.0");
    } catch(err) {

        var ret = Msgbox("The application was unable to initialise a core component.  It is likely that you need to install the Microsoft XML Component.  Would you like to be re-directed to the download location?", vbInformation + vbYesNo, "Download installer?");
        if (ret == vbYes) 
        {
            window.location.href = "http://auto.vitalsoftware.net/PublicFiles/msxml.msi";            
        }    	
	    return false;
    }

	   
	
	   
	this.RequestAction    = "";
	this.RequestHandler   = "";
	this.Library          = "";
	   
	this.EncodeRequest	    = true;
	this.DecodeResponse     = true;
	this.AutoParseParams    = true;
	   
	this.CallbackFunction   = null;	
  
   
	this.__Dispose = function() {	
		if (this.Downloader.readyState != 4) this.Downloader.abort();
	
		this.CallbackFunction = null;	
		this.XMLResponse = null;
		this.XMLDocument = null;
		this.Downloader = null;
		this.RequestParameters = null;
	}               
}
AJAXRequestControl.prototype.ReportError    = RC_ReportError;
AJAXRequestControl.prototype.SendRequest    = RC_SendXMLRequest;
AJAXRequestControl.prototype.Clear          = RC_Clear;
AJAXRequestControl.prototype.Cancel         = RC_Cancel;
AJAXRequestControl.prototype.DisplayRequest = RC_DisplayRequest;
AJAXRequestControl.prototype.RequestAsyncResponse = __RC_RequestAsyncResponseBuilder;
AJAXRequestControl.prototype.XML            = RC_BuildXMLDocument;

Cast.As.AJAXRequest = function(val) {
/// <summary>Returns a casted AJAXRequest</summary>
/// <param name="val" type="AJAXRequestControl">Value to cast</param>
/// <returns type="AJAXRequestControl" />
    return val;
}

function RC_Cancel() 
{
    if (this.Downloader.readyState != 4 && this.Downloader.readyState != 0) 
    {
        this.Downloader.abort();
    }    

	this.b_cancel = true;
	
	if (this.Async.Enabled)
	{
	    this.Async.Cancel();	
	}
	else
	{
	    this.Parent.Events.RaiseEvent("TRANSFERCANCELLED", oJSCtl);
	}

}

function RC_Clear()
{
    var oJSCtl = this;
	oJSCtl.RequestParameters.Clear();
	
	oJSCtl.RequestHandler    = "";
	oJSCtl.RequestAction     = "";		
	oJSCtl.Library           = "";
	
	oJSCtl.XMLDocument		 = new ActiveXObject("MSXML2.DOMDocument.4.0");
	oJSCtl.XMLResponse		 = new ActiveXObject("MSXML2.DOMDocument.4.0");
	
	oJSCtl.Response          = new RC_Response();
}

function RC_AddResponseNodes(oContainer, nodeXML) 
{	
	var oTmp = oContainer.Add();
	oTmp.Name = nodeXML.nodeName;

	if (nodeXML.childNodes.length == 1 && (nodeXML.childNodes[0].nodeType == 3 || nodeXML.childNodes[0].nodeType == 4)) {
		oTmp.Value = (nodeXML.text != undefined) ? nodeXML.text.toString() : "";
	} else {
		for (var i = 0; i < nodeXML.childNodes.length; i++) {
			RC_AddResponseNodes(oTmp.Nodes, nodeXML.childNodes[i])
		}
	}
}

function RC_DisplayRequest(uTarget) {
    var oJSCtl = this;
	oJSCtl.EncodeRequest = false;
	if (uTarget != undefined) {
		uTarget.innerText = RC_BuildXMLDocument(oJSCtl);
	} else {
		alert(RC_BuildXMLDocument(oJSCtl));
	}
	oJSCtl.EncodeRequest = true;	
}

function RC_OnReadyStateChange(oJSCtl)
{
    if (oJSCtl.Downloader.readyState == 4 && oJSCtl.b_cancel)   // exit early, tranfer cancelled
	{
		oJSCtl.Events.RaiseEvent("TRANSFERCANCELLED", oJSCtl);					
		return;	
	}
	if (oJSCtl.Downloader.readyState != 4) return;  // Exit early, download not finished
	
    
    // Transfer Complete

	if (typeof(oJSCtl.XMLResponse) != "object") {	
		oJSCtl.XMLResponse = new ActiveXObject("MSXML2.DOMDocument.4.0");				
	} else {
		if (oJSCtl.XMLResponse.hasChildNodes) {
			oJSCtl.XMLResponse.removeChild(oJSCtl.XMLResponse.childNodes[0]);
		}
	}
				
	var strXML = oJSCtl.Downloader.responseText;					
		oJSCtl.ResponseText = oJSCtl.Downloader.responseText;

    // Time out or user has cancelled the page.
    if (strXML.length == 0) {
        oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
		return;
    }    

	oJSCtl.XMLResponse.loadXML(strXML);	

	if (oJSCtl.XMLResponse.parseError != 0)
	{	
	    if (oJSCtl.Parent != null && oJSCtl.Parent != undefined)
	    {
	        // Running in QueueSystem
	    } 
	    else
	    {
	        // Running Stand Alone
		    oJSCtl.ReportError();
		}
		
		oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
		return;
	}

	
	// ** OK, load the response nodes into the response object		
	var nodeXMLHeader   = oJSCtl.XMLResponse.selectSingleNode("//DataTransfer/Header");
	var nodeXMLResponse = oJSCtl.XMLResponse.selectSingleNode("//DataTransfer/Response");				
	
	if (nodeXMLHeader == null || nodeXMLResponse == null) {
		var ret = Msgbox("A problem occurred with the server response, an internal server error may have occurred.\n\nWould you like to see the response?", vbQuestion + vbYesNo, "View server response?");
        if (ret == vbYes) alert(strXML);
        
		oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
		return;
	}
	
	// Check to see if a response size has been attached
	var nodResponseSize = oJSCtl.XMLResponse.selectSingleNode("//DataTransfer/Header/ResponseSize");
	if (nodResponseSize != null) 
	{
	    var sResponseSize = nodResponseSize.text.Trim();
	    var iResponseSize = sResponseSize.ToInt();
	    
	    if (iResponseSize != oJSCtl.XMLResponse.xml.length) 
	    {
	        alert("Response size does not match the original size sent from the server...!!!!");
	    }
	}

	var Response = oJSCtl.Response;
	// Add the response header properties
	Response.ErrorNumber			= nodeXMLHeader.selectSingleNode("ErrorNumber").text.ToInt();
	Response.ErrorType				= nodeXMLHeader.selectSingleNode("ErrorType").text.toString();
	Response.ErrorDescription		= nodeXMLHeader.selectSingleNode("ErrorDescription").text.toString();			
	
	var nodErrorName                = nodeXMLHeader.selectSingleNode("ErrorName");
	if (nodErrorName != null) 
	    Response.ErrorName		    = nodErrorName.text.toString();		
	
	var nodErrorData                = nodeXMLHeader.selectSingleNode("ErrorData");
	if (nodErrorData != null) 
	{
	    for (var i = 0; i < nodErrorData.childNodes.length; i++)
	    {
	        Response.ErrorData[Response.ErrorData.length] = { Key   : nodErrorData.childNodes[i].selectSingleNode("Key").text,  
	                                                          Value : nodErrorData.childNodes[i].selectSingleNode("Value").text 
	                                                         }
	    }
	}
							
	Response.Parameters.Clear();
	
	// Parse debug messages.
	var DebugMessages = Response.DebugMessages;
	DebugMessages.splice(0, DebugMessages.length);
	
	var oxmlDebugMessages = nodeXMLHeader.selectSingleNode("DebugMessages");
	
	if (oxmlDebugMessages != null) {
		for (var i = 0; i < oxmlDebugMessages.childNodes.length; i++)
		{
			try { DebugMessages[i] = oxmlDebugMessages.childNodes[i].text; } catch (err) { } 
		}
	}
	
	// Test If the AJAXRequest Control is parented by the queuesystem.
	var bParse = (oJSCtl.Parent != undefined) ? oJSCtl.Parent.Parent.AutoParseParams : oJSCtl.AutoParseParams;
	if (bParse) {
		for (var i = 0; i < nodeXMLResponse.childNodes.length; i++) {
			RC_AddResponseNodes(oJSCtl.Response.Parameters, nodeXMLResponse.childNodes[i]);
		}			 									
	}


	if (oJSCtl.Async.Enabled == true && oJSCtl.Async.ID == null) {		
   
        // Just started a new async call
        var nodAsyncID = oJSCtl.XMLResponse.selectSingleNode("//DataTransfer/Response/TransactionID");
  
        if (nodAsyncID == null) {
            oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
	        return;
        }
        
        // Retrieve the call back ID
        oJSCtl.Async.ID = nodAsyncID.text;    

        // Set Timeout for maximum amount of time to wait for it to complete executing
        if (oJSCtl.Async.Timeout > 0)
        {
            oJSCtl.Async.__TimeoutHandle = setTimeout(oJSCtl.Async.__TimeoutCallback, oJSCtl.Async.Timeout * 1000);
        }
        
        // Set Timeout for checking its completion
        oJSCtl.Async.__StatusCheckHandle = setTimeout(oJSCtl.Async.__StatusCheckCallback, oJSCtl.Async.PollInterval * 1000);
	
	    
	    
	} else {

		if (oJSCtl.Async.Enabled == true) {
		    // Will be a status check
		    var oStatusCheck = oJSCtl.XMLResponse.selectSingleNode("//DataTransfer/Response/DataSet/Record/NumericStatus");
		    if (oStatusCheck == null) {
		        oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
		        return;
		    }
		    
		    var iStatusCheck = oStatusCheck.text.toString().ToInt();
		    
		    clearTimeout(oJSCtl.Async.__StatusCheckHandle);
		    oJSCtl.Async.__StatusCheckHandle    = null; 		    

            oJSCtl.Events.RaiseEvent("ASYNCSTATUSRECEIVED", oJSCtl, iStatusCheck);

		    switch (iStatusCheck) 
		    {
		        case 0 : //Ongoing
		            oJSCtl.Async.__StatusCheckHandle = setTimeout(oJSCtl.Async.__StatusCheckCallback, oJSCtl.Async.PollInterval * 1000);
                    break;
                
                case 1 : // Completed
                    //clearTimeout(oJSCtl.Async.__TimeoutHandle);  
                    //oJSCtl.Async.__TimeoutHandle = null;   
                    oJSCtl.Async.Enabled = false;
                    oJSCtl.RequestAsyncResponse();                               
                    break;
                    		        
		        case 2 : // Failed
		        case 3 : // Cancelled
		            clearTimeout(oJSCtl.Async.__TimeoutHandle);
		            oJSCtl.Async.__TimeoutHandle = null;
		            oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
                    break;
		            
		        default:
		            oJSCtl.Events.RaiseEvent("TRANSFERFAILED", oJSCtl);
		            break;
		    }
	   
		    return;
		}
																					
	    oJSCtl.Events.RaiseEvent("TRANSFERCOMPLETE", oJSCtl);
	}								

	
}

function RC_SendXMLRequest()
{	
    var oJSCtl = this;    
    RC_BuildXMLDocument(oJSCtl);
    oJSCtl.b_cancel = false;

	oJSCtl.Downloader.open("POST", oJSCtl.AJAXEntryPoint, true, "", "");		

	oJSCtl.Downloader.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		
	// Assign our callback					
	oJSCtl.CallbackFunction = function() { return RC_OnReadyStateChange(oJSCtl); }	
	oJSCtl.Downloader.onreadystatechange = oJSCtl.CallbackFunction;		
					
	// Add Request size
    var iRequestLength = oJSCtl.XMLDocument.xml.length;
		
	// Convert this to a proper form post				
	var strXML = "RequestSize=" + iRequestLength + '&XmlPost=' + escape(oJSCtl.XMLDocument.xml);	
	
	oJSCtl.Downloader.send(strXML);	
}

function RC_AddParams(colParams, nodeParam, oJSCtl)
{					
	for (var i = 0; i < colParams.Items.length; i++)
	{						
		var nodeExtParam = oJSCtl.XMLDocument.createElement(colParams.Items[i].Name);											

		if (colParams.Items[i].Value != undefined) {
			nodeExtParam.nodeTypedValue = (oJSCtl.EncodeRequest == true) ? EncodeHTML(colParams.Items[i].Value.toString()) : colParams.Items[i].Value.toString();
		} else {
			nodeExtParam.nodeTypedValue = "";
		}

		nodeParam.appendChild(nodeExtParam);
		
		if (colParams.Items[i].ExtendedParameters.Items.length > 0)
			RC_AddParams(colParams.Items[i].ExtendedParameters, nodeExtParam, oJSCtl);		
	}
}

function RC_BuildXMLDocument(oJSCtl) {
    /// <summary>Builds the XML document</summary>
    /// <param name="oJSCtl" type="AJAXRequestControl">Optional</param>
    /// <returns type="IXMLDOMNode" />
    
    if (oJSCtl == undefined) oJSCtl = this;
    
	oJSCtl.XMLDocument	 = new ActiveXObject("MSXML2.DOMDocument.4.0");		
	
    var nodeRoot		 = oJSCtl.XMLDocument.createElement("DataTransfer");
    var nodeHeader       = oJSCtl.XMLDocument.createElement("Header");
    var nodePage        = oJSCtl.XMLDocument.createElement("Page");             // Used for tracing
    var nodeCorrelationId = oJSCtl.XMLDocument.createElement("CorrelationId");  // Used for tracing
    var nodeAction	     = oJSCtl.XMLDocument.createElement("Action");	
    var nodeClassHandler = oJSCtl.XMLDocument.createElement("ClassHandler");
    var nodeRequest		 = oJSCtl.XMLDocument.createElement("Request");
    var nodLibrary       = oJSCtl.XMLDocument.createElement("Library");
	
    var nodExecute         = oJSCtl.XMLDocument.createElement("Execute");

    // ** Set the header values
    nodeAction.nodeTypedValue		= (oJSCtl.EncodeRequest == true) ? EncodeHTML(oJSCtl.RequestAction)  : oJSCtl.RequestAction;
    nodeClassHandler.nodeTypedValue = (oJSCtl.EncodeRequest == true) ? EncodeHTML(oJSCtl.RequestHandler) : oJSCtl.RequestHandler;				
    nodLibrary.nodeTypedValue		= (oJSCtl.EncodeRequest == true) ? EncodeHTML(oJSCtl.Library)  : oJSCtl.Library;
    nodePage.nodeTypedValue         = (oJSCtl.EncodeRequest == true) ? EncodeHTML(Authent_CurrentPage) : Authent_CurrentPage;
    nodeCorrelationId.nodeTypedValue = (oJSCtl.EncodeRequest == true) ? EncodeHTML(Authent_CorrelationId) : Authent_CorrelationId;
           
    // ** Set Async Properties
    var sExecute = oJSCtl.Async.Enabled == true && oJSCtl.Async.ID == null ? 'ASYNC' : 'SYNC';
    nodExecute.nodeTypedValue       = (oJSCtl.EncodeRequest == true) ? EncodeHTML(sExecute) : sExecute;
    

    var aItems =  oJSCtl.RequestParameters.Items;
    // ** Now add the parameter nodes		
    for (var i = 0; i < aItems.length; i++)
    {
	    var param = aItems[i];	
		
	    if (param.Name == undefined)
	    {
	        var e = new Error();
		    e.message = "Undefined parameter name passed in RC_BuildXMLDocument()";
		    e.description = e.message;
		    throw e;			
	    }	
		
	    var nodeParam = oJSCtl.XMLDocument.createElement(param.Name);
		
	    if (param.Value != undefined) {
		    nodeParam.nodeTypedValue = (oJSCtl.EncodeRequest == true) ?  EncodeHTML(param.Value.toString()) : param.Value.toString();				
	    } else {
		    nodeParam.nodeTypedValue = "";
	    }
				
	    if (param.ExtendedParameters.Items.length > 0)
	    {
		    RC_AddParams(param.ExtendedParameters, nodeParam, oJSCtl);
	    }
			
	    nodeRequest.appendChild(nodeParam);
    }
	    
    // ** Now attach the nodes to the document
    nodeHeader.appendChild(nodeAction);
    nodeHeader.appendChild(nodeClassHandler);
    nodeHeader.appendChild(nodLibrary);

    nodeHeader.appendChild(nodePage);
    nodeHeader.appendChild(nodeCorrelationId);
    
    nodeHeader.appendChild(nodExecute);
	
    nodeRoot.appendChild(nodeHeader);
    nodeRoot.appendChild(nodeRequest);
	
    oJSCtl.XMLDocument.appendChild(nodeRoot);
		
	return oJSCtl.XMLDocument.xml;
}

/* Decoding functions */
function RC_DecodeXML(xmlstring)
{
	var i;
	var intag = true;
		
	var x = new ActiveXObject("MSXML2.DOMDocument.4.0");
	x.loadXML(xmlstring);

	for (i = 1; i < x.childNodes.length; i++)
	{
		RC_DecodeNode(x.childNodes[i]);
	}
			
	return x.xml;
}
	
function RC_DecodeNode(node)
{
	return;

	var i;
	if (!node.hasChildNodes())
	{
		node.text = ToDisplay(node.text);
	}
	for (i = 0; i < node.childNodes.length; i++)
	{
		RC_DecodeNode(node.childNodes[i]);
	}
}

function __RC_Response_ShowDebugMessages() {
    /// <summary>Shows the debug messages in a debug window</summary>
    var o = new DebugDialogOptions(this.DebugMessages);
    o.Show();	
	//for (var i =0; i <  this.DebugMessages.length; i++)
//		alert(this.DebugMessages[i]);
}


function RC_ReportError() {
	try {
		var oJSCtl = this;
		var oErrArgs = new AJAXErrorDialogOptions(oJSCtl, null, "SERVERERROR");	
		
		var o = window.showModalDialog("/AJAXErrorReportDialog.html", oErrArgs, "dialogHeight: 260px; dialogWidth: 450px;");
		
		return true;
	} catch (err)
	{
		return false;
	}
}

var AJAXError = AJAXErrorDialogOptions;
function AJAXErrorDialogOptions(oAJAXRequest, sCaption, sErrorType) {
    if (oAJAXRequest == undefined || oAJAXRequest == null) {
        var e = new Error();
        e.message = 'No AJAXRequest object has been passed in, this is a required parameter!';
        e.description = e.message;
        throw e;
    }

	var initValue = oAJAXRequest.EncodeRequest;
	oAJAXRequest.EncodeRequest		= false;
	
	this.RequestXML					= RC_BuildXMLDocument(oAJAXRequest);
	oAJAXRequest.EncodeRequest = initValue;
	
	this.ResponseXML				= oAJAXRequest.XMLResponse.xml;
	this.ResponseText				= oAJAXRequest.ResponseText;
	this.AdvancedInfo               = '';        
	this.Caption                    = '';
	this.Icon                       = vbCritical;
	this.AllowErrorSend             = true;
	this.AllowAdvanced              = true;
	this.AllowCopy                  = true;
	
	switch (sErrorType)
	{
	    case "SERVERERROR":	    // Server Error (Bad Compile / Unhandled Exception) 	
	        this.Icon               = vbCritical;
	        this.Caption            = (sCaption == null || sCaption == undefined || sCaption.length == 0) ? 'A serious error has occurred' : sCaption;
	        this.AdvancedInfo       = oAJAXRequest.XMLResponse.parseError.reason + "\n\n" + this.ResponseText;  
	        this.AllowErrorSend     = true;       
	        break;
	        
	        
	    default:    // Standard AJAX Error
	        this.Caption            = (sCaption == null || sCaption == undefined || sCaption.length == 0) ? 'A page error has occurred' : sCaption;
	        this.Icon               = vbExclamation;
	        this.AllowErrorSend     = true;
	        this.SimpleInfo         = oAJAXRequest.Response.ErrorDescription;
	        this.AllowErrorSend     = false;
	        try {
	            this.AdvancedInfo = oAJAXRequest.XMLResponse.selectSingleNode("//DataTransfer/Header/Source").text;
	        } catch (err) {}
	}
	   
	this.AuthenticationKey			= Authent_Key;
	this.Authent_UserID				= Authent_UserID;
	this.Authent_LoggedIn			= Authent_LoggedIn;
	this.Authent_OrganisationID		= Authent_OrganisationID;
	this.CurrentDatabaseID			= getCookie("CurrentDatabaseID");
	this.CookieStatus				= document.cookies;
	this.RequestAction				= oAJAXRequest.RequestAction;
	this.RequestHandler				= oAJAXRequest.RequestHandler;
	this.URL						= window.location;
}
AJAXErrorDialogOptions.prototype.Show = __AJAXEDO_Show;


function __AJAXEDO_Show() {
    window.showModalDialog("/AJAXErrorReportDialog.html", this, "dialogHeight: 260px; dialogWidth: 450px;");
}
