//'******************* 
//  'Analista Desenvolvedor: Luiz Alexandre Dantas dos Santos
//  'Criação: 17/05/2006
//  'Alterações:
//  '*******************'

// Módulo genérico para funções em JavaScript

// ***************** FUNÇÕES DE PARA USO DE XML HTTP ***************** 
//função para invocar página através de XML DOM, com parâmetros e 
//realizar processamento

// codifica string de parâmetro para caracteres HTML (Hex)

function cURLEncode(cStringParam) {
    var cChrHex = "0123456789ABCDEF";
    var cChrsEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var iCont, cChrCode, cHex1, cHex2, cStringEncode = "";
    for(iCont = 0; iCont < cStringParam.length; iCont++) {
        if (cChrsEncode.test(cStringParam.charAt(iCont))) {
            cStringEncode += cStringParam.charAt(iCont);
        } else {
            if (cStringParam.charAt(iCont) == "&") {
                cStringEncode += "&amp;";
            }
            else{
                cChrCode = cStringParam.charCodeAt(iCont);
                cHex1 = cChrHex.charAt(Math.floor(cChrCode / 16));
                cHex2 = cChrHex.charAt(cChrCode % 16);
                cStringEncode += "%" + (cHex1 + cHex2);
            }
        }
    }
    return cStringEncode;
}

// decodifica string (em formato HTML - hex) de parâmetro para caracteres ASCII
function cURLDecode(cStringParam) {
    var iCont, cChrCode, cStringDecode = "";
    for (iCont = 0; iCont < cStringParam.length; iCont++) {
        if (cStringParam.charAt(iCont) == "%") {
            cChrCode = cStringParam.charAt(iCont + 1) + cStringParam.charAt(iCont + 2);
            cStringDecode += String.fromCharCode(parseInt(cChrCode, 16));
            iCont += 2;
        } else {
            cStringDecode += cStringParam.charAt(iCont);
        }
    }
    return cStringDecode;
}

//Codifica para o envio do html
function cHTMLEncode2(cValor){
	var Encode = new String;
	var Code = new String;
	var i;
	//Somente os sinais de < e > foram deixados de fora pois faz parte da tag	
	var Encode = "%ÊêÂâÔôÕõÃãÀÁÈÉÌÍÒÓÙÚáàéèíìóòùúçÇ&¨+°ªº§ " + String.fromCharCode(13);
	var Code = "%25%CA%EA%C2%E2%D4%F4%D5%F5%C3%E3%C0%C1%C8%C9%CC%CD%D2%D3%D9%DA%E1%E0%E9%E8%ED%EC%F3%F2%F9%FA%E7%C7%26%A8%2B%B0%AA%BA%A7%20%0D";
	for(i = 0; i < Encode.length; i++){
		if(cValor.indexOf(Encode.substring(i,i+1))!=-1){
			cValor = Replace(cValor, Encode.substring(i,i+1), Code.substring((i*3),(i*3)+3))
		}
	}
	return cValor;
}

//carrega conteúdo XML em obj XML DOM
function fLoadXML(cXML, lArq) {
    //cXML: conteúdo XML a ser carregado
    var oXML = new ActiveXObject("Microsoft.XMLDOM");
    oXML.async = false;
    oXML.onreadystatechange=fStatusXML;
    
    function fStatusXML(){
    //função que monitora o status da resposta do XML HTTP com o conteúdo XML
    // 0 Object is not initialized
    // 1 Loading object is loading data
    // 2 Loaded object has loaded data
    // 3 Data from object can be worked with
    // 4 Object completely initialized
      if (oXML.readyState != 4)
      {
        return false;
      }
    }    
    if (lArq) {
        //carrega arq. XML
        oXML.load(cXML);
    }
    else {
        //carrega conteúdo XML
        oXML.loadXML(cXML);
    }
    return oXML;
}

//envio de string com parâmetros via GET e resposta em formato XML
function fXMLHttp(cPagina, cParams) {
    //cPagina: pagina a ser submetida para processamento
    //cParams: parâmetros da ação - por ex.: ?Param=123&Param2=ABC
    var oXML = new ActiveXObject("Microsoft.XMLDOM");
    var cXML = new String();
    cXML = cPagina + cParams;
    oXML.async = false;
    oXML.load(cXML);
    //retorn conteúdo XML de resposta do processamento
    return oXML;
}


 function fBusValSelect()
 {
    var oHTTPRequest = fCreateXMLHttp(); 
     oHTTPRequest.open("post", "wCNA_PRO_Vendedor.asp", true);
     oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     oHTTPRequest.onreadystatechange=function(){
      if (oHTTPRequest.readyState==4){
         document.all.divVendedor.innerHTML = oHTTPRequest.responseText;}}
       oHTTPRequest.send("lstPatio=" + document.all.lstPatio.value);
 }

//cria objeto XML HTTP
function fCreateXMLHttp(){
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest();  
   } else if (window.ActiveXObject) {  
      //return new ActiveXObject("Msxml2.XMLHTTP");
      return new ActiveXObject("Microsoft.XMLHTTP");
   } else {  
       alert("Seu navegador n&atilde;o suporta XMLHttpRequest.");  
      return;  
   }
    //if (window.ActiveXObject) {
    //    return new ActiveXObject("Microsoft.XMLHTTP");
    //} else if (window.XMLHttpRequest) {
    //    return new XMLHttpRequest();
    //} else {
    //    return null;
    //}
}

//executa uma chamada via XML HTTP
function cExecXMLHTTP(cPagina, cXML, cFuncao, iTempo){
    //cPagina: link (URL) a ser submetido
    //cXML: conteúdo XML de parâmetro
    //cFuncao: nome da função a ser chamada ao receber retorno do XML HTTP
    //iTempo: tempo de aguarda para executar função do parâmetro
    var oXML = fCreateXMLHttp();
    var cRespXML = "";
    if (oXML == null) {
        //não foi possível criar obj. XML HTTP
       alert("nulo");
    }
    oXML.onreadystatechange = fHandleHttpEvent;
    
    //função para manipular retorno da chamada XML HTTP
    function fHandleHttpEvent(){
    
        if (oXML.readyState == 4) {
            if (oXML.status == 200) {
                //ao receber retorno do processamento, chama função que processará o resultado
                if (cFuncao == "fRetGravarVeiculoXML") {
                    document.frmMain.hidCampoAlterado.value="0";
                }
                return fRetornoXML(oXML.responseText, cFuncao, iTempo);
            } else {
                //alert("sem dados");
            }
        }
    }
    oXML.open("POST", cPagina , false);
    //; iso-8859-1
    oXML.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //função cURLEncode: codifica caracteres a serem enviados para evitar 
    //problemas com caracteres especiais, acentuação
    //cXML = cURLEncode(cXML);
    //oXML.send(cXML);
    oXML.send("xml=" + cXML);
    
}

//retorna resultado da chamada XML HTTP no estado 
// oXML.readyState == 4 e 
// oXML.status == 200 
// Retorno em oXML.responseText
function fRetornoXML(cRetornoXML, cFuncao, iTempo){ 
    //cRetornoXML: parâmetro com conteúdo do retorno XML da chamada XML HTTP
    //cFuncao: nome da função a ser invocada ao ter o retorno XML
    //iTempo: tempo para aguardar a chamada a função passada como parâmetro
    cFuncao = cFuncao + "(" + String.fromCharCode(34) + cRetornoXML + String.fromCharCode(34) + ");";
    fTimer(cFuncao, iTempo);
}

function cTagXML(cNomeTag, cValor){
    return "<" + cNomeTag + ">" + cValor + "</" + cNomeTag + ">";
}

//cria timer que invocará função passada como parâmetro
function fTimer(cFuncao, iTempo){
    //cFuncao: nome da função a ser chamada
    //iTempo: tempo em milissegundos para aguardar até chamar função
    setTimeout(cFuncao, iTempo);
}

//Timer para a executar função passada como parâmetro
function fExecutaFuncao(cNomeFuncao, oObj, cMsg){
    //cNomeFuncao: nome da função a ser chamada após contagem do tempo com setTimeout
    //oObj: objeto de referência para posicionar a exibição do frame
    //cMsg: mensagem exibida
    document.all.txtMessage.innerHTML = cMsg;
    fVisibleDiv(document.all.DivTime,oObj,"",true);
    setTimeout(cNomeFuncao, 1);
}

