// ---------------------------------------------------------------------
// Basic AJAX related GET, POST, and Form Serialization Method Functions
// ---------------------------------------------------------------------
//
// AJAX.js
// Written and coded by Michael Southworth
// May 1, 2009
// 
// LD Computech: http://www.ldcomputech.com
// ---------------------------------------------------------------------

// The AJAX Get Function:

function ajaxGET(URL, Parameters, ID){

// The function received the parameters
// "URL" identifying the script AJAX is going to run,
// "Parameters" which is a string of serialized parameters, and
// "ID" which will be the id of the div the response
// will be inserted into.
//
// Serialized parameters should be in the form:
// "variable1=value1&variable2=value2&variable3=value3" , etc.
//
// The parameters are concatenated with the URL using
// the "?" character as they would in any normal URL
// which uses a GET method:

  URL += "?" + Parameters;

// An object reference to whatever "ID" refers to needs
// to be created:

  var Target = document.getElementById(ID);

// 
// We first need to instantiate an XMLHttpRequest Object.
// This object is the interface to send and recieve data
// via AJAX calls.
//
// Since the browsers all handle AJAX differently
// We have to try several mechanisms and settle on
// whichever works.

  var xmlHttp;								// This will become the XMLHttpRequest object reference.

  try {									// First, the Firefox, Opera 8.0+, Safari method.
    xmlHttp = new XMLHttpRequest();
  }
  catch (e) {								// This caused an error, so now try the newest IE method.
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {								// This also caused an error, so try the old IE method.
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {							// OK, so this browser obviously can't do AJAX.
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

// So now we either have an XMLHttpRequest Object, or a big alert
// saying our browser doesn't support AJAX.
//
// Now we need to define a function for the XMLHttpRequest Object
// that recieves the data back from the server.
// This function will communicate a "readystate" property, used
// to communicate the state of the object.  Such an interface
// is required due to the asyncronous nature of the object.
//
// Possible values of the "readyState" property of the object
// are predefined as:
//
//	0	The request is not initialized
//	1	The request has been set up
//	2	The request has been sent
//	3	The request is in process
//	4	The request is complete

  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4){					// Here the AJAX object is saying the request is complete.

      // Get the response data and set the "Target" object's inner HTML to it.

      Target.innerHTML = xmlHttp.responseText;
    } 
  }

// Now, we need to send the AJAX request to the server.
// the "open" method has the parameters for the communication method,
// the URL for the script, and a "true" to direct asyncronous
// communication.


  xmlHttp.open("GET", URL, true);
  xmlHttp.send(null);

}  // End of the AJAX GET Function


// The AJAX POST Function:

// The POST method contains similar syntax to
// the GET method except where noted below:

function ajaxPOST(URL, Parameters, ID){

// The Parameters are not concatenated with the URL
// using a POST method and are sent seperately.

  var Target = document.getElementById(ID);
  var xmlHttp;						

  try {							
    xmlHttp = new XMLHttpRequest();
  }
  catch (e) {						
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {						
      try {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e) {					
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4){			
      Target.innerHTML = xmlHttp.responseText;
    } 
  }

  xmlHttp.open("POST", URL, true);

// The Post method requires the following headers to be set:

  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", Parameters.length);	// Note that the Parameter length must be sent.
  xmlHttp.setRequestHeader("Connection", "close");

// Parameters are sent in a serialized format using the send method:

  xmlHttp.send(Parameters);  
} // End of the AJAX POST function

// The Form Serialization Function:

// We need a method of serializing the data from a form to avoid
// having to create serialized parameters by hand.
// 
// Usage:
//
// Generally we would define a regular HTML form setting the action
// and catching the submission with an "onsubmit" event.
// We want to then return "false" to stop regular submission and 
// redirect to our own custom function which would serialize the
// form and then call one of our AJAX functions to run the desired
// script.  We want to identify the form by a unique ID.
// 
// The following function serializes the form data from a form
// identified by a unique ID:

    function formSerialize(FormObject){
      var FormData = "";

      for(index = 0; index < FormObject.elements.length; index++){
        var ElementObject = FormObject.elements[index];
        var ElementType = ElementObject.type;
        var ElementName = ElementObject.name;
        var ElementValue = ElementObject.value;

        if(ElementName){						// "submit" and "button" objects can be ignored by not naming them,
									// otherwise their values get sent as if variables.		
          if((ElementType == "checkbox")||(ElementType == "radio")){
            if(ElementObject.checked){					// We want to ignore "radio" and "checkbox" items which are unchecked.
              FormData += ElementName + "=" + ElementValue;
              FormData += "&";
            }
          }
          else {
            FormData += ElementName + "=" + ElementValue;
            FormData += "&";
          }
        }
      }

      FormData = FormData.substring(0, FormData.length-1);		// We added a "&" at the end of every item.
									// The one on the very end needs to be removed.
      return FormData;					
    } // End of the Form Serialization Function

    function formSerializeById(ID){
      var FormObject = document.getElementById(ID);
      var FormData = "";

      for(index = 0; index < FormObject.elements.length; index++){
        var ElementObject = FormObject.elements[index];
        var ElementType = ElementObject.type;
        var ElementName = ElementObject.name;
        var ElementValue = ElementObject.value;

        if(ElementName){						// "submit" and "button" objects can be ignored by not naming them,
									// otherwise their values get sent as if variables.		
          if((ElementType == "checkbox")||(ElementType == "radio")){
            if(ElementObject.checked){					// We want to ignore "radio" and "checkbox" items which are unchecked.
              FormData += ElementName + "=" + ElementValue;
              FormData += "&";
            }
          }
          else {
            FormData += ElementName + "=" + ElementValue;
            FormData += "&";
          }
        }
      }

      FormData = FormData.substring(0, FormData.length-1);		// We added a "&" at the end of every item.
									// The one on the very end needs to be removed.
      return FormData;					
    } // End of the Form Serialization Function

// Form Processing Functions:

// Below are examples of form processors which automate the
// serialization of form data, retrieve the script URL from
// the form "action" property, and initiate a POST method
// AJAX submission.  The response is directed to a target
// div identified by it's ID:

// This function accepts a form ID and div target ID:
//
// Usage: (from within the form declaration tag) 
// onsubmit="return ajaxSubmitById('MyFormID', 'MyDivTargetID');"

    function ajaxSubmitById(ID, Target){

      var FormData = formSerializeById(ID);

      var FormAction = document.getElementById(ID).action;

      ajaxPOST(FormAction, FormData, Target);
      return false;
    }

// This function accepts a form object, normally passed from
// the form using "this", and a div target ID:
// 
// Usage: (from within the form declaration tag) 
// onsubmit="return ajaxSubmit(this, 'MyDivTargetID');"

    function ajaxSubmit(Obj, Target){

      var FormData = formSerialize(Obj);

      if(!Obj.action){
        alert("Please set a form action for the form being submitted.");
        return false;
      }

      var FormAction = Obj.action;

      document.getElementById(Target).innerHTML = '<div class="Title">Sending, Please Wait...</div>';

      ajaxPOST(FormAction, FormData, Target);
      return false;
     }



