/**
ajax.js

Migrated from Janus "scripts/" folder for Titanized Account Manager
-dw 7/14/2009

Collection of Scripts to allow in page communication from browser to server to
reload parts of a page dynamically

Related Docs:
http://developer.apple.com/internet/webcontent/xmlhttpreq.html
http://jibbering.com/2002/4/httprequest.html
http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c11937/

*/

//
// gets the form fields and url to start the Ajax call
//
function changeStateDisplay(url, myForm) {
	myForm.changeState.value = "true";
	//get the (form based) params to push up as part of the get request
	url = url + getFormAsString(myForm.name);
	// call the ajax function to fetch the new data from the server
	var ajax = new ajaxCall(url);
}

//
// gets the contents of the form as a URL encoded String
//
function getFormAsString(formName) {
	//Setup the return String
	returnString ="";
	//Get the form values
	formElements=document.forms[formName].elements;
	//loop through the array of elements
	for ( var i=formElements.length-1; i>=0; --i ){
		// escape (encode) each value and add to the querystring
		if (formElements[i].type == 'radio') {
			// radio buttons only if checked
			if (formElements[i].checked == true) {
				returnString = returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
			}			
		} else {
			// all other fields
			returnString = returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
		}
	}
	//return the values
	return returnString;
}

//
// Initialize Ajax Request
//
function ajaxCall(url) {
	req = createXMLHttp();
	if (req) {
		// Event handler: event fires at every state change
		req.onreadystatechange = processRequest;
		try {
			// make a HTTP GET request to the URL asynchronously
			req.open("GET", url, true);
			req.send(null);
		} catch (e) {
			alert("Problem Communicating with Server\n" + e);
		}
	}
}

//
// Create an XMLHttpRequest object with the newest version available to this browser
//
function createXMLHttp() {
    if (typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      var aVersions = ["MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
      for (var i = 0; i < aVersions.length; i++) {
        try {
            var oXmlHttp = new ActiveXObject(aVersions[i]);
            return oXmlHttp;
        } catch (oError) {
            //Do nothing so it will test the next XMLHttpRequest version
        }
      }
    }
	//XMLHttp object could be created
	return false;
}

//
// Process the data returned from the server for XmlHttpRequest State Changes
//
function processRequest() {
	// Complete
	if (req.readyState == 4) {
		// OK response
		if (req.status == 200) {
			// Split the text response into Span elements
			spanElements = splitTextIntoSpan(req.responseText);
			// Use these span elements to update the page
			replaceExistingWithNewHtml(spanElements);
		} else {
			alert("Problem with server response:\n " + req.statusText + " " + req.status);
		}
	}
}

// Splits the text into <span> elements
function splitTextIntoSpan(textToSplit){
	//Split the document
	returnElements = textToSplit.split("</span>")
	//Remove everything after the last span
	returnElements.length = returnElements.length-1;
	//Process each of the elements
	for ( var i=returnElements.length-1; i>=0; --i ){
		//if we find a match, take out everything before the span
		if(returnElements[i].indexOf("<span")>0){
			subString = returnElements[i].substring(returnElements[i].indexOf("<span"));
			returnElements[i]=trim(subString);
		}
	}
	return returnElements;
}

// Replace html elements in the document with new elements
// WHERE they have the same name AND are <span> elements
function replaceExistingWithNewHtml(newTextElements) {
	//loop through newTextElements
	for ( var i=newTextElements.length-1; i>=0; --i ) {
		//check that this begins with <span
		if(newTextElements[i].indexOf("<span")>-1) {
			//get the name - between the 1st and 2nd quote mark
			startNamePos=newTextElements[i].indexOf('"')+1;
			endNamePos=newTextElements[i].indexOf('"',startNamePos);
			name=newTextElements[i].substring(startNamePos,endNamePos);
			//get the content - everything after the first > mark
			startContentPos=newTextElements[i].indexOf('>')+1;
			content=newTextElements[i].substring(startContentPos);
			
			//check that this element exists in the document
			if(document.getElementById(name)){
				//alert("Replacing Element:\n" + trim(name) + "\n\nNew Content:\n" + trim(content) + "\n\nExisting HTML Content:\n" + trim(document.getElementById(name).innerHTML));
				// replace the content of this value
				document.getElementById(name).innerHTML = content;
			}
		}
	}
}