/******************************************************************************/
/******************************************************************************/
// My AJAX Class
/******************************************************************************/
var AJAX_ENGINE_NAME = "AJAX";
var AJAX_ENGINE_VER = 2.0;
var AJAX_ENGINE_NAME_VER = AJAX_ENGINE_NAME + "/" + AJAX_ENGINE_VER;

/******************************************************************************/
/******************************************************************************/
function AJAXResponse(request){
   this.Text = request.browser_obj.responseText;
   this.XML = request.browser_obj.responseXML;
   this.StatusCode = request.browser_obj.status;
   
   this.Headers = request.browser_obj.getAllResponseHeaders();
   
   this.Duration = (new Date()).valueOf() - request.start_time;
   this.Bytes = request.browser_obj.responseText.length;
   
   try{
      // DANGER WILL ROBINSON
      //this.JSON = eval('(' + request.browser_obj.responseText + ')');
      
      // Semi-Safe?
      this.JSON = JSON.parse(request.browser_obj.responseText);
   }catch(e){
      this.JSON = false;
   }
}

/******************************************************************************/
/******************************************************************************/
function AJAXRequest(){
   // for easy scopeing into methods
   var ajax_request = this;
   
   this.method = "GET";
   this.url = "/";
   this.headers = null;
   this.body = "";
   
   this.timeouttimer = false;
   this.response = false;
   this.onLoadCB = false;
   this.onTimeoutCB = false;
   this.onErrorCB = false;
   this.onRequestCB = false;
   this.TimeoutSecs = 5;
   
   this.start_time = 0;
   this.timedout = false;
   
/******************************************************************************/
   this.createBrowserObj = function(){
      if(window.XMLHttpRequest){
         try{ return new XMLHttpRequest(); }catch(e){ return false; }
      }else if(window.ActiveXObject){
         try{ return new ActiveXObject("Msxlm2.XMLHTTP"); }catch(e){
            try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){ return false; }
         }
      }else if(window.createRequest){
         try{ return window.createRequest(); }catch(e){ return false; }
      }
      
      return false;
   }
   
/******************************************************************************/
   this.readystateHandler = function (){
      // some basic error checking
      if(!ajax_request.browser_obj){}
      
      if(ajax_request.browser_obj.readyState == 0){ // uninitialized
      }else if(ajax_request.browser_obj.readyState == 1){ // loading
      }else if(ajax_request.browser_obj.readyState == 2){ // loaded
      }else if(ajax_request.browser_obj.readyState == 3){ // interactive
      }else if(ajax_request.browser_obj.readyState == 4){ // complete
         // clear any existing timeout
         window.clearTimeout(ajax_request.timeouttimer);
         
         // Create a responce object
         ajax_request.response = new AJAXResponse(ajax_request);
         
         if((ajax_request.browser_obj.status >= 200) && (ajax_request.browser_obj.status < 300)){
            if(typeof(ajax_request.onLoadCB) == 'function'){ ajax_request.onLoadCB(ajax_request); }
            
            // Hook into google analytics
            if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Success'); }
         }else{
            // Error
            //if(!ajax_request.browser_obj.status){
            if(ajax_request.timedout){
               if(typeof(ajax_request.onTimeoutCB) == 'function'){ ajax_request.onTimeoutCB(ajax_request); }
               
               // Hook into google analytics
               if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Timeout'); }
            }else{
               if(typeof(ajax_request.onErrorCB) == 'function'){ ajax_request.onErrorCB(ajax_request, "valid responce with error, see StatusCode"); }
               // Hook into google analytics
               if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Error', ajax_request.browser_obj.status); }
            }
         }
      }
   }
   
/******************************************************************************/
   this.timeoutHandler = function(){
      // cancle out of the request. then 
      ajax_request.browser_obj.abort();
   }
   
/******************************************************************************/
   this.request = function(params){
      
      
      if(params.method){ ajax_request.method = params.method; }
      if(params.url){ ajax_request.url = params.url; }
      if(typeof(params.onload) == 'function'){ ajax_request.onLoadCB = params.onload; }
      if(typeof(params.ontimeout) == 'function'){ ajax_request.onTimeoutCB = params.ontimeout; }
      if(typeof(params.onerror) == 'function'){ ajax_request.onErrorCB = params.onerror; }
      if(typeof(params.onrequest) == 'function'){ ajax_request.onRequestCB = params.onrequest; }
      if(params.timeout_secs){ ajax_request.TimeoutSecs = params.timeout_secs; }
      if(params.headers){ ajax_request.headers = params.headers; }
      if(params.body){ ajax_request.body = params.body; }
      
      if(this.browser_obj){
         if(ajax_request.browser_obj.readyState != 0){
            // Error - ajax currently in use?
            if(typeof(ajax_request.onErrorCB) == 'function'){ ajax_request.onErrorCB(ajax_request, "AJAX Object in use"); }
            
            // Hook into google analytics
            if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Obj in Use'); }
      
         }else{
            if(typeof ajax_request.onRequestCB == 'function'){ ajax_request.onRequestCB(ajax_request); }
            
            this.browser_obj.onreadystatechange = this.readystateHandler;
            this.browser_obj.open(ajax_request.method, ajax_request.url, true);
            this.browser_obj.setRequestHeader("User-Agent", AJAX_ENGINE_NAME_VER); // doesn't set on some browsers
            if(ajax_request.method == "POST"){
              //this.browser_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
              this.browser_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            this.browser_obj.setRequestHeader("X-Requested-With", AJAX_ENGINE_NAME);
            this.browser_obj.setRequestHeader("X-Ajax-Engine", AJAX_ENGINE_NAME);
            this.browser_obj.setRequestHeader("X-Is-Ajax", "true");
            
            if((ajax_request.headers.length % 2) == 0){
               for(var i = 0; i < ajax_request.headers.length; i+=2){
                  this.browser_obj.setRequestHeader(ajax_request.headers[i], ajax_request.headers[i + 1]);
               }
            }
            
            this.browser_obj.send(ajax_request.body);
            
            // reset instance vars
            ajax_request.start_time = (new Date()).valueOf();
            ajax_request.timedout = false;
            ajax_request.timeouttimer = window.setTimeout(this.timeoutHandler, this.TimeoutSecs * 1000);
            
            // Hook into google analytics
            if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Request'); }
         }
      }else{
         // Error  - invalid browser object
         if(typeof(ajax_request.onErrorCB) == 'function'){ ajax_request.onErrorCB(ajax_request, "invalid browser object"); }
         
         // Hook into google analytics
         if(pageTracker){ pageTracker._trackEvent('AJAX', ajax_request.url, 'Invalid Object'); }
      }
   }
   
   
   // Creates the browser object
   this.browser_obj = this.createBrowserObj();
}


/******************************************************************************/
/*var myAJAXParams = {
   method: "POST",
   url: "php/dynamic.xml.php",
   onload: function myLoad(ajax){ alert("my callback:" + ajax.response.Text); },
   ontimeout: function myTimout(ajax){ alert("my callback:" + "Timeout"); },
   onerror: function myError(ajax, infostr){ alert("my callback:" + infostr); },
   timeout_secs: 3,
   headers: [
      "X-Foo", "Bar",
   ],
}

function testit(){
   
   (new AJAXRequest()).request(myAJAXParams);
}
*/





