// JavaScript Document
//Cria objeto XMLHttpRequest ou ActivX
//Testado em IE 6 e Firefox 1.5
//28/09/2006
function cria_ajax(){
   //verifica se o browser tem suporte a ajax e cria o objeto caso tenha
   try{
      var ajax = new ActiveXObject("Microsoft.XMLHTTP");
   }
   catch(e){
      try{
         var ajax = new ActiveXObject("Msxml2.XMLHTTP");
      }
	  catch(ex){
         try{
            var ajax = new XMLHttpRequest();
         }
	     catch(exc){
            alert("Esse browser não tem recursos para uso do Ajax");
            var ajax = null;
         }
      }
   }
   return ajax;
}

//Envia request e passa resultado para função informada
//Testado em IE 6 e Firefox 1.5
//28/09/2006
function envia_http_request(url,variaveis,metodo,funcao){
	//Tenta criar o objeto ajax
	var ajax = cria_ajax();

	if(ajax){
		//Configura método de envio para url  e transmissão como assíncrono
		ajax.open(metodo, url , true);
		//Muda cabeçalho para utilizar UTF-8 resolvendo problema com caracteres especiais
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		//Espécie de protótipo que retorna estados do envio
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 4 ){
	            if(funcao != '' && funcao != undefined){
					//Testando erro
					if(ajax.responseText.indexOf('<html>') != -1){
						alert(ajax.responseText);
					}
					else{
						try{
							//Removendo quebras de linha do código
							var retorno = ajax.responseText;
							retorno = retorno.replace(/[\n\r]/g, '');
							try{
   								eval(funcao + '(\'' + retorno + '\')');
							}catch(e){
								alert("Falha na interpretação das informações do banco de dados. Tente novamente mais tarde!\n\nDesculpe-nos o transtorno.");
								show_hide_processando();
							}
						}catch(erro){
							var conteudo_janela = "Falha na interpretação do retorno do banco de dados:\n\n" + ajax.responseText;
							open_popup('..::SERVCOM - Falha no sistema::..', 'Janela ERRO', conteudo_janela, 450, 250, 'fecha_janela_popup', 'html');
						}
					}
            	}
			}
		}	
		//Envia o post para o servidor
		ajax.send(variaveis);
	}
}

//Converte objeto XML em array
//forma de acessar atributos: meu_array['nome_no']['nome_atributo']
//forma de acessar valores: meu_array['nome_no']['value']
//Testado em IE 6 e Firefox 1.5
//28/09/2006
function xml2array(xml_text){
   //Array que retornará todos os valores
   var retorno = new Array();
   var temp = new Array();
	xml_text = remove_empty_tag(xml_text);

   xml_doc = string2xml(xml_text);

   //Pega o nó root do documento
   var root = xml_doc.documentElement;

   //Guarda atributos do nó
   if(root.attributes.length > 0){
      for(var i=0; i < root.firstChild.attributes.length; i++){
			if(root.attributes[i].value){
	         temp[root.attributes[i].name] = root.attributes[i].value;
			}else{
				temp[root.attributes[i].name] = '';
			}
      }
   }

   //Seta valor do elemento
	var node_value = root.firstChild.nodeValue;
	if(node_value=="$empty$"){
		temp['value'] = "";
	}else{
		temp['value'] = root.firstChild.nodeValue;
	}
   retorno[root.nodeName] = temp;
	
   //Retorna os valores dos nós filhos
   for(var i = 0; i < root.childNodes.length; i++){
      retorno = pega_filhos(root.childNodes[i],retorno);
   }
   return retorno;
}

//Retorna atributos e valores dos nós filhos de um XML
//Testado em IE 6 e Firefox 1.5
//28/09/2006
function pega_filhos(xml_element, array_retorno){
   var temp = new Array();
   //Testa se o o elemento é do tipo 1
   if(xml_element.nodeType == 1){
      //Guarda atributos do nó no array temporário temp
      if(xml_element.attributes.length > 0){
         for(var i=0; i < xml_element.attributes.length; i++){
				if(xml_element.attributes[i].value){
	            temp[xml_element.attributes[i].name] = xml_element.attributes[i].value;
				}else{
					temp[xml_element.attributes[i].name] = '';
				}
         }
      }
      //Seta valor do elemento
		var node_value = xml_element.firstChild.nodeValue;
		if(node_value=="$empty$"){
			temp['value'] = "";
		}else{
			temp['value'] = xml_element.firstChild.nodeValue;	
		}
      array_retorno[xml_element.nodeName] = temp;
   }
   return array_retorno;
}

//Converte string em um objeto xml
//Testado em IE 6 e Firefox 1.5
//28/09/2006
function string2xml(xml) {
   //Testa a existência de activex, isto é, se é o Internet Explorer
   if (typeof ActiveXObject != 'undefined') {
     //Cria objeto activex
	  var dom = new ActiveXObject("Microsoft.XMLDOM");
	  dom.preserveWhiteSpace = false;
	  dom.async = false;   //assincrono igual a falso
	  dom.loadXML(xml);   //converte string em xml
	}
	else {
     //cria objeto parser
	  parser = new DOMParser();
     //converte string em xml
	  dom = parser.parseFromString(xml, "text/xml");
	}
	return dom;
}

function remove_empty_tag(xml_text){
	var resultado = xml_text.replace(/<([^\/>]*)>[\s]*<\//g,'<$1>$empty$</');
	return resultado;
}
