﻿//---------------------------------------------------------------------------
// Objetivo...........: Encapsular funções de requisição XMLHTTP e
//						manipulação de XML
// Autor..............: Alan A. Oliveira
// Data...............: 12/04/2007
// Comentários........: 
// Alterado por.......: 
// Data...............: 
// Motivo da Alteração: 
//--------------------------------------------------------------------------
// Componentes usados.: Microsoft.XMLHTTP, Msxml2.XMLHTTP, Microsoft.XMLDOM
//						e DOMParser
// Entradas...........:  
// Retorno............: 
//---------------------------------------------------------------------------

var gobjXMLHTTP;	//Objeto Microsoft.xmlhttp
var gobjXMLDOM;		//Objeto XMLDOM
var gstrCA = new String('')
//--------------------------------------------------------------------------------
// Objetivo	 : Instanciar objeto XMLHTTP de acordo com o navegador
// Premissas : 
// Entradas	 : 
// Retorno	 : Objeto XMLHTTP utilizado pelo navegador em uso
//--------------------------------------------------------------------------------
function InstanciarXMLHTTP(){

	if (window.XMLHttpRequest){//Mozzila
		return (new XMLHttpRequest());
	}
	else if (window.ActiveXObject){//Internet Explorer
		try {
			return (new ActiveXObject("Msxml2.XMLHTTP"));
		}
		catch (objErro){
			try {
				return (new ActiveXObject("Microsoft.XMLHTTP"));
			}
			catch (objErro){
				alert("Computador sem suporte para XMLHTTP.\n" + objErro.message)
			}
		}
	}
}
//--------------------------------------------------------------------------------
// Objetivo  : Estabeler conexao XMLHTTP
// Premissas : 
// Entradas  : strURL - URL do servidor que receberá a solicitação
//			 : strMetodoEnvio - Forma de envio dos parâmetros ("get" ou "post")
//			 : intCodigoTipoRetorno - Código do tipo de retorno do servidor
//									  1 > Retorna literal
//									  2 > Retorna objeto XML
//			 : blnAssincrono - Comportamento após da solicitação ao servidor
//							   "true" > Continua execução do script
//							   "false" > Aguarda resposta do servidor para continuar execução do script
//			 : strFuncaoGerenciadora - Nome da função que receberá os dados retornados pelo servidor
//           : arrParametro - Array com parametros para envio modo post Ex. strTexo=teste&strData=12-12-2007
// Retorno   : Literal / Objeto XML
//--------------------------------------------------------------------------------
function CarregarXMLHTTP(strURL, strMetodoEnvio, intCodigoTipoRetorno, blnAssincrono, strFuncaoGerenciadora, arrParametro){

	
	try{
	
	
	
	gobjXMLHTTP = new InstanciarXMLHTTP();		//Objeto Microsoft.xmlhttp
	if (gobjXMLHTTP){
		with (gobjXMLHTTP){
			if (strFuncaoGerenciadora.length > 0) gobjXMLHTTP.onreadystatechange = new Function("if (gobjXMLHTTP.readyState == 4){" + strFuncaoGerenciadora + "(gobjXMLHTTP." + ((intCodigoTipoRetorno == 1)?"responseText":"responseXML") + ")}");
			open(strMetodoEnvio, strURL, blnAssincrono);
			if(strMetodoEnvio.toUpperCase()== "POST")
			{
			    setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
                setRequestHeader("Pragma", "no-cache");
			
                if(typeof(arrParametro)=="object")
                {
                    send(MontarParametro(arrParametro));
                }
                else
                {
                    send(arrParametro);
                }
                
            }
			else
			{
			    send(null);
            }
            if (strFuncaoGerenciadora.length == 0) return ((intCodigoTipoRetorno == 1)?gobjXMLHTTP.responseText:gobjXMLHTTP.responseXML)
		}
	}
	}
	catch(objEx)
	{
	    alert(objEx.message)
	}
}
//--------------------------------------------------------------------------------
// Objetivo  : Estabeler conexao XMLHTTP
// Premissas : 
// Entradas  : XML quando intCodigoTipoXML = 1 ou localização do XML quando intCodigoTipoXML = 2
//			 : intCodigoTipoXML - Tipo de XML que será carregado
//							   1 > XML literal (memória)
//							   2 > XML físico
//			 : blnAssincrono - Comportamento após da solicitação de carregamento do XML
//							   "true" > Continua execução do script
//							   "false" > Aguarda carregamento para continuar execução do script
//			 : strFuncaoGerenciadora - Nome da função que receberá o objeto XML carregado
//			 : blnXPath - Habilitar suporte a linguagem XPath
// Retorno   : Objeto XML
//--------------------------------------------------------------------------------
function CarregarXML(strXML, intCodigoTipoXML, blnAssincrono, strFuncaoGerenciadora, blnXPath){
	if (window.ActiveXObject){//Internet Explorer
		objXMLDOM = new ActiveXObject("Microsoft.XMLDOM");

		if (blnXPath) objXMLDOM.setProperty ("SelectionLanguage", "XPath");

		objXMLDOM.async = blnAssincrono;

		if (intCodigoTipoXML == 1) objXMLDOM.loadXML(strXML)
		else if (intCodigoTipoXML == 2) objXMLDOM.load(strXML)

		if (strFuncaoGerenciadora.length == 0) return (objXMLDOM)
		else eval(strFuncaoGerenciadora + "(objXMLDOM)");
	}
	else {//Mozzila
		if (intCodigoTipoXML == 1){alert("1 CarregarXML")
			objXMLDOM = new DOMParser();//Manipulador XML Mozzila
			objXMLDOM.parseFromString(strXML, "text/xml");
			//objXMLDOM.onload = new Function(strFuncaoGerenciadora + "(objXMLDOM)");
		}
		if (intCodigoTipoXML == 2){
			objXMLDOM = document.implementation.createDocument("","",null);
			objXMLDOM.load(strXML);

			if (strFuncaoGerenciadora.length > 0){
				objXMLDOM.onload = new Function(strFuncaoGerenciadora + "(objXMLDOM)");
			}
			else {
				objXMLDOM.onload = new Function("return (objXMLDOM)")
			}
		}
	}
}
//--------------------------------------------------------------------------------
// Objetivo	 : Exibir Retorno objeto XMLHTTP 
// Premissas : 
// Entradas	 : 
// Retorno	 : Objeto XMLHTTP utilizado pelo navegador em uso
//--------------------------------------------------------------------------------
function ExibirRetornoXMLHTTP(objRetornoXMLHTTP){

	var gobjXMLElement = objRetornoXMLHTTP.getElementsByTagName("item")
	var intIaux;
	for (intC00=0; intC00 < gobjXMLElement.length; intC00++){
		    for(intIaux=0;intIaux<gobjXMLElement[intC00].childNodes.length;intIaux++)
		    {
		        if(gobjXMLElement[intC00].childNodes[intIaux].nodeType==1)
		            alert(gobjXMLElement[intC00].childNodes[intIaux].childNodes[0].nodeValue)
		    }
	}
}
//--------------------------------------------------------------------------------
// Objetivo	 : Montar Parâmetro form
// Premissas : 
// Entradas	 : objForm - objeto form 
// Retorno	 : 
//--------------------------------------------------------------------------------
function MontarParametro(objForm)
{
    var arrParametro = new String('')
    var intIaux  
    
    for(intIaux=0;intIaux<objForm.length;intIaux++)
    {
        if (objForm[intIaux].type=="text")
        arrParametro += objForm[intIaux].name + "="+ objForm[intIaux].value + "&"
    }
    
    return arrParametro 
}
//--------------------------------------------------------------------------------
// Objetivo	 : Exibir Retorno
// Premissas : 
// Entradas	 : 
// Retorno	 : 
//--------------------------------------------------------------------------------
function ExibirRetornoTexto(objRetornoXMLHTTP){

    alert(objRetornoXMLHTTP)
}
//--------------------------------------------------------------------------------
// Objetivo	 : Consultar Ano do documento
// Premissas : 
// Entradas	 : objXmlREt objeto xml
// Retorno	 : 
//--------------------------------------------------------------------------------
function ConsultarAtivo(objXmlREt)
{
    
   var objXMLElement = objXmlREt.getElementsByTagName("PAPEIS"); // objeto xml
   var objXMLDomElement 
   var intIaux;   // Variavel auxiliar
   var objHtml // Objeto HTML
   var strID   // Recebe id
    var strLink // Recebe link
    
    try
    {
        if (objXMLElement.length> 0 )
        {
            
            switch (objXMLElement.getAttribute("TPOINFO"))
            {
                case 0:
                    objXMLDomElement= objXmlREt.getElementsByTagName("ATIVO");
                    break;                    
                case 1:
                    objXMLDomElement= objXmlREt.getElementsByTagName("ATIVO");
                    break;
                case 2:
                    objXMLDomElement= objXmlREt.getElementsByTagName("ATIVO");
                    break;         
                    
            
            }
            
            for (intIaux=0;intIaux<objXMLElement.length;intIaux++)
            {
	            strLink = "FormConsultaDetalhe.asp?ID="+objXMLElement[intIaux].getAttribute("ID")
	            document.getElementById(strID).innerHTML = "<a  href='"+strLink+"'> " + objXMLElement[intIaux].childNodes[0].childNodes[0].nodeValue + " </a>"  
	        }
        }
    }
    catch(objEx)
    {
       alert(objEx.message)
    }
}
//--------------------------------------------------------------------------------
// Objetivo	 : Consultar Ano do documento
// Premissas : 
// Entradas	 : objXmlREt objeto xml
// Retorno	 : 
//--------------------------------------------------------------------------------
function ValidarInfoAtivo(objFormTxtCodigoAtivo)
{
    try
    {
        var strAtivo = new String('') // String
        var objPopUp // Objeto POPUP
    
        strAtivo = objFormTxtCodigoAtivo.value
        window.defaultStatus= Math.random(123);
    
        if(strAtivo.length<=3)
        {
            throw "Digite pelo menos dois caracteres."
        }
            objPopUp = window.open("ExecutaAcaoCotRapXML.asp?CodigoAtivo="+strAtivo+"&rdn="+Math.random(123),"CotacaoRapida")
            objPopUp.focus();
    }
    catch(objEx)
    {
       alert(objEx.toString());
    }
}