// ***************** FUNÇÕES DE MANIPULAÇÃO DE HTML (TABLE, COMBO, DIVs) ***************** 
//adiciona linhas a tabela
function fAddLine(cTabela, cIdCol, cColunas, cClassColunas) {
    //cTabela: id da tabela no HTML
    //cIdCol: id da coluna HTML
    //cColunas: string separada por | com colunas a serem criadas na tabela
    //cClassColunas: string separada por | com "class" de cada coluna a ser criada
    
    //cria array com colunas a serem criadas na tabela
    var acColunas = cColunas.split("|");
    //cria array com estilo (css) das colunas 
    var acClassColunas = cClassColunas.split("|");
    var iDimens = 0;
    cNewRow = cTabela.insertRow();
    while (iDimens < acColunas.length) {
      cNewCell = cNewRow.insertCell();
      if (iDimens==0) {
        //adiciona id apenas a primeira coluna da tabela
        cNewCell.id = cIdCol;
      }
      cNewCell.className = acClassColunas[iDimens];
      cNewCell.innerHTML = acColunas[iDimens];
      iDimens+=1;
    }
    return;
}

//adiciona linhas a tabela
function fAddLineMultiple(cTabela, cIdCols, cColunas, cClassColunas) {
    //cTabela: id da tabela no HTML
    //cIdCol: id da coluna HTML
    //cColunas: string separada por | com colunas a serem criadas na tabela
    //cClassColunas: string separada por | com "class" de cada coluna a ser criada
    
    //cria array com colunas a serem criadas na tabela
    var acColunas = cColunas.split("|");
    //cria array com estilo (css) das colunas 
    var acClassColunas = cClassColunas.split("|");
    //cria array com ids das colunas
    var acColunasIds = cIdCols.split("|");
    var iDimens = 0;
    cNewRow = cTabela.insertRow();
    while (iDimens < acColunas.length) {
      cNewCell = cNewRow.insertCell();
      cNewCell.id = acColunasIds[iDimens];
      cNewCell.className = acClassColunas[iDimens];
      cNewCell.innerHTML = acColunas[iDimens];
      iDimens+=1;
    }
    return;
}

//adiciona linhas a tabela
function fAddLineMultipleSpan(cTabela, cIdCols, cColunas, cClassColunas, cColSpan) {
    //cTabela: id da tabela no HTML
    //cIdCol: id da coluna HTML
    //cColunas: string separada por | com colunas a serem criadas na tabela
    //cClassColunas: string separada por | com "class" de cada coluna a ser criada
    
    //cria array com colunas a serem criadas na tabela
    var acColunas = cColunas.split("|");
    //cria array com estilo (css) das colunas 
    var acClassColunas = cClassColunas.split("|");
    //cria array com ids das colunas
    var acColunasIds = cIdCols.split("|");
    var acColSpan = cColSpan.split("|");
    var iDimens = 0;
    cNewRow = cTabela.insertRow();
    while (iDimens < acColunas.length) {
      cNewCell = cNewRow.insertCell();
      cNewCell.id = acColunasIds[iDimens];
      cNewCell.className = acClassColunas[iDimens];
      cNewCell.colSpan  = acColSpan[iDimens];
      cNewCell.innerHTML = acColunas[iDimens];
      iDimens+=1;
      //iDimens = iDimens + parseInt(acColSpan[iDimens]);
    }
    return;
}

//remove linhas de uma tabela HTML
function fRemoverLinhaTabela(cTabela, oObj, iExibeValorCel, cTitulo){
    //cTabela: id da tabela no HTML
	//oObj: indica a linha a ser removida
	//iExibeValorCel: indica qual coluna (célula) terá o conteúdo exibido na mensagem de exclusão
	//cTitulo: título a ser exibido na mensagem
    //delete linha da tabela
    cTabela.deleteRow(oObj.parentElement.parentElement.rowIndex);
}

//remove linhas de uma tabela HTML
function fRemoverLinhaTabelaAnterior(cTabela, oObj, iExibeValorCel, cTitulo){
    //cTabela: id da tabela no HTML
	//oObj: indica a linha a ser removida
	//iExibeValorCel: indica qual coluna (célula) terá o conteúdo exibido na mensagem de exclusão
	//cTitulo: título a ser exibido na mensagem
    //delete linha da tabela
    cTabela.deleteRow(oObj.parentElement.parentElement.rowIndex - 1);
    cTabela.deleteRow(oObj.parentElement.parentElement.rowIndex);
}
//limpar linhas da tabela passada como parâmetro
function fLimparTabela(cTabela){
    //cTabela: id da tabela no HTML
    while (cTabela.rows.length > 1){
        cTabela.deleteRow(cTabela.rows.length - 1);
    }
}

//procura por conteúdo em célula de tabela HTML, 
//se localizar, retorna "true" indicando que já existe
function fFindCelTabela(cTabela, cCampoFind){
    //cTabela: id da tabela no HTML
    //cCampoFind: informação a localizar
    for(iCont=1; iCont < cTabela.rows.length; iCont++){
	    if (cJavaTrimUC(cCampoFind) == cJavaTrimUC(document.all.celDados(iCont).innerText)){
		    return true;
	    }
    }
    return false;
}

function fFindCelTabela2(cTabela, cCampoFind){
    //cTabela: id da tabela no HTML
    //cCampoFind: informação a localizar
    for(iCont=1; iCont < cTabela.rows.length; iCont++){
	    if (cJavaTrimUC(cCampoFind) == cJavaTrimUC(document.all.celIdDesp(iCont).innerText)){
		    return true;
	    }
    }
    return false;
}

//procura por conteúdo em célula de tabela HTML, 
//se localizar, retorna "true" indicando que já existe
function fFindCelTabelaCol(cTabela, cCampoFind, cColuna){
    //cTabela: id da tabela no HTML
    //cCampoFind: informação a localizar
    //cColuna: nome da coluna a ser pesquisada
    //for(iCont=1; iCont < cTabela.rows.length; iCont++){
    for(iCont=1; iCont < document.all[cColuna].length; iCont++){
	    if (cJavaTrimUC(cCampoFind) == cJavaTrimUC(document.all[cColuna](iCont).innerText)){
		    return true;
	    }
    }
    return false;
}

//Localiza os registros na combo	
function fBuscaCombo(cSearch, cField, cDelimitador, oNextObjectFocus){
    //cSearch: conteúdo a ser localizado
    //cField: combo a ser pesquisada  
    //cDelimitador: delimitador do conteúdo do combobox, por ex.: 1 - Nome ("-")
    //oNextObjectFocus: próximo obj. a receber o foco
    var pattern;
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    //Usuário digitou o item completo, move foco para o próximo campo
    if((cField.options.selectedIndex !=-1) && (keycode == 13)){
	    if(cField.options[cField.options.selectedIndex].text == cSearch.value){
		    oNextObjectFocus.focus();
		    oNextObjectFocus.select();
	    }
    }
    //Setas para baixo, para cima e o enter não faz a busca
    if ((keycode == 40) || (keycode == 38) || (keycode == 13) || (keycode == 16) || (keycode == 9)){
	    return;
    }
    //Testa se foi digitado alguma coisa na caixa de texto
    if (cSearch.value == "") {
	    cField.options.selectedIndex = -1;
	    return;
    }
    //Verifica se busca pelo código ou pelo nome
    var Codigo;
    if (isNaN(cSearch.value)){
	    Codigo = false;
	    //Use "i" to make cSearch not case-sensitive
	    pattern = new RegExp("^" + cSearch.value , "i");
    }
    else {
	    Codigo = true;
    }
    //Faz a busca na combo
    var encontrou = false;
    for(var x=0; x < cField.options.length; x++){
	    //Busca pelo código
	    if (Codigo){
		    var nCod = Number(cField.options[x].text.substring(0,cField.options[x].text.indexOf(cDelimitador)));
		    if (nCod == Number(cJavaTrimUC(cSearch.value))){
			    encontrou = true;
			    cField.options[x].selected = true
			    // Se encontrou e o número de caracteres for igual a da combo, então
			    // exibe o valor da combo na caixa de texto
			    if ((encontrou) && (cField.options[x].text.indexOf(cDelimitador) == cSearch.value.length)){
				    cSearch.value = cField.options[x].text;
				    oNextObjectFocus.focus();
				    oNextObjectFocus.select();
			    }
			    break;
		    }
	    }
	    //Busca pelo nome
	    else{
	        //Primeiro busca pelo código alfanumérico
		    //Se não há parâmetro delimitador de busca então o parâmetro é o próprio texto da consulta
		    if (cDelimitador ==""){
			    var TextoA = cField.options[x].text
		    }
		    else{
			    var TextoA = cField.options[x].text.substring(0,cField.options[x].text.indexOf(cDelimitador));
		    }
		    TextoA = cJavaTrimUC(TextoA);
		    var TextoB = cSearch.value//.substring(0,cField.options[x].text.indexOf(cDelimitador))
		    TextoB = cJavaTrimUC(TextoB);
		    if ((TextoA.toUpperCase() == TextoB.toUpperCase()) && (TextoA != "") && (TextoB !="")){
			    encontrou = true;
			    cField.options[x].selected = true
			    // Se encontrou e o número de caracteres for igual a da combo, então
			    // exibe o valor da combo na caixa de texto
			    if (encontrou){
				    cSearch.value = cField.options[x].text;
				    oNextObjectFocus.focus();
				    oNextObjectFocus.select();
			    }
			    break;
		    }
		    //busca pelo nome
		    var Start = cDelimitador.length + cField.options[x].text.indexOf(cDelimitador);
		    if (pattern.test(cField.options[x].text.substring(Start,1000)) == true){
			    encontrou = true;
			    cField.options[x].selected = true
			    //Caso o usuário tenha digitado o nome completo então nem abre a combo
			    //e informa a caixa de texto passando para o próximo campo
			    break;	
		    }
	    }
    }			
    if(encontrou == false){
	    cField.options.selectedIndex = -1;
    }
}

