/*
	Project:   AJAX Class
	Developer: Dave Smith
	Date:      09/04/2008
	Version    1.02

	© 2008 Dave Smith
*/

// JavaScript AJAX class

function AJAX(name) {
   this._xmlHttpReq = this.getXMLHttpReqObject();
   this._name = name;
   this._requestTimerId = null;
   this._requestPending = false;
}

AJAX.prototype._name;

AJAX.prototype.getName = function() {
   return this._name;
}

AJAX.prototype.getXMLHttpReqObject = function() {
   var myXMLHttpReq = null;
   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      myXMLHttpReq = new XMLHttpRequest();
      if (myXMLHttpReq.overrideMimeType) {
         myXMLHttpReq.overrideMimeType('text/xml');
      }
   } else if (window.ActiveXObject) { // IE
      try {
          myXMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
      }
      catch (e) {
         try {
            myXMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
         }
         catch (e) {}
      }
   }
   return myXMLHttpReq;
}

AJAX.prototype.abort = function() {
   if (this._xmlHttpReq != null)
      this._xmlHttpReq.abort();
	clearTimeout(this._requestTimerId);
   this._requestPending = false;
}

AJAX.prototype.sendData = function(urlstring, func, timeoutMS) {
   if (this._xmlHttpReq == null) {
      alert ("Browser does not support HTTP Request");
   }
   else {
      var url = urlstring;
      var thisObj = this;
      if (!this._requestPending) {
      	this._requestPending = true;
         this._requestTimerId = setTimeout(function() { thisObj.requestTimeout(func); }, timeoutMS)
         this._xmlHttpReq.open("GET", url, true);
         this._xmlHttpReq.onreadystatechange = function() { thisObj.sendData_Response(this._xmlHttpReq, func); };
         this._xmlHttpReq.send(null);
      }
   }
}

AJAX.prototype.sendData_Response = function(xmlHttpReq, func) {
   if (this._xmlHttpReq != null) {
      if (this._xmlHttpReq.readyState==4) {
         try {
            if (this._xmlHttpReq.status==200) {
               func(this._xmlHttpReq.responseText, this._xmlHttpReq.status);
               clearTimeout(this._requestTimerId);
               this._requestPending = false;
            } else {
            	this.requestTimeout(func);
            }
         }
         catch(e) {
         }
      }
   }
}

AJAX.prototype.requestTimeout = function(func) {
	if (this._xmlHttpReq != null)
		this._xmlHttpReq.abort();
   clearTimeout(this._requestTimerId);
   func("Timeout", 9999);
   this._requestPending = false;
}
