var ajax_working = false;
var http_request = getHTTPObject();

var templateContainerForm;
var destinationContainerForm;

/*
Create the HTTP XML Object
*/
function getHTTPObject() {
	var xmlhttp;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
    	xmlhttp = new XMLHttpRequest();
		if (xmlhttp.overrideMimeType) {
        	xmlhttp.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
    	try {
        	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
            	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
    	}
    }
      
	if (!xmlhttp) {
        alert('Cannot create XMLHTTP instance');
    	return false;
	}
      
	return xmlhttp;
}


/*
Process the Return Response from the HTTP XML Object
*/
function handleHttpResponse() {
	if ((http_request.readyState == 4) && (http_request.status == 200)) {		
		// we're done executing
		ajax_working = false;
		
		// Copy template form to destination form (if we're in that situation)
		if ((templateContainerForm) && (destinationContainerForm)) {
			var tmpStr = templateContainerForm.innerHTML;
			
			// Replace hardcoded variables in the template form html
			tmpStr = replace(tmpStr, '{form_id}', destinationContainerForm.id);
			tmpStr = replace(tmpStr, '{form_name}', destinationContainerForm.name);

			// Assign the destination form innerHTML			
			destinationContainerForm.innerHTML = tmpStr;
		}
		
		// Use the XML DOM to unpack the variables and values
		//alert(http_request.responseText);
		var xmlObj = http_request.responseXML.documentElement;
		
		if (!xmlObj) { return false; }
		
		// Normalize the xmlObj to avoid size restrictions
		xmlObj.normalize();
		
		// If we have child nodes
		if (xmlObj.hasChildNodes()) {
			// Loop through each sub-child node
			for (i = 0; i < xmlObj.childNodes.length; i++) {
				// If the node type is text
				if (xmlObj.childNodes[i].nodeType == 1) {
					
					// Assign var names and values
					var itemName = xmlObj.childNodes[i].nodeName;
					var itemValue = xmlObj.childNodes[i].firstChild.nodeValue;
					//alert(itemName + ' = ' + itemValue);

					// Check to see if we're using a template to destination form situation
					if (destinationContainerForm) {
						var pageElem = findContainedObj(itemName, destinationContainerForm);

					// Otherwise, just find the element on the page
					} else {
						var pageElem = findObj(itemName);
					}
					
					//alert(pageElem.id);

					if (itemValue != '') {
						if (itemName.indexOf('_error') > -1) {
							setFormError(itemName);
							//setPageElementValue(pageElem, itemValue, itemName, false);
						} else {
							setPageElementValue(pageElem, itemValue, itemName, false);
						}
					}
				}
			}
						
		} else {
			// Invalid XML type -- no nodes found
			alert('\'' + xmlObj.tagName + '\' is an Invalid XML Object -- No Nodes Found!');
		}		
	}
}


/*
Clean out certain special characters (specifically MS Word characters)
*/
function cleanFormValue(iValue) {
	var tmpCodes   = new Array(8211, 8212, 8216, 8217, 8220, 8221, 8226, 8230);
	var tmpStrings = new Array("--", "--", "'",  "'",  '"',  '"',  "*",  "...");

	var tmpVal = iValue;
  
	for (i = 0; i < tmpCodes.length; i++) {
    	var tmpSwap = new RegExp("\\u" + tmpCodes[i].toString(16), "g"); // Hex value
    	tmpVal = tmpVal.replace(tmpSwap, tmpStrings[i]);
  	}
	
  	tmpVal = replace(tmpVal, '+', '&#43;');
	
	return tmpVal;
}


/*
Perform the ajax function with the specify values
*/
function performAjax(requestVars, url, templateForm, destinationForm) {	
	// If we're not already performing an XML request, and we have a valid HTTP XML object	
	if (!ajax_working && http_request) {
			
		var isForm = false;
				
		// generate a random number (1 - 100000) so IE wont cache the results
		var randomnumber = Math.floor(Math.random() * 100001);
		var postString = randomnumber + '=' + randomnumber;

		if (requestVars.length) {
			
			// if the reqest vars has a name/id assume it's a form
			if ((requestVars.id) || (requestVars.name)) { isForm = true; }
			
			// If we have a form obj loop through each element and add it to the post string
			if (isForm) {
				for (i = 0; i < requestVars.length; i ++) {
					// Dont overwrite the action
					if ((requestVars[i].name != 'action') && (requestVars[i].name)) {
						
						// If we're dealing with a checkbox or a radio button -- make sure they are checked before passing the value
						if ((requestVars[i].type == 'checkbox') || (requestVars[i].type == 'radio')) {							
							if (requestVars[i].checked == true) {
								postString += "&" + escape(requestVars[i].name) + "=" + escape(requestVars[i].value);								
							}
							
						// If we're dealing with a multiple select box
						} else if (requestVars[i].type == 'select-multiple') {
							for (var ji = 0; ji < requestVars[i].length; ji ++) {
								var opt = requestVars[i].options[ji];   
								if (opt.selected) {
									var val = opt.value;
									if (!val) { val = opt.text; }									
									postString += "&" + escape(requestVars[i].name)	+ "=" + escape(val);
								}								
							}
							
						// Just a normal form element -- pass the value
						} else {
							postString += "&" + escape(requestVars[i].name) + "=" + escape(cleanFormValue(requestVars[i].value));
						}
					}
				}
				
			// Loop through all the request vars and add it to the post string
			} else {
				for (var i in requestVars) {
					// Dont overwrite the action
					if (requestVars[i].name != 'action') {
						postString += "&" + escape(i) + "=" + escape(requestVars[i]);
					}
				}
			}
		}
	
		// Set the template and destination forms (if they're passed in)
		if (templateForm != '') {
			templateContainerForm = document.getElementById(templateForm);
		} else {
			templateContainerForm = '';
		}
		
		if (destinationForm != '') {
			destinationContainerForm = document.getElementById(destinationForm);
		} else {
			destinationContainerForm = '';
		}
		
		// Perform the XML POST request
		//alert(url + ' -- ' + postString);
		http_request.open("POST", url, true);
		http_request.onreadystatechange = handleHttpResponse;
		
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", postString.length);
		http_request.setRequestHeader("Cache-Control", "no-cache");
		http_request.setRequestHeader("If-Modified-Since", "Wed, 31 Dec 1980 00:00:00 GMT"); 
		http_request.setRequestHeader("Expires", "Wed, 31 Dec 1980 00:00:00 GMT");
		//http_request.setRequestHeader("Connection", "close");

		ajax_working = true;
		http_request.send(postString);
	}
}