//seleciona valores em ComboBox de múltiplos valores
function fSelComboMultiple(cValores, cNomeObj, iDimensPesquisa){
    //cValores: valores da pesquisa (por ex. F, 3 ,3 = Cd.Avaria, Hora Reparo, Valor Reparo
    //cNomeObj: nome do combo a ser pesquisa
    //iDimensPesquisa: dimensão do array cValores a ser considerado na pesquisa
    var iDimens = 0;
    var acValores = cValores.split("|");
    var acValoresDados = "";
    var cAux = "";
    while (iDimens < acValores.length - 1) {
        cAux = acValores[iDimens];
        acValoresDados = cAux.split(",");
        for(var i = 0;i < document.frmMain[cNomeObj].length;i++){
            if(document.frmMain[cNomeObj].options[i].value == cJavaTrimUC(acValoresDados[iDimensPesquisa])){
                document.frmMain[cNomeObj].options[i].selected = true;
                i = document.frmMain[cNomeObj].length;
            }
        }
      iDimens+=1;
    }
    return;
}

// Organiza os dados de uma tabela a partir do cabeçalho da mesma
function fSortTable(cTableToSort, iCol, iRowIni, iCols){
    //cTableToSort: id da tabela no HTML
    //iCol: coluna a ser ordenada
    //iRowIni: linha inicial da ordenação
    //iCols
	var iCurCell = iCol + (iCols * iRowIni);
	var totalRows = cTableToSort.rows.length;
	var arColl = new Array();
	var iAux = 0;
	
	//Coleta os dados da coluna a ser organizada
	iCurCell = iCol + (iCols * iRowIni);
	for (i = iRowIni; i < cTableToSort.rows.length; i++){
		arColl[i - iRowIni] = cTableToSort.cells(iCurCell).innerText;
		iCurCell = iCurCell + iCols;
	}
	//Organiza os dados da coluna selecionada
	arColl.sort();
	//Reorganiza a tabela
	for (i = iRowIni; i < totalRows; i++){
		iCurCell = iCol + (iCols * iRowIni);
		for( iAux = iRowIni; iAux < totalRows; iAux++){
			if (arColl[i - iRowIni] == cTableToSort.cells(iCurCell).innerText){
				cTableToSort.moveRow(iAux,i);
				break;
			}
			iCurCell = iCurCell + iCols;
		}
	}
}

//Atualiza a cor da linha da tabela
function fAtualizaStiloLinha(cTabela, iLinha){
    //cTabela: id da tabela no HTML
    //iLinha: linha a receber a mudança de cor
	iAux = 0;
	for(iCol=2; iCol < cTabela.rows.length; iCol++){
		if (iAux == 0){
			cTabela.rows(iLinha,iCol).style.backgroundColor = "cornsilk";
			iAux = 1;
		}
		else if (iAux == 1){
			cTabela.rows(iLinha,iCol).style.backgroundColor = "white";
			iAux = 0;
		}
	}
}

//Acha a posição do objeto no formulário em até 20 níveis
//Para posicionar e dimencionar o div em baixo da caixa de texto
function fVisibleDiv(cDivInf, Object, cComboDados, lVisible){
    //cDivInf: nome do Div a ser exibido
    //Object: obj. de referência da posição da msg a ser exibida
    //cComboDados: ComboBox a ser exibida
    //lVisible: indica de exibe ou esconde o Div
    var Top = 0;
    var Left = 0;
    //Nível 1
    Top = Object.offsetTop;
    Left = Object.offsetLeft;
    var cParent = "";
    //Loop dos níveis
    for(i=0;i<20;i++){
	    cParent = cParent + ".offsetParent"
	    var Obj = eval("Object" + cParent);
	    if(Obj == null){
		    break;
	    }
	    //Soma a posição do nivel atual com o anterir
	    Top = Top + Obj.offsetTop;
	    Left = Left + Obj.offsetLeft;
    }		
    //Passa os valores
    cDivInf.style.top = Top + Object.offsetHeight + 1;
    cDivInf.style.left = Left;
    if (cComboDados != "") cComboDados.style.width = Object.offsetWidth;
    if (lVisible == true) {
        if ( cDivInf.style.visibility == "hidden" ) {
             cDivInf.style.visibility = "visible";
        }
        if ( cDivInf.style.display == "none" ) {
             cDivInf.style.display = "";
        }
    }
}

//Valida o campo digitado
function fValidaComboEnter(cSearch, cField, cMsg){
    var pattern;
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    //Caso o usuário tenha digitado o item completo, então vai para o próximo campo
    if((cField.options.selectedIndex ==-1) && (keycode == 13) && (cSearch.value != "")){
	    alert(cMsg)
	    cSearch.value = "";
	    cSearch.focus();
    }
}

//Abre a combo apontada
function fAbreCombo(cCxTexto, cDivInf, cComboDados, oNextObjectFocus){
    var keycode;
    //Caso a ação tenha sido solicitada por click de botão
    if (window.event == null){
	    keycode = 38;
    }
    else{	
	    keycode = ((window.event.type == "click") ? 40: window.event.keyCode);
    }
    if (cComboDados.options.length == 0) return false;
    //Move o registro da combo para baixo e visualiza a combo
    if (keycode == 40){
	    if (cDivInf.style.visibility=="visible"){
		    if (cComboDados.options.length > cComboDados.options.selectedIndex+1){
			    cComboDados.options.selectedIndex = cComboDados.options.selectedIndex + 1;
		    }
	    }
	    fVisibleDiv(cDivInf, cCxTexto, cComboDados,true);
    }
    //Move o registro da combo para cima e visualiza a combo
    if (keycode == 38){
	    if (cDivInf.style.visibility=="visible"){
		    if (cComboDados.options.selectedIndex > 0){
			    cComboDados.options.selectedIndex = cComboDados.options.selectedIndex - 1;
		    }
	    }
	    fVisibleDiv(cDivInf, cCxTexto, cComboDados, true);
    }
    //Traz os registro da combo para a caixa de texto
    if ((keycode == 13) || (keycode == 9)){
	    if (cComboDados.options.selectedIndex != -1){
		    if (isNaN(cCxTexto.value) == false){
			    cCxTexto.value = cComboDados.options[cComboDados.options.selectedIndex].text;
			    cDivInf.style.visibility="hidden";
		    }
		    else if((cDivInf.style.visibility=="visible") && (cComboDados.options.selectedIndex != -1)){
			    cCxTexto.value = cComboDados.options[cComboDados.options.selectedIndex].text;
				
			    //Fecha a combo e posiciona o cursor para o próximo objeto
			    if (keycode == 13){
				    fFechaCombo(cCxTexto, cDivInf, cComboDados);
				    //oNextObjectFocus.focus();
				    //oNextObjectFocus.select();
			    }
		    }
	    }
    }
    //Cancela a ação(Esc)
    if(keycode == 27){
	    cDivInf.style.visibility="hidden";
	    cCxTexto.value ="";
	    cCxTexto.focus;
    }
}

