// CREDIT: http://www.ibm.com/developerworks/library/j-ajax1/

/*
 * Returns an new XMLHttpRequest object, or false if the browser
 * doesn't support it
 */
function newXMLHttpRequest() {

  var xmlreq = false;

  // Create XMLHttpRequest object in non-Microsoft browsers
  if (window.XMLHttpRequest) {
    xmlreq = new XMLHttpRequest();

  } else if (window.ActiveXObject) {

    try {
      // Try to create XMLHttpRequest in later versions
      // of Internet Explorer

      xmlreq = new ActiveXObject("Msxml2.XMLHTTP");
      
    } catch (e1) {

      // Failed to create required ActiveXObject
      
      try {
        // Try version supported by older versions
        // of Internet Explorer
      
        xmlreq = new ActiveXObject("Microsoft.XMLHTTP");

      } catch (e2) {

        // Unable to create an XMLHttpRequest by any means
        xmlreq = false;
      }
    }
  }

return xmlreq;
}

 /*
  * Returns a function that waits for the specified XMLHttpRequest
  * to complete, then passes it XML response to the given handler function.
  * req - The XMLHttpRequest whose state is changing
  * responseXmlHandler - Function to pass the XML response to
  */
 function getReadyStateHandler(req, responseXmlHandler) {

   // Return an anonymous function that listens to the XMLHttpRequest instance
   return function () {

     // If the request's status is "complete"
     if (req.readyState == 4) {
       
       // Check that we received a successful response from the server
       if (req.status == 200) {

         // Pass the XML payload of the response to the handler function.
         responseXmlHandler(req.responseXML)

       } else {

         // An HTTP problem has occurred
	 if(req.status && req.statusText)
         alert("HTTP error "+req.status+": "+req.statusText);
	 else
	 alert("unhandled HTTP error")
       }
     }
   }
 }

/*
 * sendRequest
 */
function sendRequest(type, file, handler, params)
{
  // Obtain an XMLHttpRequest instance
  var req = newXMLHttpRequest()

  // Set the handler function to receive callback notifications
  // from the request object
  var handlerFunction = getReadyStateHandler(req, handler)
  req.onreadystatechange = handlerFunction;
  
  // Third parameter specifies request is asynchronous.
  if(type == "GET")
  {
  	req.open(type, file, true)
  	req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT")
	req.send(null)
  }
  else if(type == "POST" && params.length)
  {
  	req.open(type, file, true)
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection", "close");

	var data = ""

	for(var x = 0; x < params.length; x++)
		data += params[x]

	req.send(data);
  }
  else
  {
	alert("Problem sending AJAX request. Please contact the site administrator!")
	return
  }
}