/* **************************************************************
*                         --XJS--	                            *
* Desenvolvedora: Rhianna Cantarelli							*
* Versão: 1.5													*
* Data: 17.05.2007												*
* Email: r.rhianna@yahoo.com.br									*
************************************************************** */







/* **************************************************************
Engine das Requisições Assincronas (Ajax)
Métodos do Objeto XMLHTTP:
	- Faz Requisição de Documento
	obj.open("GET ou POST", "URL "[, sinaldesincronização[, "nomeUsuário"[, "senha"]]]);
	- Faz Envio de Parametros de Comunicação
	obj.send(null);

Existem 2 formas de tratar o retorno de uma requisição:
	obj.responseXML  <-- Retorna um Objeto XML Navegavel por DOM
	obj.responseText <-- Retorna todo o documento em formato String

Resgatando Estado da Comunicação
State = obj.readyState;
	0 - Não iniciado (Uninitialised)
	1 - Carregando (Loading)
	2 - Carregado (Loaded)
	3 - Interativo (Interactive)
	4 - Completado (Completed)

Resultado da Requisição:
Result = obj.status;
	404 - não encontrado
	200 - ok.

O Método transforma caracteres especiais em formato compativel com URL
escape(param);

Quando estiver sendo usado uma linguagem de Servidor, no documento que será entregue
o conteudo real que será entregue deve estar dentro das Tags:
<getThis> e </getThis>




************************************************************** */
var RequestConfig = new objXmlHttpRequestConfig();
var XmlHttp = new objXmlHttpRequest(RequestConfig);





/* **************************************************************
Cria Objeto que Carrega Configurações que serão usadas nas
requisições assincronas
************************************************************** */
function objXmlHttpRequestConfig() {
	this.method = 'POST'; // Pode ser GET ou POST
	this.isDOM = false; // Define retorno como um documento XML ou uma String
	this.isProtected = false; // Se 'true', usará credenciais
	this.login = '';
	this.password = '';

	// Altera Configurações Básicas 
	this.setConfig = function(met, isXml, isProt, user, senha) {
		this.method = met;
		this.isDOM = isXml;
		this.isProtected = isProt;
		this.login = user;
		this.password = senha;
	};
	this.setMethod = function(value) { this.method = value; };
	this.setIsDOM = function(value) { this.isDOM = value; };
	this.setIsProtected = function(value) { this.isProtected = value; };
	this.setLogin = function(value) { this.login = value; };
	this.setPassword = function(value) { this.password = value; };

	this.arrayState = new Array();
	this.arrayIsExec = new Array();
	this.setState = function(n, value, isExec) { 
	    this.arrayState[n] = value; 
	    this.arrayIsExec[n] = isExec;
	};
	this.clearArrayState = function() { this.arrayState = new Array(4); };
}



/* **************************************************************
Cria Objeto que faz as requisições assincronas baseado nas informações
que foram configuradas num objeto do tipo objXmlHttpRequestConfig()
************************************************************** */
function objXmlHttpRequest(objConfig) {
	// Cria Objeto de Requisição Assincrona
	var objXmlHttp;
	this.XmlReturn = null;
	
	try {objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");}
	catch (e) {
		try { objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (E) { objXmlHttp = false; } 
	} 
	if (!objXmlHttp && typeof  XMLHttpRequest != 'undefined' ) {
		try { objXmlHttp = new  XMLHttpRequest(); }
		catch (e) { objXmlHttp = false; } 
	}


	var idTarget = '';


	// Faz Requisição conforme Configurações
	this.LoadPage = function(url, param, idTar) {
		idTarget = idTar;


		// Define Ação para Mudanças de Estado
		objXmlHttp.onreadystatechange = this.XmlHttpRequestChangeState;

		// Se for um documento Protejido
		if(objConfig.isProtected == true) {
			objXmlHttp.open(objConfig.method, url, true, objConfig.login, objConfig.password);
		}
		// Se for um documento sem proteção
		else { objXmlHttp.open(objConfig.method, url, true); }

		objXmlHttp.setRequestHeader('Content-Type','text/xml');
		objXmlHttp.setRequestHeader('encoding','ISO-8859-1');


		if(objConfig.method == "POST") {
			objXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			objXmlHttp.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
            objXmlHttp.setRequestHeader('Cache-Control', 'post-check=0, pre-check=0');
            objXmlHttp.setRequestHeader('Pragma', 'no-cache');
		}

		if(param == '') { param = null; } // para GET ou POST sem Parametros
		else { param = this.encodeParam(param); } // para POST
		objXmlHttp.send(param);
	};

    // Faz Tratamento de Parametros
	this.encodeParam = function(p) {
		splita = p.split('&');
		finalParam = '';

		for(i=0; i<splita.length; i++) {
	        iIni = splita[i].indexOf('=') + 1;
	        value = splita[i].substring(iIni, splita[i].length);
	        encValue = escape(value);
	        finalParam += splita[i].replace(value, encValue);
	        if(splita.length > 1 && i < (splita.length - 1)) { finalParam += '&'; }
		}
		return finalParam;
	};

	// Faz o Controle das Mudanças no Estado
	this.XmlHttpRequestChangeState = function() {
		intState = objXmlHttp.readyState;
		strState = objConfig.arrayState[intState];
		isExec = objConfig.arrayIsExec[intState];
		intStatus = '';
		
		if(intState == 4) { 
			intStatus = objXmlHttp.status; 
			if(strState == undefined || strState == '') {strState = 'open';}
		}
	

		// Se há Ação Definida para este estado
		if(strState != undefined && strState != '') {
			// Se for apenas um Alert, executa-o
			if(idTarget == 'alert') { 
				if(intState != 4) { alert(strState); }
				else {
					if(intStatus == 200) { alert(objXmlHttp.responseText+''); }
					else { alert('Erro n: ' + intStatus); }
			} }
			else {
				// Para todos os estados diferentes de 4
				if(intState != 4) { }
				else if(intState == 4) {
					// Se for para retornar um objeto DOM
					if(objConfig.isDOM == true) {
						if (intStatus == 200) { return objXmlHttp.responseXML; }
						else { return false; }
					}
					// Se for para retornar uma string
					else if(objConfig.isDOM == false) {
						if (intStatus == 200) { 
						    if(document.getElementById(idTarget)){
						        thisHTML = objXmlHttp.responseText + '';
						        intINI = thisHTML.indexOf('<getThis>') + 9;
						        intEND = thisHTML.indexOf('</getThis>');
						        thisHTML = thisHTML.substring(intINI, intEND);
							    document.getElementById(idTarget).innerHTML = thisHTML;
							}
							if(isExec == true) { eval(strState); }
						}
						else { document.getElementById(idTarget).innerHTML = 'Erro : ' + intStatus; }
					}
				}
	        }
        }
    };
}