//Fecha a combo apontada
function fFechaCombo(cCxTexto, cDivInf, cComboDados){
    if (cComboDados.options.selectedIndex != -1){
	    if ((cCxTexto.value != cComboDados.options[cComboDados.options.selectedIndex].text) && (cDivInf.style.visibility!="visible")){
		    fVisibleDiv(cDivInf, cCxTexto, cComboDados,true);
		    cCxTexto.focus();
	    }
	    else{
		    cCxTexto.value = cComboDados.options[cComboDados.options.selectedIndex].text;
		    cDivInf.style.visibility="hidden";
	    }
    }
    else if((cComboDados.options.selectedIndex == -1) && (cDivInf.style.visibility!="visible") && (cCxTexto.value != "")){
	    fVisibleDiv(cDivInf, cCxTexto, cComboDados,true);
	    cCxTexto.focus();
    }
    else if((cComboDados.options.selectedIndex == -1) && (cDivInf.style.visibility=="visible")){
	    cDivInf.style.visibility="hidden";
	    cCxTexto.value="";
    }
}

//ResetCor();
function fOutputColor(oID) {
    //oID: id do objeto que receberá mudança de cor
    oID.style.backgroundColor = "white";
}

//Aponta a cor na caixa de texto quando estiver em foco
function InputColor(oID) {
    //oID: id do objeto que receberá mudança de cor
    oID.style.backgroundColor = "#ffff99";
}

//exibe um div explicativo do campo (tooltip)
function fShowInfoProcedimento(oObj){
	if (oObj.title!=""){
	    document.all.idLinhaMensagem.innerHTML = oObj.title + "&nbsp;"
		fVisibleDiv(document.all.divToolTip,oObj,"",true);
	}
	else{
		document.all.divToolTip.style.visibility = "hidden";
	}
}

// Verificar qual navegador
function fQualNavegador(){
	var cAux = navigator.userAgent.toLowerCase();
	var cNome = navigator.appName;	
	if(cAux.indexOf('safari')!= -1)
		return "SA";	
	if ( cNome == "Microsoft Internet Explorer" )
		return "IE";
	else if ( cNome == "Netscape" )
		return "NE";
	else
		return "";
}

//Posiciona o objeto no meio do browser
function fPosBrowser(oObject){
	var iTop = 0;
	var iLeft = 0;
	//Nível 1
	iTop = oObject.offsetTop;
	iLeft = oObject.offsetLeft;
	var cParent = "";
	//Loop dos níveis
	for(i=0;i<20;i++){
		cParent = cParent + ".offsetParent"
		var oObj = eval("oObject" + cParent);
		if(oObj == null){
			break;
		}

		//Soma a posição do nivel atual com o anterir
		iTop = iTop + oObj.offsetTop;
		iLeft = iLeft + oObj.offsetLeft;
	}		
	window.scroll(0,iTop - (document.body.clientHeight / 2)+100);
}


// ***************** VALIDAÇÃO DE DADOS ***************** 
//Somente digita S ou N(Sim ou Nao)
function fValidaSimNao(evnt, ctrl, oNextObj){
	var tk;
	var c;
	var valor = ctrl.value;
	// Recebe a tecla pressionada
	tk = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
	c=String.fromCharCode(tk);
	c=c.toUpperCase();	
	if (tk == 8 && ctrl.value.length > 1) ctrl.value="";
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
	if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;		
	//Somente S ou N
	if (tk!=115 && tk!=83 && tk!=110 && tk!=78)
		return false;
	if (tk==115 || tk==83){
		ctrl.value = "SIM";
	}
	else{
		ctrl.value = "NAO";
	}
	oNextObj.focus();
	return false;
	oNextObj.select();
}

// validação de tipos comuns de campos
// sintaxe: na tag <input> incluir: onblur='cValida( this, iTipo, lRetVal );'
// iTipo: 0-texto  1-e-mail  2-numérico  3-data  4-placa  5-chassi (0-9 A-Z)
//        6-cpf/cgc  7-dígitos (0 a 9)  8-sem acentos
// lRetVal: true-retorna cValor formatado  false:retorna true ou false para válido ou inválido
function cValida( oControle, iTipo, iRetVal ) {
    var cValor = oControle.value, cMsg = "", lValido = false;
    if ( typeof( iRetVal ) == "undefined" ) { var iRet = 1; } else { var iRet = iRetVal; }
    if ( typeof( iTipo ) == "undefined" ) { iTipo = 0; }
    if ( cValor != "" ) {
        switch ( iTipo ) {
            case 0:
                cValor = cValidaTexto( cValor );
                if ( cValor == "" ) { cMsg = "texto inválido !"; } else { lValido = true; }
                break;
            case 1:
                cValor = cValidaEmail( cValor );
                if ( cValor == "" ) { cMsg = "e-mail inválido !"; } else { lValido = true; }
                break;
            case 2:
                cValor = cValidaNumerico( cValor );
                if ( cValor == "" ) { cMsg = "número inválido !"; } else { lValido = true; }
                break;
            case 3:
                cValor = cValidaData( cValor );
                if ( cValor == "" ) { cMsg = "data inválida !"; } else { lValido = true; }
                break;
            case 4:
                cValor = cValidaPlaca( cValor );
                if ( cJavaTrimUC(cValor) == "" ) { cMsg = "placa inválida !"; } else { lValido = true; }
                break;
            case 5:
                cValor = cValidaChassi( cValor );
                if ( cValor == "" ) { cMsg = "chassi inválido !"; } else { lValido = true; }
                break;
            case 6:
				//cValor = cValor.toString().substring(0,3) + cValor.toString().substring(4,7) + cValor.toString().substring(8,11) + cValor.toString().substring(12,14) ;
                cValor = cValidaCPFCGC( cValor );
                if ( cValor == "" ) { cMsg = "CPF / CNPJ inválido !"; } else { lValido = true; }
                break;
            case 7:
                cValor = cValidaDigitos( cValor );
                if ( cValor == "" ) { cMsg = "número inválido.\ndigite somente dígitos de 0 a 9 sem espaços!"; } else { lValido = true; }
                break;
            case 8:
                cValor = cValidaAcento( cValor );
                lValido = true;
                break;
        }
        if ( lValido ) {
            if ( iRet == 1 ) { oControle.value = cValor; } else { return true; }
        }
        else {
            if ( iRet == 1 ) {
                alert( cMsg );
                oControle.select();
                oControle.focus();
            }
            else {
                return false;
            }
        }
    }
}

// função complementar à cValida(), retira espaçoes em branco e converte em maiúsculas
function cValidaTexto( cTexto ) {
    return cJavaTrimUC( cTexto );
}

// função complementar à cValida() para validar e-mail's
function cValidaEmail( cEmail ) {
    var iArr = 0, cRet = "";
    cEmail = cJavaTrimUC( cEmail );
    cEmail = cEmail.toLowerCase();
    if ( cEmail.indexOf( "@" ) > 0 && cEmail.indexOf( "@" ) < cEmail.length - 1 ) {
        if ( cEmail.length > 4 ) {
            if( cEmail.indexOf( "www." ) == -1 ) {
                cRet = cEmail;
            }
        }
    }
    return cRet;
}

// função complementar à cValida() para validar campos numéricos
function cValidaNumerico( cNumero ) {
    var lNum = true, iErr = 0;
    cNumero = cJavaTrimUC( cNumero );
    // verifica se todos os dígitos são válidos
    for ( i = 0; i < cNumero.length; i++ ) {
        if ( "0123456789.,-".indexOf( cNumero.substring( i, i + 1 ) ) < 0 ) {
            lNum = false;
        }
    }
    // verifica se só foi digitado um sinal ou um ponto
    if ( cNumero == "-" || cNumero == "." || cNumero == "-." || cNumero == ".-" || cNumero == ",") { lNum = false; }
    if ( lNum == true ) {
        // verifica a posição e quantidade do sinal de negativo (-) caso haja
        for ( i = 0; i < cNumero.length; i++ ) {
            if ( "-".indexOf( cNumero.substring( i, i + 1 ) ) > -1 ) {
                iErr = i;
            }
        }
        if ( iErr <= 0 ) {
            // verifica a posição e quantidade de pontos (.)
            iErr = 0;
            for ( i = 0; i < cNumero.length; i++ ) {
                if ( ".".indexOf( cNumero.substring( i, i + 1 ) ) > -1 ) {
                    iErr++;
                }
            }
            if ( iErr > 1 ) { lNum = false; }
        }
        else {
            lNum = false;
        }
    }
    if ( !lNum ) { return ""; } else { return cNumero; }
}

