﻿// Ajax Object calls the passed method when the data returns
// Other javascript objects can inherit from this one in
// order to become Ajax enabled

function AjaxObject(url,onajaxload,onerror,method,params,contentType)
{
  this.url = url;
  this.httpreq=null;
  this.onajaxload=onajaxload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  this.loadXMLDoc(url,method,params,contentType);
  this.parameter = null;
}

AjaxObject.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.httpreq.readyState
    +"\nstatus: "+this.httpreq.status
    +"\nheaders: "+this.httpreq.getAllResponseHeaders());
}

AjaxObject.prototype.loadXMLDoc=function(url,method,params,contentType){
  if (!url)
    return;
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XMLHttpRequest){
    this.httpreq=new XMLHttpRequest();
  } else if (window.ActiveXObject){
    this.httpreq=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (this.httpreq){
    try{
      var loader=this;
      this.httpreq.onreadystatechange=function(){
        //By using call this is set to loader in onReadyState
        loader.onReadyState.call(loader);
      }
      this.httpreq.open(method,url,true);
      if (contentType){
        this.httpreq.setRequestHeader('Content-Type', contentType);
      }
      this.httpreq.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}

AjaxObject.prototype.onReadyState=function(){
  var req=this.httpreq;
  var ready=req.readyState;
  if (ready==4){
    var httpStatus=req.status;
      if (httpStatus==200 || httpStatus==411 || httpStatus==0){
        this.onajaxload.call(this);
      }
      else {
        this.onerror.call(this);
      }
  }
}
