var AJAX_DEBUG = false;

// AJAX Helper object
function AJAXHelper(){
  // Private variables
  var AJAX_NULL = 0;
  var AJAX_SETUP = 1;
  var AJAX_SENT = 2;
  var AJAX_WORKING = 3;
  var AJAX_COMPLETE = 4;
  var rscPointer = null;
  var _req;
  
  // Public variables
  this.req = null;
  
  
  // Private methods
  function buildAjax(){
    // Abort the current AJAX request
    // as IE never closes it's connections
    if (_req){
      _req.abort();
      return true;
    }else{
      // Create the AJAX object
      try{
        // For real browsers & possibly IE7
        _req = new XMLHttpRequest();
      }catch (e){
        // For IE6
        try{
          _req = new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
          // For IE5
          try{
            _req = new ActiveXObject("Microsoft.XMLHTTP");
          }catch (ex){
            // AJAX isn't supported
            if (AJAX_DEBUG){
              alert('AJAX doesn\'t appear to be supported:\n' + ex.message);
            }
            return false;
          }
        }
      }
    }
    
    return true;
  }
  
  function _req_ReadyStateChanged(){
    // This handled the AJAX ReadyStateChanged event
    // and calls the function passing the AJAX request back
    try{
      if (_req.readyState == AJAX_COMPLETE){
        rscPointer(_req);
      }
    }catch(ex){
      if (AJAX_DEBUG){
        alert('An error occured:\n' + ex.message);
      }
    }
  }


  // Public Methods
  this.setReadyStateChanged = function(funcPointer){
    // Sets the ReadyStateChanged callback method 
    rscPointer = funcPointer;
    
    // Abort the existing request, For IE
    _req.abort();
    _req.onreadystatechange = _req_ReadyStateChanged;
  }
  
  this.send = function(method, uri, aSync, data){
    // Append Random Querystring to avoid caching
    var re = /\?[a-z0-9]+/i; // Test for existing Querystring
    uri += (re.test(uri) ? '&' : '?') + 'antiCache=' +
      parseInt(Math.random() * Math.pow(2, 31));
  
    _req.open(method, uri, aSync);
    // Set the headers if posting
    if (method == 'POST'){
      _req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
      _req.setRequestHeader('Content-length', data.length);
      _req.setRequestHeader('Connection', 'close');
    }
    
    // Send the headers
    _req.send(data);
  }
  
  // Build the AJAX object
  buildAjax();
  this.req = _req;
  
  return this;
}