// função complementar à cValida() para validar chassi
// 0-9 e A-Z sem pontos, traços, etc e tamanho = 17 ou 14 ou <=12
function cValidaChassi( cChassi ) {
    var lChas = true;
    var iNum = 0;
    cChassi = cJavaTrimUC( cChassi )
    // verifica se todos os dígitos são válidos
    for ( i = 0; i < cChassi.length; i++ ) {
        if ( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( cChassi.substring( i, i + 1 ) ) < 0 ) {
            lChas = false;
        }
    }
    // verifica se, ao menos tres digitos são numéricos (0 a 9)
    for ( i = 0; i < cChassi.length; i++ ) {
        if ( "0123456789".indexOf( cChassi.substring( i, i + 1 ) ) >= 0 ) {
            iNum = iNum + 1;
        }
    }
    if( iNum < 3 ) { lChas = false; }
    // verifica o tamanho da string
    if( lChas ) {
        if( cChassi.length != 17 && ( cChassi.length > 14 || cChassi.length < 3 ) ) {
            lChas = false;
        }
    }
    if ( !lChas ) {
        // alert( "Chassi inválido\nPor favor digite somente números de 0 a 9 ou\nletras de A a Z sem pontos, traços ou separadores !" );
        return "";
    }
    else {
        return cChassi;
    }
}

// função complementar à cValida() para validar campos somente numéricos (sem pontos, traços, etc)
function cValidaDigitos( cNumero ) {
    var lNum = true;
    cNumero = cJavaTrimUC( cNumero )
    // verifica se todos os dígitos são válidos
    for ( i = 0; i < cNumero.length; i++ ) {
        if ( "0123456789".indexOf( cNumero.substring( i, i + 1 ) ) < 0 ) {
            lNum = false;
        }
    }
    if ( !lNum ) {
        // alert( "por favor digite somente números de 0 a 9 sem pontos, traços ou separadores !" );
        return "";
    }
    else {
        return cNumero;
    }
}

// função para validar campos somente caracteres e numéricos (sem pontos, traços, etc)
function cValidaCharNum( cTexto ) {
    var lNum = true;
    cTexto = cJavaTrimUC( cTexto )
    // verifica se todos os dígitos são válidos
    for ( i = 0; i < cTexto.length; i++ ) {
        if ( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( cTexto.substring( i, i + 1 ) ) < 0 ) {
            lNum = false;
        }
    }
    if ( !lNum ) {
        // alert( "por favor digite somente números de 0 a 9 sem pontos, traços ou separadores !" );
        return "";
    }
    else {
        return cTexto;
    }
}

// função complementar à cValida() para validar e formatar datas (dd/mm/aaaa)
function cValidaData( cData ) {
    var iD1, iD2, iDia, iMes, iAno, cAno, lData = false; lMes = true;
    cData = cJavaTrim( cData );
    iD1 = cData.indexOf( "/" );
    if ( iD1 > 0 && iD1 + 1 < cData.length ) {
        iD2 = cData.indexOf( "/", iD1 + 1 );
    }
    if ( iD1 > 0 && iD2 > 0 && iD2 + 1 <= cData.length ) {
        iDia = parseInt( parseFloat( cData.substring( 0, iD1 ) ) );
        iMes = parseInt( parseFloat( cData.substring( iD1 + 1, iD2 ) ) );
        cAno = cData.substring( iD2 + 1, cData.length );
        iAno = parseInt( parseFloat( cAno ) );
        if ( iDia > 0 && iDia < 32 && iMes > 0 && iMes < 13 && iAno < 2100 && ( iAno > 0 || cAno == "0" || cAno == "00" || cAno == "000" ) ) {
            if ( iAno < 100 ) {
                if ( iAno > 30 ) { iAno = parseInt( iAno ) + 1900; } else { iAno = parseInt( iAno ) + 2000; }
            }
            if ( iAno >= 1900 ) {
                if ( ( iMes == 2 || iMes == 4 || iMes == 6 || iMes == 9 || iMes == 11 ) ) {
                    if ( iMes == 2 ) {
                        if ( iAno % 4 != 0 ) { if ( iDia > 28 ) { lMes = false; } }
                        else { if ( iDia > 29 ) { lMes = false; } }
                    }
                    else { if ( iDia > 30 ) { lMes = false; } }
                }
                if ( lMes ) {
                    lData = true;
                    if ( iDia < 10 ) { iDia = "0" + iDia; }
                    if ( iMes < 10 ) { iMes = "0" + iMes; }
                    return ( iDia + "/" + iMes + "/" + iAno );
                }
            }
        }
    }
    if ( !lData ) {
        return "";
    }
}

// função complementar à cValida() para validar placas de veículos
function cValidaPlaca( cPlaca ) {
    var lPlaca = false;
    cPlaca = cJavaTrimUC( cPlaca );
    if ( cPlaca.length == 6 || cPlaca.length == 7 || cPlaca.length == 5) {
        if ( cPlaca.length == 6 ) {
            var cLetras = cPlaca.substring( 0, 2 );
            var cNumeros = cPlaca.substring( 2, 6 );
        }
        else if ( cPlaca.length == 5 ) {
            var cLetras = cPlaca.substring( 0, 2 );
            var cNumeros = cPlaca.substring( 2, 5 );
        }        
        else {
            var cLetras = cPlaca.substring( 0, 3 );
            var cNumeros = cPlaca.substring( 3, 7 );
        }
        lPlaca = true;
        for ( i = 0; i < cLetras.length; i++ ) {
            if ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf( cLetras.substring( i, i + 1 ) ) < 0 ) {
                lPlaca = false;
            }
        }
        for ( i = 0; i < cNumeros.length; i++ ) {
            if ( "0123456789".indexOf( cNumeros.substring( i, i + 1 ) ) < 0 ) {
                lPlaca = false;
            }
        }
    }
    if ( !lPlaca ) { return ""; } else { return cPlaca; }
}

// função complementar à cValida() para validar CPF's e CGC's
// função complementar à Valida() para validar CPF's e CGC's
function cValidaCPFCGC( cCPFCGC ) {
    cCPFCGC = cJavaTrimUC( cCPFCGC );
    // verifica se é CPF valido ( 11 dígitos )
    if ( cCPFCGC.length == 11 ) {
        var nDig1 = 0, nDig2 = 0, lVal = false;
        // verifica se não é repetição de números ( 11111111111, 22222222222, etc )
        for ( i = 0; i < 11; i++ ) {
            if ( cCPFCGC.substring( i, i + 1 ) != cCPFCGC.substring( 0, 1 ) ) { lVal = true; }
        }
        for ( i = 10; i > 1; i-- ) {
            nDig1 += parseInt( cCPFCGC.substring( 10 - i, 11 - i ) ) * i;
        }
        for ( i = 11; i > 1; i-- ) {
            nDig2 += parseInt( cCPFCGC.substring( 11 - i, 12 - i ) ) * i;
        }
        nDig1 = ( nDig1 * 10 ) % 11;
        nDig2 = ( nDig2 * 10 ) % 11;
        if ( nDig1 == 10 ) { nDig1 = 0; }
        if ( nDig2 == 10 ) { nDig2 = 0; }
        if ( nDig1 != cCPFCGC.substring( 9, 10 ) || nDig2 != cCPFCGC.substring( 10, 11 ) || !lVal ) {
            // alert( "CPF inválido" );
            return "";
        }
        else {
            return cCPFCGC;
        }
    }
    else {
        // verifica se é CGC valido ( 14 dígitos )
        if ( cCPFCGC.length == 14 ) {
            var nMult1 = "543298765432", nMult2 = "6543298765432", nDig1 = 0, nDig2 = 0, lVal = false;
            for ( i = 0; i < 12; i++ ) {
                nDig1 += parseInt( cCPFCGC.substring( i, i + 1 ) ) * parseInt( nMult1.substring( i, i + 1 ) );
            }
            for ( i = 0; i < 13; i++ ) {
                nDig2 += parseInt( cCPFCGC.substring( i, i + 1 ) ) * parseInt( nMult2.substring( i, i + 1 ) );
            }
            nDig1 = ( nDig1 * 10 ) % 11;
            nDig2 = ( nDig2 * 10 ) % 11;
            if ( nDig1 == 10 ) { nDig1 = 0; }
            if ( nDig2 == 10 ) { nDig2 = 0; }
            if ( nDig1 != cCPFCGC.substring( 12, 13 ) || nDig2 != cCPFCGC.substring( 13, 14 ) ) {
                return "";
            }
            else {
                return cCPFCGC;
            }
        }
        else {
            return "";
        }
    }
}

