// Objeto AJAX para comunicação Assincrona com um servidor de aplicações WEB
// AJAX(
//		  url =  Endereço que será chamado,
//		  metodo = GET ou POST,
//		  params = Parametros caso o metodo escolhido seja o POST,
//		  processa = Nome da função que será executada quando obtiver a resposta da pag.,
//		  modo = T (texto) ou X (xml)
//		  exibeMsg = true | false
//var ajaxCliente0 = new AJAX('resposta.asp?tp=nomes','GET',null,mostraNome,'T');
//var ajaxCliente1 = new AJAX('resposta.asp','POST','tp=nome',mostraNome,'T');
var timerErroAJAX;
function AJAX(url,metodo,params,processa,modo,escondeMsg) { // Definição da Classe AJAX
	this.url = url;
   this.metodo = (metodo) ? metodo : 'GET';
   this.params  = (metodo=='GET') ? null : params;
   this.processaresultado = processa; // Nome da função que será executada quando obtiver a resposta do site
   this.Header = new Array();
   this.modo = (modo) ? modo : 'T';
   if(this.modo!='T'&&this.modo!='X'&&this.modo!='R') {
      this.modo = 'T';
   }
	this.escondeMsg = (escondeMsg) ? escondeMsg : false;

	//////////////////////////////////////
	// Definindo a chamadas das funções //
	//////////////////////////////////////
	this.addHeader = addHeader;
	this.delHeader = delHeader;
	this.setHeader = setHeader;
	this.conectar = conectar;
	this.processaretorno = processaretorno;
	this.processaerro = processaerro;
		
	///////////////////////////////////////////////////
	// Forçando a execução do objeto logo na criação //
	///////////////////////////////////////////////////
   this.conectar(); 

	//////////////////////////////////////
	// Definindo metodos da Classe AJAX //
	//////////////////////////////////////
   function addHeader(h,v) {
		this.Header[h] = v;
	}
		
   function delHeader(h) {
		delete(this.Header[h]);
	}
		
   function setHeader() {
		if(this.httprequest==null) { 
			return;
		} 
		for(h in this.Header) {
			this.httprequest.setRequestHeader(h,this.Header[h]);
		}
	}
		
   function conectar() {
		/////////////////////////////////////
		// Gerando mensagem de processando //
		/////////////////////////////////////
		if(timerErroAJAX){
			clearTimeout(timerErroAJAX);
		}		
		if (this.escondeMsg == false){
			if (document.getElementById("dvXmlHTTP") == null){
				objDiv = document.createElement("div");
				objDiv.id = 'dvXmlHTTP';
				
				objDiv.style.position = 'absolute';
				objDiv.style.display = 'none';
				objDiv.style.zIndex = '999';
				objDiv.style.color = '#FF0000';
				objDiv.style.padding = '2px';
				objDiv.style.margin = '2px';
				objDiv.style.border = 'solid 1px #666666';
				
				objDiv.style.backgroundColor = '#FFFFFF';
				objDiv.style.fontWeight = 700;
				
				objDiv.innerHTML = '<img src="/_smi/admin/imagens/loading.gif" width="13" height="13"> Processando...';
			
				document.body.insertBefore(objDiv, document.body.firstChild);
			}else{
				objDiv = document.getElementById("dvXmlHTTP");
				objDiv.innerHTML = '<img src="/_smi/admin/imagens/loading.gif" width="13" height="13"> Processando...';
			}
			objDiv.style.display = '';
		}
				
		///////////////////////////////////////////////
		// Verifica se existe alguma URL para chamar //
		///////////////////////////////////////////////
		if(this.url==undefined||this.url=='') {
			return; 
		}
				
		//////////////////////////////
		// Criando o objeto XMLHTTP //
		//////////////////////////////
		this.httprequest = null; // Setando um valor inicial
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			this.httprequest = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE
			try {
				this.httprequest = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
				  this.httprequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
				}
			}
		}
		
		/////////////////////////////////////////////////////////////
		// Verificando se o objeto XMLHTTP foi criado corretamente //
		/////////////////////////////////////////////////////////////
		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';
			}
			
			var url = this.url;
			
			if (this.metodo == 'POST'){
				this.addHeader('Content-Type',"application/x-www-form-urlencoded; charset=iso-8859-1");
				this.addHeader("Cache-Control","no-store, no-cache, must-revalidate");
				this.addHeader("Cache-Control","post-check=0, pre-check=0");
				this.addHeader("Pragma", "no-cache");	
			}else{
				var rnd = Math.random();
				url += (this.url.indexOf('?')!= -1) ? '&rnd='+rnd : '?rnd='+rnd;
			}
			
			this.httprequest.open(this.metodo, url, true);
									
			this.setHeader();
			
			this.httprequest.send(this.params);
			
		}else{
			alert('Seu navegador é incompatível com este site.');	
		}
	}
		
   function processaretorno() {
		if(this.httprequest.readyState==4) {// Terminou a execução da página
			if (this.escondeMsg == false){
				document.getElementById('dvXmlHTTP').style.display = 'none';
			}
			if(this.httprequest.status==200) { // A pag. foi executada corretamente
				var resp;
				
				if (this.modo=='T'){ // Verificando se a resposta tem que ser enviada com texto ou xml
					resp = this.httprequest.responseText;
				}else if(this.modo=='R'){ // Verificando se a resposta tem que ser enviada como recordset
					resp = new XMLtoRS(this.httprequest.responseXML);
				}else{ // Verificando se a resposta tem que ser enviada como XML
					resp = this.httprequest.responseXML;
				}
				
				if(this.processaresultado!=null) {
					this.processaresultado(resp);
				} else {
					document.write(resp);
				}
			} else { // A pag. NÂO foi executada corretamente
				this.processaerro();
			}
		}
	}
		
   function processaerro() { // Mostrando erro
		objDiv = document.getElementById("dvXmlHTTP")
		if (objDiv){
			objDiv.innerHTML = 'Erro processando a requisição';
			objDiv.style.display = '';
			timerErroAJAX = setTimeout("objDiv.style.display = 'none'", 3000);
		}
		//alert('Erro processando a requisição.');
		//alert('Erro processando a requisição \n' + this.httprequest.status + '-' + this.httprequest.statusText + ' :-> ' + this.url);
	}
}


