// JavaScript Document
// 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, param){
	//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){

					funcao(ajax.responseText, param);
				}
			}
		}	
		//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ó
	temp = getNodesAttributes(root);
	
	//Busca o valor do nó	

	temp['_DATA'] = getNodeValue(root);

	retorno[root.nodeName] = temp;
	
	//Retorna os valores dos nós filhos
	retorno[root.nodeName]['_ELEMENTS'] = pega_filhos(root);

	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){
	var temp = new Array();
	var node_array = new Array();
	
	for(var i = 0; i < xml_element.childNodes.length; i++){
		if(xml_element.childNodes[i].nodeType == 1){
			//Guarda atributos do nó no array temporário temp
			temp = getNodesAttributes(xml_element.childNodes[i]);
			
			//Seta valor do elemento
			temp['_DATA'] = getNodeValue(xml_element.childNodes[i]);
			
			node_array[xml_element.childNodes[i].nodeName] = temp;

			if(xml_element.childNodes[i].childNodes){
				node_array[xml_element.childNodes[i].nodeName]['_ELEMENTS'] = pega_filhos(xml_element.childNodes[i]);
			}
		}
	}
	
	return node_array;
}

//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;
}

//Função auxiliar para a remoçao de tags vazias
function remove_empty_tag(xml_text){
	var resultado = xml_text.replace(/<([^\/>]*)>[\s]*<\//g,'<$1>$empty$</');
	return resultado;
}

//Função auxiliar que obtém todos os atributos de um nó
function getNodesAttributes(node){
	var temp = new Array();
	//Guarda atributos do nó
	if(node.attributes){
		for(var i=0; i < node.attributes.length; i++){			
			if(node.attributes[i].value){				
				temp[node.attributes[i].name] = node.attributes[i].value;
			}else{
				temp[node.attributes[i].name] = '';
			}
		}
	}	
	return temp;
}

function getNodeValue(node){
	if(node.firstChild){
		if(node.firstChild.nodeValue=='$empty$' || trim(node.firstChild.nodeValue)=='undefined'){
			return '';
		}
		else{
			return node.firstChild.nodeValue;
		}
	}
	else{
		return '';	
	}
}

//Função auxiliar para a correção de propriedades XML que contenham aspas
function converte_aspas(string){
	var test = string.indexOf('[aspas]');
	if(test!=-1){
		var padrao = /\[aspas\]/;
		var retorno = string.replace(padrao, '"');
	}
	else{
		var padrao = /"/;
		var retorno = string.replace(padrao, '[aspas]');
	}
	return retorno;
}

// Remove espaços em branco à esquerda
function LTrim(value) {
	if(value){
		var re = /\s*((\S+\s*)*)/;
		return value.replace(re, "$1");
	}
}

// Remove espaços em branco à direita
function RTrim(value) {
	if(value){
		var re = /((\s*\S+)*)\s*/;
		return value.replace(re, "$1");
	}
}

// Remove espaços em branco à direita e esquerda
function trim(value) {
	if(value){
		return LTrim(RTrim(value));
	}
}