// função complementar a cValida() para remover acentos e caracteres especiais
function cValidaAcento( cTexto ) {
    var cNew = "", iAux = 0;
    cTexto = cTexto.toLowerCase();
    for ( i = 0; i < cTexto.length; i++ ) {
        iAux = "áàãäâéèëêíìïîóòõöôúùüûýñç".indexOf( cTexto.substring( i, i + 1 ) );
        if ( iAux < 0 ) {
            cNew += cTexto.substring( i, i + 1 );
        }
        else {
            cNew += "aaaaaeeeeiiiiooooouuuuync".substring( iAux, iAux + 1 );
        }
    }
    return( cNew.toUpperCase() );
}

function cValidaCPF() {
    cCPF = document.validacao.cpfID.value;
    cErro = new String;
    if (cCPF.length < 11) cErro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
    var nonNumbers = /\D/;
    if (nonNumbers.test(cCPF)) cErro += "A verificacao de CPF suporta apenas numeros! \n\n"; 
    if (cCPF == "00000000000" || cCPF == "11111111111" || cCPF == "22222222222" || cCPF == "33333333333" || cCPF == "44444444444" || cCPF == "55555555555" || cCPF == "66666666666" || cCPF == "77777777777" || cCPF == "88888888888" || cCPF == "99999999999"){
         cErro += "Numero de CPF invalido!"
    }
    var a = [];
    var b = new Number;
    var c = 11;
    for (i = 0; i < 11; i++){
       a[i] = cCPF.charAt(i);
       if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
    b = 0;
    c = 11;
    for (y=0; y<10; y++) b += (a[y] * c--); 
    if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
    if ((cCPF.charAt(9) != a[9]) || (cCPF.charAt(10) != a[10])){
       cErro +="Digito verificador com problema!";
    }
    if (cErro.length > 0){
       alert(cErro);
       return false;
    }
    return true;
}

function fToInteger(cCheckString) {
var cNewString = "";    
var iCount = 0;         
    for (i = 0; i < cCheckString.length; i++) {
        ch = cCheckString.substring(i, i+1);
        if (ch >= "0" && ch <= "9") 
        {
            cNewString += ch;
        }
        else
        {
         if (ch == "-") cNewString += ch;
         if (ch == ".") cNewString += ch;
         if (ch == "/") cNewString += ch;
        }
    }
    return cNewString; //cCheckString;
}

function fFormataDataBarra(campo){
   if(campo.value.length==2){
      campo.value = campo.value + "/"
      campo.focus();
   }
   if(campo.value.length==5){
      campo.value = campo.value + "/"
      campo.focus();
   }
}

function fDigitarHora(cCampo){
    var cReturn="";
    cReturn = fFormataHoraDoisPontos(cCampo);
    cReturn = fDigitarNumero(event,cCampo);
    return cReturn;
}

function fFormataHoraDoisPontos(campo){
   if(campo.value.length==2){
      campo.value = campo.value + ":"
      campo.focus();
   }
}

var reTime1 = /^\d{2}:\d{2}$/;
var reTime2 = /^([0-1]\d|2[0-3]):[0-5]\d$/;
var reTime3 = /^(0[1-9]|1[0-2]):[0-5]\d$/;
var reTime4 = /^\d+:[0-5]\d:[0-5]\d$/;
var reTime5 = /^\d+:[0-5]\d:[0-5]\.\d{3}\d$/;

function fValidarTime(pStr, pFmt){
	eval("reTime = reTime" + pFmt);
	if (reTime.test(pStr.value)) {
	} else if (pStr.value != null && pStr.value != "") {
		alert(pStr.value + " Horário Inválido !");
		pStr.focus();
		return "";
	}
}

function fCompararHoras(oHoraIni, oHoraFim){
    cHoraInicio = oHoraIni.value;
    iHoraInicio = cHoraInicio.substring(0,2);
    cHoraFim = oHoraFim.value;
    iHoraFim = cHoraFim.substring(0,2);                
    if (iHoraInicio != iHoraFim){
        if (iHoraInicio > iHoraFim){
            alert ("Horário de Abertura é superior ao horário de fechamento");
            oHoraIni.focus();
            return false;
        }
        return true;
    }
    cMinInicio = oHoraIni.value;
    iMinInicio = cMinInicio.substring(3,5);
    cMinFim = oHoraFim.value;
    iMinFim = cMinFim.substring(3,5);
    if (iMinInicio != iMinFim){
        if (iMinInicio > iMinFim){
            alert("Horário de Abertura é superior ao horário de fechamento");
            oHoraIni.focus();
            return false;
        }
        return true;
    }
}

function cMascaraData (cFormato, cKeyPress, cObjeto) {
	campo = eval (objeto1);
	if (campo.value == '00/00/0000') {campo.value=""}
	if (cFormato=='txtDataPrevRealizacao') {
		cCaracteres = '01234567890';
		iSeparacoes = 2;
		cSeparacao1 = '/';
		cSeparacao2 = '/';
		iConjuntos = 2;
		iConjunto1 = 2;
		iConjunto2 = 5;
		if ((cKeyPress > 47 && cKeyPress < 58) && campo.value.length < 
		(iConjunto1 + iConjunto2 + 3)) {
			if (campo.value.length == iConjunto1) 
			   campo.value = campo.value + cSeparacao1;
			if (campo.value.length == iConjunto2) 
			   campo.value = campo.value + cSeparacao2;
			}
		else 
			event.returnValue = false;
	}
}

//Só aceita valor monetário no campo apontado
//*******************************************
function fDigitarMonetario(evnt,ctrl){
	var tk;
    var c;
	var valor = ctrl.value;
	
	// Recebe a tecla pressionada
	tk = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
    c=String.fromCharCode(tk);
	c=c.toUpperCase();	
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;		
	//somente números e ","		
	if ( (c<"0" || c>"9") && (c!=","))
		return false;
	//virgula no começo -- se já existir "," e sem valor
	if ( (c==",") && ((valor.search(",")>-1) || (valor.length==0)) )
		return false;			
}

function fDigitarNumero(evnt,ctrl){
var tk;
var c;
var valor = ctrl.value;
	// Recebe a tecla pressionada
	tk = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
    c = String.fromCharCode(tk);
	c = c.toUpperCase();	
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;		
	//somente números
	if ((c<"0" || c>"9"))
		return false;
}

function fDigitarCharNumero(evnt,ctrl){
var tk;
var c;
var valor = ctrl.value;
	// Recebe a tecla pressionada
	tk = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
    c = String.fromCharCode(tk);
	c = c.toUpperCase();	
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;		
	//somente números
    if ( "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ@".indexOf( c ) < 0 ) {
        return false;
    }
}

function fDigitarNumeroPosNeg(evnt,ctrl){
var tk;
var c;
var valor = ctrl.value;
	// Recebe a tecla pressionada
	tk = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
    c = String.fromCharCode(tk);
	c = c.toUpperCase();	
    //alert (c);
	//return false;

	// Só aceita teclas numéricas. Aceita teclas de controle + ou -
    if ( tk >= 48 && tk <=57 || tk == 45)
		return true;
    if ( "0123456789-".indexOf( c ) < 0 ) {
        return false;
    }
}


function cChecaData( cData, iOpc ) {
	//valida data
	//iOpc = 0: não permite data digitada seja Maior ou igual a data corrente
	//iOpc = 1: não permite data digitada seja Menor que a data corrente
	var d, cVerData = "", cVerDataCorrente = "";
	d = new Date();
	if (cData.length == 10) {
		cVerData = cValidaData(cData);
		cVerDataCorrente = cValidaData(d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getYear())
		cVerData = cData2(cVerData)
		cVerDataCorrente = cData2(cVerDataCorrente)
		if (cValidaData(cData)) {
		    if (iOpc == 0) {
			    //data válida, deve ser menor que data atual
			    if (parseInt(cVerData) >= parseInt(cVerDataCorrente)) {
				    return( false );
			    }
			    else {
				    if ((parseInt(event.keyCode) >= 96 && parseInt(event.keyCode) <= 105) || (parseInt(event.keyCode) == 111)) {
					    alert('Data não pode ser anterior a data atual !');
					    return( true );
				    }
			    }
	        }
	        else if (iOpc == 1){ 
			    //data inválida se se for maior que data atual
			    if (parseInt(cVerData) > parseInt(cVerDataCorrente)) {
				    return( '' );
			    }
	        }
		}
		else {
			alert('Data inválida !');
			return( true );		
		}
	}
	return( true );
}

//retorna os valores de um control (combo) com valores múltiplos
function fGetSelectValues(oControl, lRetirarSelecao){
    var cResult = "";
    //Control.length = false;
    for(var i = 0;i < oControl.length;i++){
        if(oControl.options[i].selected){
            if (lRetirarSelecao) {
                oControl.options[i].selected = false;
            }
            else {
                cResult = cResult + oControl.options[i].value + "," ;
            }
        }
    }
    cResult = cResult
    return cResult;
}

//retorna os valores de um control (combo) com valores múltiplos
function fGetValuesComboMultiple(oControl){
    var cResult = "";
    //Control.length = false;
    for(var i = 0;i < oControl.length;i++){
        cResult = cResult + oControl.options[i].value + "," ;
    }
    return cResult;
}

// Remove espaços em branco à direita e à esquerda de cExpr
function cJavaTrim( cExpr ) {
    cExpr = cJavaLTrim( cExpr );
    cExpr = cJavaRTrim( cExpr );
    return cExpr;
}

// Remove espaços em branco à esquerda de cExpr
function cJavaLTrim( cExpr ) {
    var iSpc;
    cExpr = cExpr.toString();
    iSpc = cExpr.length;
    for ( i = 0; i < cExpr.length; i++ ) {
        if ( cExpr.substr( i, 1 ) != " " ) { iSpc = i; i = cExpr.length; }
    }
    cExpr = cExpr.substring( iSpc, cExpr.length );
    return cExpr;
}

// Remove espaços em branco à direita de cExpr
function cJavaRTrim( cExpr ) {
    var iSpc;
    cExpr = cExpr.toString();
    iSpc = 0;
    for ( i = cExpr.length - 1; i >= 0; i-- ) {
        if ( cExpr.substr( i, 1 ) != " " ) { iSpc = i; i = 0; }
    }
    cExpr = cExpr.substring( 0, iSpc + 1 );
    return cExpr;
}

// Remove espaços e converte para maiúsculas
function cJavaTrimUC( cExpr ) {
    return cJavaTrim( cExpr.toUpperCase() );
}

// converte yyyymmdd em dd/mm/yyyy
function cData1( cTexto ) {
    return cTexto.substring( 6, 8 ) + "/" + cTexto.substring( 4, 6 ) + "/" + cTexto.substring( 0, 4 );
}

// converte dd/mm/yyyy em yyyymmdd
function cData2( cTexto ) {
    return cTexto.substring( 6, 10 ) + cTexto.substring( 3, 5 ) + cTexto.substring( 0, 2 );
}

//Retorna Data corrente em Javascript formato dd/mm/yyyy
//Parâmetro lRetornaHora = true retorna a parte de horário também (hh:mm:ss)
function fDataCorrente (lRetornaHora) {
	cDataAtual = new Date() 
	cDia = cDataAtual.getDate() 
	cMes = cDataAtual.getMonth() + 1 
	cAno = cDataAtual.getYear() 
	cHora = cDataAtual.getHours() 
	cMin = cDataAtual.getMinutes() 
	cSeg = cDataAtual.getSeconds() 
	cData = ((cDia < 10) ? "0" + cDia + "/" : cDia + "/") 
	cData += ((cMes < 10) ? "0" + cMes + "/" + cAno : cMes + "/" + cAno) 
    if (lRetornaHora) {
    	cHoraAtual = ((cHora < 10) ? "0" + cHora + ":" : cHora + ":") 
    	cHoraAtual += ((cMin < 10) ? "0" + cMin + ":" : cMin + ":") 
    	cHoraAtual += ((cSeg < 10) ? "0" + cSeg : cSeg) 
        cData += ' ' + cHoraAtual
    }
    return cData;
}

//Retorna Hora corrente em Javascript formato hh:mm
function fHoraCorrente () {
	cDataAtual = new Date() 
	cHora = cDataAtual.getHours() 
	cMin = cDataAtual.getMinutes() 
	cSeg = cDataAtual.getSeconds() 
	cHoraAtual = ((cHora < 10) ? "0" + cHora + ":" : cHora + ":") 
	cHoraAtual += ((cMin < 10) ? "0" + cMin : cMin ) 
	//+ ":" 
	//cHoraAtual += ((cSeg < 10) ? "0" + cSeg : cSeg) 
    return cHoraAtual;
}

function cReplaceVirgPonto( cExpr ) {
    var cPonto, cRet, cRet1;
    cExpr = cExpr.toString();
    cRet = cExpr.replace(",", ".");
    return cRet;
}

function Replace(String, find, replace){
	out = find;
	add = replace;
	NovaString = "";
	StringRestante = String;
	while(String.indexOf(out)>-1){
		NovaString += StringRestante.substring(0, ((StringRestante.indexOf(replace)> -1) ? StringRestante.indexOf(replace)+replace.length:0));
		StringRestante = StringRestante.substring((StringRestante.indexOf(replace)==-1) ? StringRestante : StringRestante.indexOf(replace) + replace.length);
		if (StringRestante.indexOf(out)==-1){
			 NovaString += StringRestante;
			 break;
		}
		else{
			pos = StringRestante.indexOf(out);
			StringRestante = (StringRestante.substring(0, pos) + add + StringRestante.substring((pos + out.length), StringRestante.length));		
		}
	}
	return NovaString;
}

//função para trocar um caracter por outro
function fTrocaCaracteres(cEntrada, cCharAPesquisar, cCharATrocar) {
    //cEntrada: string a ter caracteres trocados
    //cCharAPesquisar: caracter a ser pesquisado para ser alterado
    //cCharATrocar: caracter a ser trocado pelo pesquisado
    cRetorno = "" + cEntrada; // temporary holder
    while (cRetorno.indexOf(cCharAPesquisar)>-1) {
        pos= cRetorno.indexOf(cCharAPesquisar);
        cRetorno = "" + (cRetorno.substring(0, pos) + cCharATrocar + 
            cRetorno.substring((pos + cCharAPesquisar.length), cRetorno.length));
    }
    return cRetorno;
}

//código para esconder links de href nas páginas
//função que esconde mensagem da status bar do browser
function fHideStatus(){
    window.status=''
    return true
}
if (document.layers)
    document.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT)
    document.onmouseover = fHideStatus
    document.onmouseout = fHideStatus