/////////////////////////////////
// Função de tratamento do XML //
/////////////////////////////////
function XMLtoRS(xmlDOC){
	//this.linhas = xmlDOC.childNodes[1].childNodes;
	this.linhas = xmlDOC.getElementsByTagName('root')[0].childNodes;
		
	////////////////////////
	// Declarando funções //
	////////////////////////
	this.get = get;
	this.moveNext = moveNext;	
	this.movePrevious = movePrevious;
	this.moveFirst = moveFirst;
	
	//////////////////////
	// Inicializando RS //
	//////////////////////
	this.moveFirst()
	
	///////////////////////
	// Corpo das funções //
	///////////////////////
	function moveNext(){
		this.linhaAtual++;
		
		if (this.linhaAtual >= this.linhas.length) {
			this.linhaAtual--;
			this.eof = true;
		}else{
			this.eof = false;
		}
	}
	
	function movePrevious(){
		this.linhaAtual--;
		
		if (this.linhaAtual < 0) {
			this.linhaAtual++;
		}
		
		if (this.linhaAtual >= this.linhas.length) {
			this.eof = true;
		}else{
			this.eof = false;
		}
	}
	
	function moveFirst(){
		this.linhaAtual = 0;
		this.eof = (this.linhas.length == 0) ? true : false;
	}
	
	function get(cmp){
		if (!this.eof){
			//alert(this.linhas[this.linhaAtual].childNodes[0].firstChild.nodeValue);
			if (this.linhas[this.linhaAtual].getElementsByTagName(cmp)[0].firstChild){
				return this.linhas[this.linhaAtual].getElementsByTagName(cmp)[0].firstChild.nodeValue;
			}else{
				return '';	
			}
			//alert(this.linhas[this.linhaAtual].getElementsByTagName(cmp).firstChild.nodeValue);
		}
	}
}