//check if it is IE
var isIE = (window.navigator.appName.toLowerCase().indexOf("microsoft")>=0);

//implement loadXML method for Mozilla since it is not supported
if(!isIE){
    Document.prototype.loadXML = function (s) {

        // parse the string to a new doc
        var doc2 = (new DOMParser()).parseFromString(s, "text/xml");

         // remove all initial children
         while (this.hasChildNodes())
            this.removeChild(this.lastChild);

        // insert and import nodes
        for (var i = 0; i < doc2.childNodes.length; i++) {
            this.appendChild(this.importNode(doc2.childNodes[i], true));
         }
     };
}  
var xmlhttp;

//Tenta criar o objeto xmlHTTP
function getHTTPObject() {
	try
	{
	    xmlhttp = new XMLHttpRequest();
	}
	catch(ee)
	{
	    try
	    {
	        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	    }
	    catch(e)
	    {
	        try
	        {
	            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	        }
	        catch(E)
	        {
	            xmlhttp = false;
	        }
	    }
	}
	return xmlhttp;
}

//Fila de conexoes
fila = [];
ifila = 0;

//Carrega via XMLHTTP a url recebida e coloca seu valor
//no objeto com o id recebido
function ajaxHTML(id, url) {
    //Carregando...
    document.getElementById(id).innerHTML += "<img alt='Carregando' tittle='Carregando' src='images/carregando.gif' border='0' />"
    //Adiciona a fila
    fila[fila.length] = [id, url]
    //Se nao ha conexoes pendentes, executa
    if( (ifila + 1) == fila.length)
    	ajaxRun();
}

//Carrega via XMLHTTP a url recebida e coloca seu valor
//no objeto com o id recebido, mostrando o ?cone Carregando e a mensagem "Carregando..."
function ajaxHTMLCarregando(id, url) {
    //Carregando...
    document.getElementById(id).innerHTML = "<img alt='Carregando' tittle='Carregando' src='images/carregando.gif' border='0' /> Carregando..."
    //Adiciona a fila
    fila[fila.length] = [id, url]
    //Se nao ha conexoes pendentes, executa
    if( (ifila + 1) == fila.length)
    	ajaxRun();
}

//Executa uma commandLink oculto
//e rerenderiza o target especificado
function ajaxComando(comando, target) {
    var hiddenCommandLink = window.document.getElementById(comando);
    	if (hiddenCommandLink )
	{
            if (hiddenCommandLink.onclick)
                hiddenCommandLink.onclick(); 
            else
		hiddenCommandLink.fireEvent("onclick");
	}
}	

//Executa a pr?xima conexao da fila
function ajaxRun() {
    //Abre a conexao
    xmlhttp.open("GET", fila[ifila][1], true);
    
    //Funcao para tratamento do retorno
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) 
        {
            //Mostra o HTML recebido
            retorno = unescape(xmlhttp.responseText.replace(/\+/g, " "));
            document.getElementById(fila[ifila][0]).innerHTML = retorno;
            //Roda o proximo
            ifila++;
            if(ifila < fila.length)
            	setTimeout("ajaxRun()", 20);
        }
    }
    //Executa
    xmlhttp.send(null);
}

//Carrega Campo
function carregarCampo(campo,elementoResposta) {
        //if not ready, abort the previous request
        if (xmlhttp.readyState != 0) {
                xmlhttp.abort();
        }

        //servlet url, pass the search key
        //var url = "/iSecWeb/AjaxServlet?chave="+document.getElementById(fonte).value+"&acao="+acao;
        var url = "http://er.acbrasil.org/cgi-bin/hde.cgi";
        var xmlDoc;
		var textoXML = ""
		if (isIE)
			textoXML="<?xml version = '1.0'?>";
		textoXML += "<DOCUMENT><SERVICE>000001</SERVICE><DATABASE>geral</DATABASE><DSN>MyDSN</DSN>";
		textoXML += "<SQLS> <SQL1>select doc_nome from docto where doc_docto='02735933903'</SQL1> </SQLS></DOCUMENT>";

        //send request to the server
        if (xmlhttp != null) {
            xmlhttp.open("POST", url, true);
	    xmlhttp.setRequestHeader('Content-Type',"application/xml; charset=iso8859-1");
            xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        xmlDoc = processResponse();
                        var elemento = xmlDoc.getElementsByTagName("ROW");
						if (elemento.length>0)
						{
                            var valor = elemento.item(0).getAttribute("doc_nome");
                            document.getElementById(campo).value = valor;
                        } else {
                            document.getElementById(campo).value = "NAO ENCONTRADO!";
                        }
                    }
            };
			
			if (isIE) {
//				xmlhttp.send('<?xml version = "1.0"?>'+xmlConsulta.xml);
				xmlhttp.send(textXML);
			} else {
			    xmlhttp.send(textoXML);
			}
        }
}