function cMsg( cTexto ) {
    window.status = cTexto;
}

// abre nova janela, tipo pop-up, com parâmetro cParam para configurações de exibição
function fNovaJanela( cPagina, cParam ) {
    //"top=0,left=0,scrollbars=yes"
    window.open( cPagina, "_blank", cParam );
}

//limpa cObjeto HTML do form
function fLimpaConteudo( cForm, oItem  ) {
	document[ cForm ][ oItem ].value = "";
}
//foco em objeto passado por parâmetro se pressionado TAB
function fProxFocus( cObjeto ){
	if (event.keyCode == 9) {
		//9 = TAB
		document[ cForm ][ cObjeto ].focus();
		event.returnValue = false;
	}
}    

//foco em objeto passado por parâmetro
function fFocus( cObjetoFocus ) {
	//foca cObjeto passado como parâmetro
	cObjetoFocus.focus();
}

//abre janela de impressão
function fImpressora() {
    window.print();
}

// ***************** FUNÇÕES DE FORMATAÇÃO NUMÉRICA ***************** 
// formata máscara numérica
function fFmtCurrency(cNumero,iTipoFormato){       
    var cValAux='';
    var cMinus='';
    var cDecimal='';
    cDecimal = fGetDecimalDelimiter(iTipoFormato);
    if (cNumero.lastIndexOf("-") == 0) { cMinus='-'; }
    if (cNumero.lastIndexOf(cDecimal) < 0) { cNumero = cNumero + '00'; }
    cNumero = fFmtClean(cNumero);
    cValAux = cMinus + fFmtMonet(cNumero,fGetCommaDelimiter(iTipoFormato)) + 
        fGetDecimalDelimiter(iTipoFormato) + fFmtCents(cNumero);
    return cValAux;
}

function fFmtMonet(cValor,cDelimitaVirgula){
    try {
        cValor = parseInt(cValor);
        var scValor = new String(cValor);
        if (scValor.length < 3) { return 0; }  
        scValor =  scValor.substring(0,scValor.length -2);
        for (var i = 0; i < Math.floor((scValor.length-(1+i))/3); i++){
           scValor = scValor.substring(0,scValor.length-(4*i+3)) + cDelimitaVirgula + scValor.substring(scValor.length-(4*i+3));
         }
        }
    catch (exception) { AlertError("Format Comma",e); }
    return scValor;
}