var objPopup;
//--------------------------------------------------------------------------------
// Objetivo	 : Consultar Ano do documento
// Premissas : 
// Entradas	 : objXmlREt objeto xml
// Retorno	 :
//--------------------------------------------------------------------------------

/*
Função para pesquisar cotação rápida ao pressionar o enter no campo de pesquisa 
*/
function keyPressPesquisaCotacao(objeto, e) {
    if ((e.keyCode != null && e.keyCode == 13) || (e.charCode != null && e.charCode == 13)) {
        document.getElementById(objeto).click();
    }
}

function ValidarCotacaoRapida(intStatus, intIdioma) {
    try {


        if (document.getElementById('txtCodigo').value == '') {
            if (intIdioma == "P") {
                throw "Digite o nome da empresa ou código."
            }
            else if (intIdioma == "I") {
                throw "Type the company name or code ."
            }
            else if (intIdioma == "E") {
                throw "Teclee el nombre o clave de la empresa."
            }
        }
        else if (document.getElementById('txtCodigo').value.length <= 2) {
            if (intIdioma == "P") {
                throw "Digite mais de 2 caracter."
            }
            else if (intIdioma == "I") {
                throw "Type 2 caracter."
            }
            else if (intIdioma == "E") {
                throw "Teclee el."
            }
        }
        else if (document.getElementById('txtCodigo').value.toUpperCase() == 'IBOV' || document.getElementById('txtCodigo').value.toUpperCase() == 'ITAG' || document.getElementById('txtCodigo').value.toUpperCase() == 'IBXX' || document.getElementById('txtCodigo').value.toUpperCase() == 'IBXL' || document.getElementById('txtCodigo').value.toUpperCase() == 'ITEL' || document.getElementById('txtCodigo').value.toUpperCase() == 'ISEE' || document.getElementById('txtCodigo').value.toUpperCase() == 'INDX' || document.getElementById('txtCodigo').value.toUpperCase() == 'IGCX' || document.getElementById('txtCodigo').value.toUpperCase() == 'IVBX' || document.getElementById('txtCodigo').value.toUpperCase() == 'IEEX') {
            document.getElementById('txtCodigo').value = document.getElementById('txtCodigo').value + " " + " - Índice"
        }


        if (intStatus == 1) {
            var codigo = document.getElementById('txtCodigo').value;
            codigo = codigo.toUpperCase();
            if (objPopup == null) {

                if (intIdioma == "P") {
                    objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=0', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');

                }
                else if (intIdioma == "I") {
                    objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=1', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');
                }
                else if (intIdioma == "E") {
                    objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=2', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');
                }

                objPopup.focus();

            }
            else {

                var url = '';

                if (intIdioma == "P") {
                    url = '/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=0', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1';
                }
                else if (intIdioma == "I") {
                    url = '/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=1', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1';
                }
                else if (intIdioma == "E") {
                    url = '/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + codigo + '&intIdiomaXsl=2', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1';
                }
                try {

                    objPopup.location.href = url;
                    objPopup.focus();
                }
                catch (objEx) {
                    if (intIdioma == "P") {
                        objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + document.getElementById('txtCodigo').value + '&intIdiomaXsl=0', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');
                    }
                    else if (intIdioma == "I") {
                        objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + document.getElementById('txtCodigo').value + '&intIdiomaXsl=1', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');
                    }
                    else if (intIdioma == "E") {
                        objPopup = window.open('/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=' + gstrCA + '&txtCodigo=' + document.getElementById('txtCodigo').value + '&intIdiomaXsl=2', 'CotacaoRapida', 'width=352px,height=360px,scrollbars=1');
                    }

                    objPopup.focus();


                }
            }
        }

        else if (intStatus == 2) {

            if (intIdioma == "P") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "&intIdiomaXsl=0";
            }
            else if (intIdioma == "I") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "&intIdiomaXsl=1";
            }
            else if (intIdioma == "E") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "&intIdiomaXsl=2";
            }

            document.frmCotacaoRapida.submit();
        }
        else if (intStatus == 3) {

            if (intIdioma == "P") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "&intIdiomaXsl=5";
            }
            else if (intIdioma == "I") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "&intIdiomaXsl=6";
            }
            else if (intIdioma == "E") {
                document.frmCotacaoRapida.action = "/Pregao-online/ExecutaAcaoCotRapXSL.asp?gstrCA=" + gstrCA + "& intIdiomaXsl=7";
            }

            document.frmCotacaoRapida.submit();
        }

    }
    catch (objEx) {
        alert(objEx.toString())
    }
}
