/**
 * Dateiname       : javascript/AjaxHandler.js
 * Erzeugungsdatum : 12.12.2007
 * Autor           : Carsten Kube
 * Version         : 1.1
 * Letzte Akt.     : 28.02.2008 (CK)
 * 
 * (c) Copyright SECRA GmbH
 */

var secra;
if(!secra)
{
  secra = {};
}
else if(typeof secra != "object")
{
  throw new Error("secra ist kein Objekt!");
}

if(secra.AjaxHandler)
{
  throw new Error("secra.AjaxHandler existiert bereits!");
}


secra.AjaxHandler = function(name){
  this.x = null;
  this.method = "";
  this.url = "";
  this.body = null;
  this.name = name;
  this.async = true;
  this.json = false;

  if (window.XMLHttpRequest) {
    try {
      this.x = new XMLHttpRequest();
      this.name += " XMLHttpRequest";
    } catch (e) { }
  } else if (window.ActiveXObject) {
    try {
      this.x = new ActiveXObject("Msxml2.XMLHTTP");
      this.name += " ActiveXObject";
    } catch (e) {
      try {
        this.x = new ActiveXObject("Microsoft.XMLHTTP");
        this.name += " ActiveXObject";
      } catch (e) { }
    }
  }
  var thisObj = this;
  this.x.onreadystatechange = function() { thisObj.callback(); };
}

secra.AjaxHandler.prototype.open = function(method, url, async) {
  this.method = method;
  this.url = url;
  if(typeof async === "boolean")
  {
    this.async = async;
  }
  this.x.open(this.method, this.url, this.async);
};

secra.AjaxHandler.prototype.send = function(body) {
  if(this.method == "POST")
  {
    this.body = body;
  }
  this.x.send(this.body);
  if(!this.async)
  {
    if(typeof this.state4 == "function")
    {
      this.state4(this);
    }
  }
};

secra.AjaxHandler.prototype.registerCallback = function(p, returnType) {
  for(var key in p)
  {
    if(typeof p[key] == "function") this[key] = p[key];
  }
  if(returnType == "json") {
    this.json = true;
  }
};

secra.AjaxHandler.prototype.callback = function() {
  if(this.x.readyState == 0)
  {
    if(typeof this.state0 == "function")
    {
      this.state0(this);
    }
  }
  else if(this.x.readyState == 1)
  {
    if(typeof this.state1 == "function")
    {
      this.state1(this);
    }
  }
  else if(this.x.readyState == 2)
  {
    if(typeof this.state2 == "function")
    {
      this.state2(this);
    }
  }
  else if(this.x.readyState == 3)
  {
    if(typeof this.state3 == "function")
    {
      this.state3(this);
    }
  }
  else if(this.x.readyState == 4)
  {
    if(typeof this.state4 == "function")
    {
      this.state4(this);
    }
  }
};

secra.AjaxHandler.prototype.toString = function() {
  return "[XMLHttpObject " + this.name + "]";
};

secra.AjaxHandler.prototype.getText = function() {
  return this.x.responseText;
};
secra.AjaxHandler.prototype.getJSON = function() {
  return JSON.parse(this.x.responseText);
};

