var UOLLib = window.UOLLib || {}
/** 
 * @projectDescription Efetua requisições utilizando os metodos padrões XMLHttpRequest ou ActiveXObject("Microsoft.XMLHTTP")
 *
 * @author  Roberto Robson (Bode) rnogueira@uolinc.com
 * @version 1.2
 * @since   1.0
 */

UOLLib.ajax = function(){
  /**
   * Objeto XMLHttpRequest
   * @type {Object}
   */
  this.request;
  this.callback;
  var obj = this;
  
  /**
   * Verifica qual Objeto esta diponivel para a instancia XMLHttpRequest ou ActiveXObject("Microsoft.XMLHTTP")
   * @type {Method}
   */
  var setRequestObject = function(){
    if (window.XMLHttpRequest) 
      obj.request = new XMLHttpRequest();
    else 
      if (window.ActiveXObject) 
        obj.request = new ActiveXObject("Microsoft.XMLHTTP");
  }

  /**
   * Faz requisição em um endereço (URL) especifico
   * @type {Method}
   * @param {Json} Json {
   *      method : String (Optional), Metodo utilizado na requisição: GET OU POST. padrão "GET"
   *      url : String, URL da requisição que deve estar no mesmo dominio
   *      async : Boolean, (Optional) Ativar ou não o async do XMLHttpRequest, padrão "true"
   *      callback : Function (Optional), Função a ser executado no final do request
   *      hit : String (Optional), Caso tenha a necessidade de efetuar uma requisição 
   *                               de um arquivo normalmente HTML para a contabilização de audiencia
   *
   * }
   */
  this.open = function(){
    setRequestObject();
    this.params=arguments[0];
    this.method = this.params['method'] || "GET";
    this.url = this.params['url'];
    this.async = typeof this.params['async'] != 'undefined' ? this.params['async'] : false || true;
    this.hit = this.params['hit'] || '';
    this.callback = this.params['callback'] || false;

    if (obj.request) {
  		obj.request.onreadystatechange = function(){
        if (obj.request.readyState == 4) 
          if (obj.request.status == 200)
            if (typeof(obj.callback) == "function"){
              obj.callback();
              if(obj.hit!='')
                obj.requestHit();
            }
      }

      this.request.open(this.method, this.url, this.async);
      this.request.send(null);
    }
  }
  
  this.requestHit = function(){
    var id="uollibAjaxHit";
    var gE=document.getElementById(id);
    var ts = new Date();
    ts = ts.getTime();
    var HTML;
    if(gE)
      gE.parentNode.removeChild(gE);
    
    HTML=document.createElement('div');
    HTML.id=id;
    HTML.innerHTML="<iframe src=\""+this.hit+"\" name=\""+id+ts+"\" style=\"width:1px;height:1px;position:absolute;top:-1000px;left:-1000px\"></iframe>";
    document.getElementsByTagName('body')[0].insertBefore(HTML,document.getElementsByTagName('body')[0].firstChild);
  }
  
}
