var xmlHttp;

/* 
Creates the XML request object.
*/
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

/*
Starts the transfer process.
*/
function startTransfer(pHandler, pDestination, pParameters) {
    createXMLHttpRequest();
    xmlHttp.onreadystatechange = handleStateChange;
    // the timestamp is filled to prevent clients from caching this Http request
    xmlHttp.open("GET", handler + "?handler=" + pHandler + "&destination=" + pDestination + "&parameters=" + pParameters + "&timestamp=" + new Date().getTime(), true);
    xmlHttp.send(null);
}

/*
Handles the response from the Transfer Handler.
*/
function handleStateChange() {
    if(xmlHttp.readyState == 4) {
        if(xmlHttp.status == 200) {
		var responseText = xmlHttp.responseText;
        	if (isValidTransferResponse(responseText))
        	{
			createForm();
		}
		else
		{
			if (window.transferFault)
			{
				window.location = transferFault;
			}
			else
			{
				window.location = errorHandler;
			}
		}
        }
        else {
		window.location = errorHandler;
        }
    }
}

/*
Determines if the provided responseText looks like a valid TransferResult response xml document or not.
*/
function isValidTransferResponse(text)
{
	var regex = /<TransferResult[^>]+>\s*<destination>([^<]+)<\/destination>\s*<parameters>[\s\S]*?<\/parameters>\s*<\/TransferResult>/;
	var result = text.match(regex);
	
	return result;
}

/*
Prompts a confirm box to the user before transfering if they say ok call the start transfer
*/
function startConfirmTransfer(pHandler, pDestination, pParameters, pMessage) 
{		
	if(confirm(pMessage) ) {	
		startTransfer(pHandler,pDestination,pParameters);
	}	
}

/*
Creates the form to be posted using the XML returned by the
Transfer Handler.
*/
function createForm() {
	var xmlDoc = xmlHttp.responseXML;

	//Create a new form.
	var lForm = document.createElement("form");
	var lBody = document.getElementsByTagName("body")[0];
	lBody.appendChild(lForm);
	lForm.method = "POST";

	var lDestination = xmlDoc.getElementsByTagName("destination")[0];

	lForm.action = lDestination.childNodes[0].nodeValue;

	var lParameters = xmlDoc.getElementsByTagName("parameter");
	createHiddenFields(lForm, lParameters);

	//Get the callback function to use, if any.
	var lCallbackFunction = xmlDoc.getElementsByTagName("callbackFunction")[0];

	if (lCallbackFunction != null)
	{
		eval(lCallbackFunction.childNodes[0].nodeValue);
	}

	lForm.submit();
}

/*
Turns any parameters included in the XML into hidden fields to be posted.
*/
function createHiddenFields(pForm, pParameters) 
{
	var lParameter = null;
	for(var i = 0; i < pParameters.length; i++) 
	{
		var lField = document.createElement("input");
		lField.setAttribute("type", "hidden");
		pForm.appendChild(lField);
        	lParameter = pParameters[i];
		var lName = lParameter.getElementsByTagName("name")[0];
		var lValue = lParameter.getElementsByTagName("value")[0];
		lField.setAttribute("name", lName.childNodes[0].nodeValue);
		lField.setAttribute("value", concatChildNodes(lValue));
	}
}

/*
Concatenates all child node values for the supplied node into one big string.
This fixes the 4096 byte/childNode limitation with FireFox 1.5.0.7 (and other version).
*/
function concatChildNodes(node)
{
	var lResult = "";
	
	for (var lIndex=0; lIndex<node.childNodes.length; lIndex++)
	{
		lResult += node.childNodes[lIndex].nodeValue;
	}
	
	return lResult;
}
