var cuentaAtrasAjax = null;
var tiempoEsperaAjax = 5000;
var reintentosAjax = 0;
var reintentosAjaxMaximos = 3;

var ajax = new Object();

ajax.READY_STATE_UNINITIALIZED=0;
ajax.READY_STATE_LOADING=1;
ajax.READY_STATE_LOADED=2;
ajax.READY_STATE_INTERACTIVE=3;
ajax.READY_STATE_COMPLETE=4;

//constructor
ajax.cargar = function(metodo, url, parametros, funcion, funcionError)
{
   this.url = url;
   this.req = null;
   this.onload = funcion;
   this.onerror = (funcionError) ? funcionError : this.defaultError;
   this.cargaContenidoXML(metodo, url, parametros);
}

ajax.cargar.prototype = {
   cargaContenidoXML: function(metodo, url, parametros)
   {
      if (window.XMLHttpRequest) this.req = new XMLHttpRequest();
      else if (window.ActiveXObject) this.req = new ActiveXObject("Microsoft.XMLHTTP");

      if (this.req)
      {
         try
         {
            var loader = this;
            clearTimeout(cuentaAtrasAjax);
            cuentaAtrasAjax = setTimeout("expiraAjax()", tiempoEsperaAjax);
            this.req.onreadystatechange = function()
            {
               loader.onReadyState.call(loader);
            }
            this.req.open(metodo, url, true);
            if (metodo == "POST") this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            this.req.send(parametros);
         }
         catch(err)
         {
            this.onerror.call(this);
         }
      }
   },

   onReadyState: function()
   {
      var req = this.req;
      var ready = req.readyState;
      if (ready == ajax.READY_STATE_COMPLETE)
      {
         var httpStatus = req.status;
         if (httpStatus == 200 || httpStatus == 0) this.onload.call(this);
         else this.onerror.call(this);
         clearTimeout(cuentaAtrasAjax);
         reintentosAjax = 0;
      }
   },

   defaultError: function()
   {
      alert("Se ha producido un error al obtener los datos"
      + "\n\nreadyState:" + this.req.readyState
      + "\nstatus: " + this.req.status
      + "\nheaders: " + this.req.getAllResponseHeaders());
   },

   expiraAjax: function()
   {
      reintentosAjax++;
      if (reintentosAjax > reintentosAjaxMaximos)
      {
         reintentosAjax = 0;
         alert("Ha ocurrido un error interno en el servidor. Inténtelo más tarde.");
      }
      else
      {
         this.req.abort();
         this.cargaContenidoXML(this.metodo, this.url, this.parametros);
      }
   }
}