﻿
  /**
   * ajax.js - Comunicação assíncrona com o servidor
   * ------- - -------------------------------------
   * @author Cau Guanabara <caugb@ibest.com.br>
   * @date 2006-04
   */

var _ajax = { handler: {}, idCounter: 0 };

function ajax(timeLimit, errorFunc) {
this.id = ++_ajax.idCounter;
_ajax.handler[this.id] = this;
this.timeout = timeLimit ? timeLimit : 0;
this.timeHand = null;
this.errorFunction = (errorFunc || null);
this.returnXML = false;
this.param = []; 
this.paramStr = ''; 
this.returnValue = null; 
this.status = ['inicializando','carregando...','carregado','interação','completo'];

  this.sendLoad = function(url, waitFunc, loadFunc, type) {
  this.loadFunction = (loadFunc || (this.loadFunction || function() {}));
  this.waitFunction = (waitFunc || (this.waitFunction || function() {}));
  type = /^post$/i.test(type) ? 'POST' : 'GET';
  this.req.onreadystatechange = new Function("_ajax.handler["+this.id+"].onChange();");
  this.req.open(type, url+((type == 'GET' && this.param.length > 0) ? '?'+this.paramStr : ''), true); 
    if(type == 'POST') this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    if(!document.all) // O Netscape não envia o HTTP_REFERER se a página não recarregar
      this.req.setRequestHeader('REFERER', window.location.href);
  this.req.send((type == 'POST' && this.param.length > 0) ? this.paramStr : null);
	  if(this.timeout > 0) 
		  this.timeHand = setTimeout("_ajax.handler["+this.id+"].interrupt();", this.timeout * 1000);
  };
  
  this.sendForm = function(frm, waitFunc, loadFunc) {
  this.loadFunction = (loadFunc || (this.loadFunction || function() {}));
  this.waitFunction = (waitFunc || (this.waitFunction || function() {}));
  var arr = [], str = '', act = frm.action, mtd = (frm.method || 'GET');
    if(!act) return false;
    for(i = 0; i < frm.elements.length; i++) { 
      if(frm.elements[i].name != '') { 
        if(/^radio|checkbox$/i.test(frm.elements[i].type) && frm.elements[i].checked == false) continue;
        if(!inArray(arr,frm.elements[i].name) || new RegExp('\\[\\]$').test(frm.elements[i].name)) {
        arr.push(frm.elements[i].name);
        arr.push(frm.elements[i].value);
        }
      } 
    } 
   
    if(arr.length > 0) str += "_ajax.handler["+this.id+"].setParams('"+arr.join("','")+"'); ";
  str += "_ajax.handler["+this.id+"].sendLoad('"+act+"',_ajax.handler["+this.id+"].waitFunction,"+
         "_ajax.handler["+this.id+"].loadFunction,'"+mtd+"');";
  new Function(str)();
  
    function inArray(arr, val) {
      for(var i = 0; i < arr.length; i++) if(arr[i] == val) return true; 
    return false;
    }
  };
  
  this.onChange = function() { 
  this.waitFunction(this.status[this.req.readyState]);
    if(this.req.readyState == 4) { 
		  if(this.timeHand != null) {
			clearTimeout(this.timeHand);
			this.timeHand = null;
			}
    var resp = this.returnXML ? 'responseXML' : 'responseText';
    this.returnValue = this.req.status == 200 ? this.req[resp] : this.req.status+' - '+this.req.statusText;
    this.loadFunction(this.returnValue);
    }
  };
  
  this.setParams = function() {
    if(!this.req || this.setParams.arguments.length < 2) return;
    for(var i = 0; i < this.setParams.arguments.length; i += 2) 
      if(typeof(this.setParams.arguments[i + 1]) != 'undefined') 
        this.param.push(this.setParams.arguments[i]+'='+escape(this.setParams.arguments[i + 1]));
  return this.paramStr = this.param.join('&');
  }; 
  
	this.interrupt = function() { 
	this.req.abort(); 
	  if(this.errorFunction != null) this.errorFunction();
	};
	
  this.makeXHR = function() {
    if(!window.XMLHttpRequest) {
      window.XMLHttpRequest = function() {
      var types = ['Microsoft.XMLHTTP','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'];
        for(var i = 0; i < types.length; i++) {
        var xhr = (new ActiveXObject(types[i]) || false);
          if(xhr) return xhr;
        }
      return false;
      };
    }
  };

this.makeXHR();
this.req = new XMLHttpRequest();
}
