/*********************************************************************************************************************
*
*                            Copyright (C) 2006; Action Information Management Ltd
*
*********************************************************************************************************************
*
*          System Name       :  Common Resources
*          Module Name       :  /uk/co/aimltd/resources/javascript/Ajax.js                                                                                             *
*          Author            :  bmundin
*          Date Created      :
*
*********************************************************************************************************************/
/**
 * 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 <ajaxReplace id="ID_OF_ELEMENT">newContent</ajaxReplace>
 * 		 - each element with the same ID in the *existing* document will be replaced with newContent
 *
 * NOTE: <ajaxReplace id="ID_OF_ELEMENT"> is case sensitive. id *must* follow the first quote mark and end in a quote
 *		 Everything after the first '>' mark until </ajaxReplace> is considered content.
 *		 Empty Sections should be in the format <ajaxReplace id="ID_OF_ELEMENT"></ajaxReplace>
 */

//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, if there is no form data.)
   */
	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+"\nURL:" + url );
      			}

      		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()
  		{
  		// Has the request completed ?
		if (req.readyState == 4)
			{
			// Did we get an HTTP 200 OK response ?
			if (req.status == 200)
				{
        		// alert("Ajax response:"+req.responseText);

        		// Split the text response into div elements
        		divElements = splitTextIntoElements(req.responseText);

        		// Use these div elements to update the page
        		replaceExistingWithNewHtml(divElements);
      			}
      		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; if null then the form will not be loaded.
  * @return string with encoded form values , beings with &
  */
 function getFormAsString(formName){

 	//Setup the return String
 	returnString ="";

 	if ( formName != null )
 		{
	  	//Get the form values
	  	var theform = document.forms[formName];

	  	if ( theform != null )
	  		{
		 	formElements=theform.elements;

		 	//loop through the array , building up the url
		 	//in the form /strutsaction.do&name=value

		 	for ( var i=formElements.length-1; i>=0; --i )
		 		{
		 		if (formElements[i].name != "")
		 			{
		 			//we escape (encode) each value
		 			returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
		 			}
			 	}
			 }

		myRand=parseInt(Math.random()*99999999);  // cache buster
 		returnString = "?" + returnString.substring(1)+ "&rand=" + myRand;
		}

 	//return the values
 	return returnString;
 }

 /**
   * Splits the text into <ajaxReplace> elements
   *
   * @param the text to be parsed
   *
   * @return array of <ajaxReplace> elements - this array can contain nulls
   */
 function splitTextIntoElements(textToSplit)
 	{
  	// Split the document
 	returnElements = textToSplit.split("</ajaxReplace>");

 	// Process each of the elements
 	for (var i = returnElements.length-1;
 		 i >= 0;
 		 --i)
		{
 		// Remove everything before the 1st ajaxReplace
 		divPos = returnElements[i].indexOf("<ajaxReplace");

 		// Did we find a match ?
 		if(divPos>0)
 			{
 			// Take out everything before the ajaxReplace
 			subString=returnElements[i].substring(divPos);
 			returnElements[i]=subString;
 			}
 		}

 	return returnElements;
	}

 /*
  * Replace html elements in the existing (ie viewable document)
  * with new elements (from the ajax requested document)
  * WHERE they have the same ID.
  *
  * @param newTextElements (output of splitTextIntoElements)
  *					in the format <ajaxReplace id="ID_OF_OBJECT">texttoupdate
  */
 function replaceExistingWithNewHtml(newTextElements)
 	{
 	// Loop through the list of elements to replace
 	for ( var i=newTextElements.length-1; i>=0; --i )
 		{
 		// check that this begins with <ajaxReplace
 		if(newTextElements[i].indexOf("<ajaxReplace")>-1)
 			{
 			// Get the ID of the element to replace
 			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);

 			//Now update the existing Document with this element

	 			// Does out existing document have an element with this ID ?
	 			if(document.getElementById(name))
	 				{
	 				//alert("Replacing Element:"+name);
	 				document.getElementById(name).innerHTML = content;
	 				}
	 			else
	 				{
	 				//alert("Element:"+name+"not found in existing document");
	 				}
 			}
 		}
	}