//processa a resposta vinda do AjaxServlet
function processResponse() {
    if (xmlhttp.readyState == 4){
        //process only if OK
        if (xmlhttp.status == 200)  {
            if(xmlhttp.responseText!=null) {
                return parseResponse(xmlhttp.responseText);
            }
        }
    }
}

//traduz a resposta vinda do AjaxServlet
function parseResponse(result){

    var xmlDoc;
    //load xml document
    if(document.implementation && document.implementation.createDocument) {
        // MOZILLA
        xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.async="false";
        xmlDoc.loadXML(result);
    } else if (window.ActiveXObject) {

        //IE
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(result);
    }
    return xmlDoc;
}

//Carrega varios campos
//fonte (campo contendo o valor da chave para pesquisa)
//campos (array contendo os nomes dos campos que serão carregados)
//elementosResposta (array contendo o nome dos elemento do XML de resposta
//                  referentes aos campos na mesma ordem)
function carregarCampos(fonte,campos,elementosResposta) {
        //if not ready, abort the previous request
        if (xmlhttp.readyState != 0) {
                xmlhttp.abort();
        }

        //servlet url, pass the search key
        //var url = "/iSecWeb/AjaxServlet?chave="+document.getElementById(fonte).value+"&acao="+acao;
        var url = "http://er.acbrasil.org/cgi-bin/hde.cgi";
        var xmlDoc;
		var textoXML = ""
		if (isIE)
			textoXML="<?xml version = '1.0'?>";
		textoXML += "<DOCUMENT><SERVICE>000001</SERVICE><DATABASE>geral</DATABASE><DSN>MyDSN</DSN>";
		textoXML += "<SQLS> <SQL1>select ";
		isPrimeiro = true;
		for ( i in elementosResposta ){
		  if (!isPrimeiro){
			textoXML +=", "+elementosResposta[i];
		  } else {
			isPrimeiro = false;
			textoXML +=elementosResposta[i];
		  }
		}
		textoXML +=" from docto where doc_docto='"+document.getElementById(fonte).value+"'</SQL1> </SQLS></DOCUMENT>";

        //send request to the server
        if (xmlhttp != null) {
            xmlhttp.open("POST", url, true);
	    xmlhttp.setRequestHeader('Content-Type',"application/xml; charset=iso8859-1");
            xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        xmlDoc = processResponse();
                        var elemento = xmlDoc.getElementsByTagName("ROW");
                        if (campos.length == elementosResposta.length) {
                            for (i in campos){
                                if (elemento.length > 0) {
                                    var valor = elemento.item(0).getAttribute(elementosResposta[i]);
				    if (elementosResposta[i]=="doc_oudoc") {
					//verifica se os 2 primeiros e os 2 últimos caracteres não são número
					// e nesse caso retira-os 
					if (!isNumeros(valor.substring(0,2)) && !isNumeros(valor.substring(valor.length-2,valor.length))) {
						var rg = valor.substring(2,valor.length-2);
						valor = rg;
					}
				    }
				    if (elementosResposta[i]=="doc_data") {
					var data = valor.split("-");
					valor = data[2]+data[1]+data[0];
				    }
                                    document.getElementById(campos[i]).value = valor;
                                }
                            }
                        }
                    }
            };
		
	    if (isIE) {
//		xmlhttp.send('<?xml version = "1.0"?>'+xmlConsulta.xml);
			xmlhttp.send(textoXML);
	    } else {
		        xmlhttp.send(textoXML);
            }
  	}
}

function novoXML(tagRaiz) { 
	if (!tagRaiz) tagRaiz = ""; 
	if (document.implementation && document.implementation.createDocument) { 
	    // This is the W3C standard way to do it 
		return document.implementation.createDocument("", tagRaiz, null); 
	} else { // This is the IE way to do it 

		var doc = new ActiveXObject("MSXML2.DOMDocument"); 

	    if (tagRaiz) { 
			var tagname = tagRaiz; 

			// Create the root element (with optional namespace) as a 
			// string of text 
			var text = "<" + tagname + "/>"; 
			// And parse that text into the empty document 
			doc.loadXML(text); 
		} 
		return doc; 
	} 
}

function parserXML(textoXML){
	var docXML=false;
	if (document.implementation.createDocument) {
        var parser = new DOMParser();
        doc = parser.parseFromString(textoXML, "text/xml");
    // MSIE
    } else if (window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async="false";
        doc.loadXML(textoXML);
    }
	return docXML;
}

function isNumeros(field)
{
  res = false;

  if (field.match("[0-9]+") == field) {
    res = true;
  }

  return (res);
}
getHTTPObject();