function fGetDecimalDelimiter(iTipoFormato){
    var cRetorno='';
    switch (iTipoFormato){
        case 3:   
           cRetorno = '#';
           break;
        case 2:   
           cRetorno = ',';
           break;
        default:
           cRetorno = '.';
           break;
    }
    return cRetorno;
}

function fFmtClean(cNumero){
   var cVal='';
   var iVal = cNumero.length;
   var cCharAux='';
   try{
       for(i=0;i<iVal;i++){
         cCharAux = cNumero.charAt(i);
         nChar = cCharAux.charCodeAt(0);
         if ((nChar >=48) && (nChar <=57))  { cVal += cNumero.charAt(i);   }
      }
   }
    catch (exception) { AlertError("Format Clean",e); }
    return cVal;
}

function fGetCommaDelimiter(iTipoFormato){
   var cRetorno='';
   switch (iTipoFormato){
   case 3:   
       cRetorno = '*';
       break;
   case 2:   
       cRetorno = ',';
       break;
   default:
       cRetorno = ',';
       break;
    }
  return cRetorno;
}

function fFmtCents(cValor){
    var cCents = '';
    try {
       cValor = parseInt(cValor);
       var acValor = new String(cValor);
       if (acValor.length == 0) { return '00'; }
       if (acValor.length == 1) { return '0' + acValor; }
       if (acValor.length == 2) { return acValor; }
       cCents =  acValor.substring(acValor.length -2,acValor.length);
    }
    catch (exception) { AlertError("Format Cents",e); }
    return cCents;
}

function fFmtNumberDecimal(cNumero,iQtdDecimal){
	if (isNaN(cNumero)) { return 0};
	if (cNumero=='') { return 0};
	var acNum = new String(cNumero);
	var cSec = acNum.split('.');
	var cWhole = parseFloat(cSec[0]);
	var cResult = '';
	if(cSec.length > 1){
		var acDec = new String(cSec[1]);
		acDec = String(parseFloat(cSec[1])/Math.pow(10,(acDec.length - iQtdDecimal)));
		acDec = String(cWhole + Math.round(parseFloat(acDec))/Math.pow(10,iQtdDecimal));
		var cPonto = acDec.indexOf('.');
		if(cPonto == -1){
			acDec += '.'; 
			cPonto = acDec.indexOf('.');
		}
		while(acDec.length <= cPonto + iQtdDecimal) { acDec += '0'; }
		cResult = acDec;
	} else{
		var cPonto;
		var acDec = new String(cWhole);
		acDec += '.';
		cPonto = acDec.indexOf('.');
		while(acDec.length <= cPonto + iQtdDecimal) { acDec += '0'; }
		cResult = acDec;
	}	
	return cResult;
}

fFmtValorMilharDecimal = function( n, c, d, t ) {
    if (parseFloat(n)==0){
        return 0;}
    else if (isNaN(n)){ 
        return 0;}
    else if (n == ""){ 
        return 0;}
    else {
        var m = ( c = Math.abs( c ) + 1 ? c : 2, d = d || ",", t = t || ".", /(\d+)(?:(\.\d+)|)/.exec( n + "" ) ), x = m[1].length % 3;
        if (parseFloat(n)>999){
	        return ( x ? m[1].substr( 0, x ) + t : "" ) + m[1].substr( x ).replace( /(\d{3})(?=\d)/g, "$1" + t ) + ( c ? d + ( +m[2] ).toFixed( c ).substr( 2 ) : "" );
        }
        else {
            return ( x ? m[1].substr( 0, x ) : "" ) + m[1].substr( x ).replace( /(\d{3})(?=\d)/g, "$1" + t ) + ( c ? d + ( +m[2] ).toFixed( c ).substr( 2 ) : "" );
        }
    }
};

//retorna cálculo de mValorIni * 100 / mValorSobre
function fPerc(mValorIni, mValorSobre){
    var cValorIni = mValorIni + '';
    var cValorSobre = mValorSobre + '';
    var mValor = 0;
    if ( cValorIni.indexOf(",") != -1){
        mValorIni = fTrocaCaracteres(mValorIni,".","");
        mValorIni = cReplaceVirgPonto(mValorIni);
    }
    if ( cValorSobre.indexOf(",") != -1){
        mValorSobre = fTrocaCaracteres(mValorSobre,".","");
        mValorSobre = cReplaceVirgPonto(mValorSobre);
    }
    mValor = fFmtNumberDecimal( ((parseFloat(mValorIni) * 100) / parseFloat(mValorSobre)) , 2 );
    return mValor;
}

//move foco para próximo campo qdo campo corrente 
//tiver o tamanho máximo de caracteres digitado
function cTabNextFocus(oObj) {
    var cFieldLength = 0;
    var cKeyCode = event.keyCode; 
    cKeyCode = ( (fQualNavegador()=="IE") ? event.keyCode : evnt.which);
    //despreza contagem de caracteres se for pressionado teclas Home e End
    if (cKeyCode == 35 || cKeyCode == 36) return;

    var isNN = (navigator.appName.indexOf("Netscape")!=-1);
        if (oObj.value.length != cFieldLength) {
            cFieldLength = oObj.value.length;
            var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
            if (cFieldLength >= oObj.getAttribute("maxlength") && !fContainsElement(filter,cKeyCode)) {
			    oObj.value = oObj.value.slice(0, cFieldLength);
			    oObj.form[(fGetIndex(oObj)+1) % oObj.form.length].focus();
		    }
        }
        function fGetIndex(oObj) {
    	    var index = -1, i = 0, lFound = false;
    	    var lNextObj = false;
    	    while (i < oObj.form.length-1 && index == -1)
    		    if (oObj.form[i] == oObj && lNextObj == false){
    		        //verifica se próximo campo não está desabilitado, 
    		        //se estiver busca pelo próximo disponível
    			    if (oObj.form[i+1].disabled==false){
    				    index = i;
    				    break;
    			    }
    			    else{
    				    lNextObj = true
    				    i++;
    			    }
    		    }
    		    else if (lNextObj == true){
    			    if (oObj.form[i+1].disabled == false){
    				    index = i;
    				    break;
    			    }
    		    }
    		    else{i++}
    	    return index;
        }
        function fContainsElement(aMatriz, cElemento) {
        var lFound = false, index = 0;
            while(!lFound && index < aMatriz.length)
                if(aMatriz[index] == cElemento)
                    lFound = true;
                else
                    index++;
                return lFound;
        }
}

//move foco para próximo campo qdo campo corrente tiver o tamanho máximo de caracteres digitado
var cFieldLength = 0;
function fTabNext(oObj, event, oFieldNext) {
    var cElement = document.frmMain.elements;
    
    loLen = oObj.getAttribute("maxlength");
    if (event == "down") {
       cFieldLength = oObj.value.length;
    }
    else if (event == "up") {
       if (oObj.value.length != cFieldLength) {
           cFieldLength = oObj.value.length;
           if (cFieldLength == loLen) {
              oFieldNext.focus();
           }
       }
    }
}

//DateDiff JS - Calcula difenrença entre datas 
//por Kleiton Amorim em 15/9/2008
//Obs: As datas são calculadas pelos vetores com descrição em inglês por definição da linguagem
//Obrigatórios:
//      - dData1 -> Formato dd/mm/aaaa
//      - dData2 -> Formato dd/mm/aaaa
//Retorno: Diferença entre datas Positiva, Nula ou Negativa
function fdateDiff(dData1,dData2){
    var cMes, cData, cDataAtual, cDataInfo, aDataInfo1, aDataInfo2, cDiasEntreDatas;

    cMes = [];
    cMes[0] = "January";
    cMes[1] = "February";
    cMes[2] = "March";
    cMes[3] = "April";
    cMes[4] = "May";
    cMes[5] = "June";
    cMes[6] = "July";
    cMes[7] = "August";
    cMes[8] = "September";
    cMes[9] = "October";
    cMes[10] = "November";
    cMes[11] = "December";

// Separa as datas informadas pelo usuário através da barra /
    aDataInfo1 = dData1.split('/');
    aDataInfo2 = dData2.split('/');
    
// Formata as datas para o seguinte formato: Month Day Year
    aDataInfo1 = cMes[(aDataInfo1[1] - 1)] + ' ' + aDataInfo1[0] + ' ' + aDataInfo1[2];
    aDataInfo2 = cMes[(aDataInfo2[1] - 1)] + ' ' + aDataInfo2[0] + ' ' + aDataInfo2[2];

// Retorno com o o total de dias entre as datas informadas pelo usuário
    return (((Date.parse(aDataInfo2))-(Date.parse(aDataInfo1)))/(24*60*60*1000)).toFixed(0);
}