/*==============================================================================================
--| Objeto AJAX para comunicação Assincrona com um servidor de aplicações WEB
==============================================================================================*/
function versoesMSXMLHttp(){
	var versoes = [ "MSXML2.XMLHttp.6.0" , "MSXML2.XMLHttp.5.0" , "MSXML2.XMLHttp.4.0" , "MSXML2.XMLHttp.3.0" , "MSXML2.XMLHttp" , "Microsoft.XMLHttp" ];
	
	for (var i=0; i<versoes.length; i++){
		try{
			var objetoXMLHttp = new ActiveXObject(versoes[i]);
			return objetoXMLHttp;
		} catch (ex){	}
	}
	return false;
}

function AJAX(url, metodo, params, processa, modo) {
	this.url = url;
	this.metodo = (metodo) ? metodo : 'GET';
	this.params  = (metodo='GET') ? "" : params;
	this.retorno = processa;
	this.modo = (modo) ? modo : 'T';
	if (this.modo != 'T' && this.modo != 'X') { this.modo = 'T'; }
	this.conectar();
}

AJAX.prototype = {
	
	// Instancia o objeto e faz a chamada a assincrona
	conectar: function() {
		if (this.url == undefined || this.url == '') {
			return; 
		}
		this.httprequest = null;
	   	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	     	this.httprequest = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE
			// TESTE DE VARIAS VERSOES DO IE
	     	this.httprequest = versoesMSXMLHttp();
		}
		if (this.httprequest != null && this.httprequest != undefined) {
			var obj = this;
			this.httprequest.onreadystatechange = function() {
				obj.processaRetorno.call(obj);
			}
			if (this.metodo == undefined || this.metodo == '') { this.metodo = 'GET';}
	    	this.httprequest.open(this.metodo, this.url, true);
			
			// Cabeçalho pra evitar CACHE
			this.httprequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
			this.httprequest.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			this.httprequest.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
			this.httprequest.setRequestHeader("Pragma", "no-cache");
			
	        this.httprequest.send(this.params);
		}
	},
	
	// Processa o retorno
	processaRetorno: function() {
		if (this.httprequest.readyState == 4) {
			if (this.httprequest.status == 200) {
				var resp = (this.modo == 'T') ? this.httprequest.responseText : this.httprequest.responseXML;
				if (this.retorno != null) {					
					// Trata os caracteres acentuados no ASP
					if (this.modo == 'T') {
						resp = resp.replace(/\+/g," ");
						resp = unescape(resp); 
					}					
					this.retorno(resp);
				} else {
					document.write(resp);
				}
			} else { 
				this.processaErro();
			}
		}
	},

	// Exibe um alert() com a descrição do ERRO
	processaErro: function() {
		alert(this.httprequest.status + '-' + this.httprequest.statusText + ' :-> ' + this.url);
	}
}

/*==============================================================================================
--| Executa qualquer <script></script> que existir na página
==============================================================================================*/
function executaScript(texto){
    // inicializa o inicio ><
    var ini = 0;
    // loop enquanto achar um script
    while (ini!=-1){
        // procura uma tag de script
        ini = texto.indexOf('<script', ini);
        // se encontrar
        if (ini >=0){
            // define o inicio para depois do fechamento dessa tag
            ini = texto.indexOf('>', ini) + 1;
            // procura o final do script
            var fim = texto.indexOf('</script>', ini);
            // extrai apenas o script
            codigo = texto.substring(ini,fim);
            // executa o script
            eval(codigo);
        }
    }
}
