//------------------------------------------------------------------------------
// call:
// AjaxRequest( { callback: javascript callback function or object to refresh,
//						element: id of DOM element to replace,
//                abort: false/true,
//                debug: false/true,
//                method: 'POST'/''GET',
//                url: php server module,
//                args: [array of parameters] });
//
// save last request:
var ajaxRequestList = [];
//
function AjaxRequest(parms)
{
   var http      = null; // the XMLHTTP object
   var loading   = null; // the loading msg object
   // some basic client validation --------------------
   if (!parms.url) {
      alert('AJAX call without server url');
      return;
   }
   if (parms.element) {
      parms['callback'] = ajaxRefresh;
   } else {
      if (parms.callback) {
         if (typeof(parms.callback) != "function") {
            var evaled = eval(parms.callback);
            if (typeof(evaled) == "function") {
               parms['callback'] = evaled;
            } else {
				   parms['callback'] = null;
			   }
         }
      } else {
         parms['callback'] = null;
      }
   }
   if (!parms.debug)  { parms['debug'] = false; }
   if (!parms.abort)  { parms['abort'] = false; }
   // some basic server validation --------------------
   if (!parms.method) { parms['method'] = 'POST'; }
   if (!parms.args || parms.args.length == 0) { parms['args'] = null; }
   // create the XMLHTTP object --------------------
   if (parms.abort) abortRequests();
   http = createHttpObject();
   if (http) {
      ajaxRequestList.push(http);
      loading = document.getElementById("loading");
      sendRequest();
   }
   //-- abort previous request -------------------------------------------------
   function abortRequests()
   {
      var obj = null;
      while (ajaxRequestList.length > 0) {
         obj = ajaxRequestList.pop();
      	if (obj && typeof(obj) == "object") {
      		obj.onreadystatechange = function(){};
            obj.abort();
         }
   	}
   }
   //-- create the XMLHTTP object ----------------------------------------------
   function createHttpObject()
   {
      // always try the activex first if it is present...
      return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
   }
   //---------------------------------------------------------------------------
   function ajaxError(msg)
   {
      ajaxStatus('Error', false);
      alert(msg);
   }
   //---------------------------------------------------------------------------
   function ajaxStatus( msg, show )
   {
      if (loading) { loading.style.display = (show ? "block" : "none"); }
      window.status = msg;
   }
   //---------------------------------------------------------------------------
   function ajaxCleanup()
   {
      // Stop memory leaks --------------------
      http.onreadystatechange = function(){};
      var i = 0;
      while (i < ajaxRequestList.length) {
         if (ajaxRequestList[i] == http) {
            ajaxRequestList.splice(i, 1);
            break;
         } else {
            i++;
         }
      }
      http = null;
   }
   //------------------------------------------------------------------------------
   function rawurldecode(source)
   {
      var response = source.replace(/%2B/g,'+');
      return unescape(response);
   }
   //---------------------------------------------------------------------------
   function rawurlencode(source)
   {
      var str = escape(source);
      return str.replace(/\+/g,'%2B');
   }
   //---------------------------------------------------------------------------
   function processResponse()
   {
      try {
         var response = rawurldecode(http.responseText);
         if (parms.debug) { alert('RETURNED ('+http.readyState+' '+http.status+' '+http.statusText+"):\n" + response); }
         if (response && response.length > 0) {
            // do the callback
            try {
               eval('var data = ' + response);
               if (data.errmsg) { ajaxError( data.errmsg ); }
               else if (parms.callback) { parms.callback( data ); }
            }
            catch(e) {
               if (parms.callback) { parms.callback( response ); }
            }
         }  else if (parms.callback) { parms.callback(); }
         ajaxStatus('Ready', false);
      }
      catch(e) {
         ajaxError("XMLHTTP ERROR: " + e.message + ' STATUS: ' + http.statusText);
      }
   }
   //---------------------------------------------------------------------------
   function ajaxResponse()
   {
      try {
         if (http.readyState != 4) return;
         if (http.status == 200 || http.status == 304) {
            processResponse();
         } else {
            ajaxError("XMLHTTP ERROR: " + http.statusText);
         }
         ajaxCleanup();
      }
      catch(e) {
         ajaxError("XMLHTTP ERROR: " + e.message);
         ajaxCleanup();
      }
   }
   //---------------------------------------------------------------------------
   function ajaxRefresh( html ) {
      if (parms.element) {
         var elt = document.getElementById(parms.element);
         if (elt && elt.innerHTML) elt.innerHTML = html;
      }
   }
   //-- send the HTTP request --------------------------------------------------
   function sendRequest()
   {
      // build the query string --------------------
      var querystr = "";
      if (parms.args && parms.args.length > 0) {
         var tag = 'ARG';
         for (var i = 0; i < parms.args.length; i++) {
            var arg = rawurlencode(parms.args[i]);
            querystr += tag + (i+1) + "=" + arg;
            tag = '&ARG';
         }
      }
      // call server --------------------
      try {
      	ajaxStatus('Running', true);
         var urltogo = parms.url;
         if (parms.method == "GET" && querystr && querystr.length > 0) {
            urltogo += "?" + querystr + "&RAND=" + parseInt( Math.random() * 99999999, 10 );
         }
         if (parms.debug) { alert("SENDING:\n" + parms.method + ": " + urltogo + "\nARGS: " + querystr); }
         // set the callback function --------------------
         http.onreadystatechange = ajaxResponse;
         // set the request --------------------
         http.open(parms.method, urltogo, true);
         if (parms.method == "POST") {
            http.setRequestHeader("Method", "POST "+parms.url+" HTTP/1.1");
            http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=ISO-8859-1");
         } else {
            querystr = null;
         }
         http.setRequestHeader('User-Agent','XMLHTTP');
         http.setRequestHeader("X-Requested-With", "XMLHttpRequest");
         http.send(querystr);
      }
      catch(e) {
         ajaxError("XMLHTTP ERROR: " + e.message);
         ajaxCleanup();
      }
   }
   //---------------------------------------------------------------------------
}