/**
* Ajax.js
*
* Collection of Scripts to allow in page communication from browser to (struts) server
* ie can reload part instead of full page
*
* How to use
* ==========
* 1) Call retrieveURL from the relevant event on the HTML page (e.g. onclick)
* 2) Pass the url to contact (e.g. Struts Action) and the name of the HTML form to post
* 3) When the server responds ...
*		 - the script loops through the response , looking for <span id="name">newContent</span>
* 		 - each <span> tag in the *existing* document will be replaced with newContent
*
* NOTE: <span id="name"> is case sensitive. Name *must* follow the first quote mark and end in a quote
*		 Everything after the first '>' mark until </span> is considered content.
*		 Empty Sections should be in the format <span id="name"></span>
*/

//global variables
var req;
var which;


/**
* Get the contents of the URL via an Ajax call
* url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1) 
* nodeToOverWrite - when callback is made
* nameOfFormToPost - which form values will be posted up to the server as part 
*					of the request (can be null)
*/
function retrieveURL(url,nameOfFormToPost) {
    
    //get the (form based) params to push up as part of the get request
    url=url+getFormAsString(nameOfFormToPost);
    
    //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
        req.onreadystatechange = processStateChange;
        try {
            req.open("GET", url, true); //was get
        } catch (e) {
        alert("Problem Communicating with Server\n"+e);
    }
    req.send(null);
} else if (window.ActiveXObject) { // IE

req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
    req.onreadystatechange = processStateChange;
    req.open("GET", url, true);
    req.send();
}
}
}

/*
* Set as the callback method for when XmlHttpRequest State Changes 
* used by retrieveUrl
*/
function processStateChange() {
    
    if (req.readyState == 4) { // Complete
        if (req.status == 200) { // OK response
            
            // alert("Ajax response:"+req.responseText);
            
            //Get elements from response
            element = splitText(req.responseText);
            
            //Use these span elements to update the page
            //replaceExistingWithNewHtml(element);
            
        } else {
        alert("Problem with server response:\n " + req.statusText);
    }
}
}

/**
* gets the contents of the form as a URL encoded String
* suitable for appending to a url
* @param formName to encode
* @return string with encoded form values , beings with &
*/ 
function getFormAsString(formName){
    
    //Setup the return String
    returnString ="?";
    
    //Get the form values
    formElements = document.getElementById(formName);
    
    //loop through the array , building up the url
    //in the form /strutsaction.do&name=value
    var count = 0;
    for (var i=formElements.length-1; i>=0; --i ){
        //we escape (encode) each value
        if (formElements[i].checked) {
            if (count > 0) returnString = returnString + "&";
            returnString=returnString+escape(formElements[i].name)+"="+escape(formElements[i].value);
            count++;
        }
    }
    //return the values
    return returnString; 
}

/**
* Splits the text into elements of interest
* @param the text to be parsed
* @return the selected text
*/
function splitText(textToSplit){
    
    //Split the document
    index1 = textToSplit.indexOf('<div id="mapContent">');
    string1 = textToSplit.substr(index1);
    index2 = string1.indexOf('<script type="text/javascript" defer="defer">');
    index3 =  string1.indexOf('Fin script');
    var count = index3 - index2 - 45;
    mapcontent = string1.substr(index2+45, count);
    eval(mapcontent);
    return mapcontent;
}

/*
* Replace html elements in the existing (ie viewable document)
* with new elements (from the ajax requested document)
* WHERE they have the same name AND are <span> elements
* @param newTextElements (output of splitTextIntoSpan)
*					in the format <span id=name>texttoupdate
*/
function replaceExistingWithNewHtml(newTextElements){
    
    document.getElementById("mapContent").innerHTML = newTextElements;
    
}
