/*
  AJax Controller
*/

var ajaxControl = new Array();
ajaxControl.Handler = function(url, method, target, callback) {
  this.url = url;
  this.method = "POST";
  if (method != null) {
    this.method = method;
  }
  this.target = null;
  if (target != null) {
    this.target = xgetElementById(target);
  }
  this.callback = null;
  if (callback != null) {
    this.callback = callback;
  }
}

ajaxControl.Handler.prototype.sendRequest = function(params) {
  var target = this.target;
  var callback = this.callback;
  var url = this.url;
  var method = this.method;

  var xmlHttp = this.createXMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
     if (xmlHttp.readyState == 4) {
        try {
           if (xmlHttp.status == 200) {
              var text = xmlHttp.responseText;
              var xml = xmlHttp.responseXML;
              if (target != null) {target.innerHTML = text;
                 target.style.visibility = 'visible';
              }
              if (callback != null) {
                callback.call(this, text, xml);
              }
           }
           else {
              var text = xmlHttp.statusText;
              //alert(text);
              if (target != null) {
                 target.innerHTML = text;
                 target.style.visibility = 'visible';
              }
              if (callback != null) {
                callback.call(this, text, xml);
              }
           }
        }
        catch (e) {
           //alert(e);
        }
     }
  }

  try {
     xmlHttp.open(method, url, true);
     xmlHttp.send(params);
  }
  catch(e) {
     alert(e + ": " + this.url);
  }
}

ajaxControl.Handler.prototype.createXMLHttpRequest = function () {
  var xmlHttp = null;
  if (window.ActiveXObject) {
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }
  return xmlHttp;
}

function addAjaxHandler(url, method, target) {
   var handler = new ajaxControl.Handler(url, method, target);
   handler.sendRequest();
   return handler;
}

function addAjaxCallback(url, method, callback) {
   var handler = new ajaxControl.Handler(url, method, null, callback);
   handler.sendRequest();
   return handler;
}

/*
  function to display a new page using ajax
*/
function displayAjaxPage(uri, method, target) {
   var handler = addAjaxHandler(uri, method, target)
   return false;
}

