var textoSafra, textoProduto, textoFormSafra, textoFormCultura, textoCultura, textoProdutoVisita, textoVisita, textoAnalisePeriodo, textoProjeto, textoSafraAnterior;
    
textoProjeto =  "Informe o Projeto em que está prestando serviço e o Produtor Rural que<br>";
textoProjeto += "foi visitado. O campo Contato Técnico é preenchido automaticamente e não pode ser alterado.<br>";
textoProjeto += "Caso não encontre o nome do Produtor Rural na lista, o mesmo terá que ser incluído, <br>";
textoProjeto += "clique no botão Cadastrar Produtor.<br>"
textoProjeto += "Clique no botão Salvar para gravar a nova visita, ou no botão Cancelar para abortar a inclusão.<br>"

textoSafra =  "Selecione a Safra clicando sobre a descrição da Safra<br>";
textoSafra += "caso não esteja cadastrada clique em INCLUIR.";  

textoSafra2 =  "Selecione a Safra listada no campo abaixo";

textoFormSafra =  "Escolha uma das Safras listadas no campo.<br>";
textoFormSafra += "Para gravar os dados, clique no botão Salvar.<br>";
textoFormSafra += "Para abortar a inclusão, clique no botão Cancelar.<br>";
textoFormSafra += "Para retornar à tela de Visitas Técnicas, clique no botão Voltar.";

textoCultura =  "Selecione a cultura clicando sobre a descrição da cultura<br>";
textoCultura += "caso não esteja cadastrada clique em INCLUIR.<br>";

textoFormCultura =  "Selecione a cultura listada no campo abaixo<br>";
textoFormCultura += "preencha os respectivos campos<br>";
textoFormCultura += "após clique em SALVAR.";

textoProduto =  "Selecione o produto clicando sobre a descrição da produto<br>";
textoProduto += "caso não esteja cadastrada clique em INCLUIR.<br>";

textoProdutoVisita =  "Selecione o produto na referida listagem abaixo<br>";
textoProdutoVisita += "preencha os respectivos campos<br>";
textoProdutoVisita += "após clique em SALVAR.";

textoVisita =  "Esta é a tela principal da Visita Técnica. Nela é mostrada uma lista com todas as visitas realizadas.<br>";
textoVisita += "Se desejar incluir uma nova visita, clique no botão Inserir.<br>";
textoVisita += "Caso queira alterar, movimentar ou excluir uma visita existente, clique em qualquer campo da<br>";
textoVisita += "visita. Todos os campos são exibidos como link.<br>";
textoVisita += "O botão Produtor Rural exibe os produtores rurais já cadastrados, para consulta e alteração.";

textoSafraAnterior = "É necessário fornecer os dados para a safra anterior e também para a safra atual.";
    
function mensagemInfo(texto, oculta, obj, cmbHidden) {
    var div = document.getElementById("divTexto");
    var cmb;    
    
    
    if (cmbHidden != null) {               
       cmb = document.getElementById(cmbHidden);       
       cmb.style.display= (oculta == 0) ? "" : "none";        
    }
        
    if ( oculta == 1 ) {
        div.style.top = offsetTop( obj );
        div.style.left = offsetLeft( obj ) + 15;            
        div.style.display="";        
        
            
        document.getElementById("lblTexto").innerHTML = texto;
    } else {
        div.style.display = "none";
        
    }
        
} // mensagemInfo

function mensagemInfoDireita(texto, oculta, obj, cmbHidden) {
    var div = document.getElementById("divTexto");
    var cmb;
    if (cmbHidden != null){
       cmb = document.getElementById(cmbHidden);       
       cmb.style.display= (oculta == 0) ? "" : "none";        
    }
    if ( oculta == 1 ) {
        div.style.top = (offsetTop( obj ) + 25) + "px";
        div.style.right = "40px";
        //div.style.left = 40;
        
        div.style.display="";        
        document.getElementById("lblTexto").innerHTML = texto;
    } else {
        div.style.display = "none";
    }
} // mensagemInfo


function offsetLeft(elemento){ 
    x = elemento.offsetLeft; 
        
    for( e=elemento.offsetParent; e; e=e.offsetParent )  
        x += e.offsetLeft; 
        
    return x;
}
    
function offsetTop(elemento){ 

    y = elemento.offsetTop;
        
    for( e=elemento.offsetParent; e; e=e.offsetParent )  
        y += e.offsetTop;
        
    return y;
}


function Trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}

function linkVisitaTecnica(codigoVisitaTecnica) {  
  window.location = "../servlet/Controller?op=retrieve&handle=" + codigoVisitaTecnica + "&nomeClasse=unicampo.base.visita.VisitaBase";
}

function linkSafra(codigoVisitaTecnica, codigoProdutorRural,codigoSafra) {   
   window.location = "../servlet/Controller?codigoProdutorRural=" + codigoProdutorRural + "&op=retrieve&nomeClasse=unicampo.base.visita.VisitaSafraBase&codigoVisitaTecnicaSafra=" + codigoSafra + "&codigoVisitaTecnica=" + codigoVisitaTecnica;
}

function linkCultura(codigoProdutorRural, codigoSafra, codigoVisitaTecnica, codigoCultura) {       
   window.location = "../servlet/Controller?codigoProdutorRural=" + codigoProdutorRural + "&op=retrieve&nomeClasse=unicampo.base.visita.VisitaTecnicaCulturaBase&codigoVisitaTecnicaSafra=" + codigoSafra + "&codigoVisitaTecnica=" + codigoVisitaTecnica + "&codigoVtCultura=" + codigoCultura;    
}

function linkProduto(codigoVisitaTecnica, codigoVtCultura, codigoProjeto, codigoVtSafra, codigoSafra, codigoProdutorRural, codigoVtProduto) {   
   window.location = "../servlet/Controller?codigoVisitaTecnica=" + codigoVisitaTecnica + "&op=retrieve&codigoVtCultura=" + codigoVtCultura + "&nomeClasse=unicampo.base.visita.VisitaTecnicaProdutoBase&codigoProjeto=" + codigoProjeto + "&codigoVtSafra=" + codigoVtSafra + "&codigoSafra=" + codigoSafra + "&codigoProdutorRural=14&codigoVisitaTecnicaProduto=" + codigoVtProduto;    
}


function preparaValor(valor) {
    var result;
    qtdePontos = 0;
     if (valor.indexOf(',') >= 0) { //se tiver vírgula 1.500,00 ou 1500,00
        for (i=0; i < valor.length; i++) {
            if (valor.charAt(i) == '.') {
                valor = valor.replace(valor.charAt(i),"");//.replace(",",".");    
            }
        }    
        result = valor.replace(",",".");
    } else {
        result = valor;
    }  
    return result;
}

function formatarValores(obj) {    
    num = document.getElementById(obj).value;    
    x = 0;
    
    if(num<0) {
        num = Math.abs(num);
        x = 1;
    }
    
    if(isNaN(num)) num = "0";
    
    cents = Math.floor((num*100+0.5)%100);
    num = Math.floor((num*100+0.5)/100).toString();
    
    if(cents < 10) cents = "0" + cents;
    
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+'.'+num.substring(num.length-(4*i+3));   
    ret = num + ',' + cents;  
    if (x == 1) 
        ret = ' - ' + ret;        
    
    document.getElementById(obj).value = ret;   
}
// Função que apaga o conteudo da caixa de texto caso este esteja selecionado
var textoSelecionado = 0;

function on_Select(valor) {
    textoSelecionado = valor;  
}

function FormataValor(campo,tammax) {     
    var tecla = event.keyCode;
    frm = campo.form;
    vr = campo.value;    
    
    if ( textoSelecionado == 1 ){          
        vr = "";   
        textoSelecionado = 0;
    }
    
    vr = vr.replace( "/", "" );
    vr = vr.replace( "/", "" );
    vr = vr.replace( ",", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    vr = vr.replace( ".", "" );
    tam = vr.length;
    
    if (tam < tammax && tecla != 8) { tam = vr.length + 1 ; }
    
    if (tecla == 8 ){	tam = tam - 1 ; }
    
    if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
        
        if ( tam <= 2 ){ 
            campo.value = vr ; 
        }
        
        if ( (tam > 2) && (tam <= 5) ){
            campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
        }
        
        if ( (tam >= 6) && (tam <= 8) ){
            campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
        }
        
        if ( (tam >= 9) && (tam <= 11) ){
            campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
        }
        
        if ( (tam >= 12) && (tam <= 14) ){
            campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
        }
        
        if ( (tam >= 15) && (tam <= 17) ){
            campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;            
        }
    }	
}

function mascCnpj(objeto) {
    campo = eval(objeto);  
    objeto.maxLength=18;
    
    if ( (event.keyCode<48 || event.keyCode>57) )
        event.returnValue = false; 
    if (campo.value.length == 2) 
        campo.value = campo.value + '.';
    else if (campo.value.length == 6) 
        campo.value = campo.value + '.';
    else if (campo.value.length == 10) 
        campo.value = campo.value + '/';      
    else if (campo.value.length == 15) 
        campo.value = campo.value + '-'; 
}

function valida_cnpj(obj) {
    var CNPJ = document.getElementById(obj).value;
    erro = new String;
    if (CNPJ.length < 18) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
        if (erro.length == 0) erro += "E' necessarios preencher corretamente o numero do CNPJ! \n\n";
    }
    //substituir os caracteres que nao sao numeros
    if(document.layers && parseInt(navigator.appVersion) == 4){
        x = CNPJ.substring(0,2);
        x += CNPJ.substring(3,6);
        x += CNPJ.substring(7,10);
        x += CNPJ.substring(11,15);
        x += CNPJ.substring(16,18);
        CNPJ = x;	
    } else {
        CNPJ = CNPJ.replace(".","");
        CNPJ = CNPJ.replace(".","");
        CNPJ = CNPJ.replace("-","");
        CNPJ = CNPJ.replace("/","");
    }
    
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++){
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
    }
    if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
    b = 0;
    for (y=0; y<13; y++) {
        b += (a[y] * c[y]); 
    }
    if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
        erro +="Digito verificador com problema!";
    }
    if (erro.length > 0){
        //alert(erro);
        return false;
    } 
    return true;
} 


function mascCpf(objeto) {
    campo = eval(objeto);  
    objeto.maxLength=14;
    
    if ( (event.keyCode<48 || event.keyCode>57) )
        event.returnValue = false;  
    
    if (campo.value.length == 3) 
        campo.value = campo.value + '.';
    else if (campo.value.length == 7) 
        campo.value = campo.value + '.';
    else if (campo.value.length == 11) 
        campo.value = campo.value + '-';      
    
}

function validaCpf(texto){
    var cpf = document.getElementById(texto).value;        
    var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
    if(!filtro.test(cpf)){     
        return false;
    }
    
    cpf = remove(cpf, ".");
    cpf = remove(cpf, "-");
    
    if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
        cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
        cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
        cpf == "88888888888" || cpf == "99999999999"){	  
        return false;
    }
    
    soma = 0;
    for(i = 0; i < 9; i++)
        soma += parseInt(cpf.charAt(i)) * (10 - i);
    resto = 11 - (soma % 11);
    if(resto == 10 || resto == 11)
        resto = 0;
    if(resto != parseInt(cpf.charAt(9))){	 
        return false;
    }
    soma = 0;
    for(i = 0; i < 10; i ++)
        soma += parseInt(cpf.charAt(i)) * (11 - i);
    resto = 11 - (soma % 11);
    if(resto == 10 || resto == 11)
        resto = 0;
    if(resto != parseInt(cpf.charAt(10))){     
        return false;
    }
    return true;
}

// Função para formatar telefones
function fmtFone(Dado, ValidateNull){
    var Result = Dado;
    var l = Dado.length;
    var a;
    
    if (ValidateNull)
        a = -1;
    else
        a = 0;
    
    if ((l > a) && (l < 2))
        Result = '(' + Dado.substr(0, 2);
    
    if ((l >= 2) && (l < 6))
        Result = '(' + Dado.substr(0, 2) + ')' + Dado.substr(2, 4);
    
    if (l >= 6)
        Result = '(' + Dado.substr(0, 2) + ')' + Dado.substr(2, 4) + '-' + Dado.substr(6, 4);
    
    return Result;
}

function passaDominio(StrDado, Dominio)
{
    var i, j, c;
    var Result;
    
    Result = "";
    
    for (i = 0; i < StrDado.length; i++)
    {
        c = StrDado.substr(i, 1);
        
        for (j = 0; j < Dominio.length; j++)
        {
            if (c == Dominio.substr(j, 1))
                break;
        }
        
        if (j < Dominio.length)
            Result = Result + c;
    }
    
    return Result;
}

function blurFone(Objeto){
    Objeto.value = Objeto.value.replace("(","").replace("-","").replace(")","");
 
    if(Objeto.value.length != Objeto.maxLength && Objeto.value.length > 0){
        alert("Telefone Inválido");
        Objeto.value = "";
        return;
    }
    Objeto.value = passaDominio(Objeto.value, "0123456789");
    Objeto.value = fmtFone(Objeto.value, false);
    
    return true;
}

function blurEmail(Objeto)
{
    if (Objeto.value == "")
        return true;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;    
    
    if (filter.test(Objeto.value))
    {
        Objeto.value = Objeto.value.toLowerCase();
        
        return true;
    }
    else
    {
        window.alert('E-mail inválido!');
        //clearFocus(Objeto);
        return false;
    }
}

function clearFocus(Objeto){
    Objeto.value = "";
    Objeto.focus();
}

function validaEmail(obj){
    var txt = obj.value;
    alert(txt);
    if (txt == ""){
        return;
    }
    if ((txt.length < 5) || (txt.indexOf("@") < 1) || (txt.indexOf('.') < 1)) {
        alert('Email inválido');
        clearFocus(obj);
    }
}
// formata telefone no keypress
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;
    
    var textoSelecionado = document.selection.createRange().text;  
    
    if (textoSelecionado.length == objeto.maxLength){
        alert(textoSelecionado.length);
        objeto.value = "";
        return;
    }

    if(document.all) { // Internet Explorer
        nTecla = evtKeyPress.keyCode;
    } else if(document.layers) { // Nestcape
        nTecla = evtKeyPress.which;
    } else {
        nTecla = evtKeyPress.which;
        if (nTecla == 8) {
            return true;
        }
    }

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
            
        if (bolMask) {
            sCod += sMask.charAt(i);
            mskLen++; 
        } else {
            sCod += sValue.charAt(nCount);
            nCount++;
        }

        i++;
    }
 
    objeto.value = sCod;

    if (nTecla != 8) { // backspace
        if (sMask.charAt(i-1) == "9") { // apenas números...                   
            return ((nTecla > 47) && (nTecla < 58)); } 
        else { // qualquer caracter...
            return true;
        } 
    }
    else {
        return true;
    }
}

function mascFone(objeto) {
    var campo = eval(objeto);  
    objeto.maxLength=13;    
    var tam = campo.value.length;
    
    var textoSelecionado = document.selection.createRange().text;  
    
    if (textoSelecionado.length == objeto.maxLength){
        alert("entrou");        
        tam = 0;        
        return;
   
    }     
    
   
    if ( (event.keyCode<48 || event.keyCode>57) )
        event.returnValue = false;  
    
    if (tam == 0) {
        campo.value += '(';        
    }
    else if (tam == 3) {
        campo.value += ')';        
    }
    else if (tam == 8) {
        campo.value +=  '-';        
    }
    
}

function position(Objeto)
{
    if (document.selection)
    {
        Objeto.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -Objeto.value.length);
        return Sel.text.length;
    }
    else if ((Objeto.selectionStart) || (Objeto.selectionStart == "0"))
    {
        return Objeto.selectionStart;
    }
    
    return 0;
}

function selection(Objeto)
{
    var selectedString = "";
    
    if (window.getSelection)
        selectedString = window.getSelection();
    else if (document.all)
        selectedString = document.selection.createRange().text;
    else if (document.getSelection)
        selectedString = document.getSelection();
    
    return (selectedString != "");
}

function blurFone(Objeto)
{
    Objeto.value = passaDominio(Objeto.value, "0123456789");
    Objeto.value = fmtFone(Objeto.value, false);
    
    return true;
}

function fmtFone(Dado, ValidateNull)
{
    var Result = Dado;
    var l = Dado.length;
    var a;
    
    if (ValidateNull)
        a = -1;
    else
        a = 0;
    
    if ((l > a) && (l < 2))
        Result = '(' + Dado.substr(0, 2);
    
    if ((l >= 2) && (l < 6))
        Result = '(' + Dado.substr(0, 2) + ')' + Dado.substr(2, 4);
    
    if (l >= 6)
        Result = '(' + Dado.substr(0, 2) + ')' + Dado.substr(2, 4) + '-' + Dado.substr(6, 4);
    
    return Result;
}	

function keyPressFone(Evento, Objeto)
{
    if (!keyNumber(Evento, Objeto))
        return true;
    
    if (selection(Objeto))
        return true;
    
    if (Objeto.value.length >= 13)
    {
        cancelKey(Evento);
        return true;
    }
    
    if (position(Objeto) != Objeto.value.length)
        return true;
    
    Objeto.value = passaDominio(Objeto.value, "0123456789");
    Objeto.value = fmtFone(Objeto.value, true);
    
    return true;
}

function passaDominio(StrDado, Dominio)
{
    var i, j, c;
    var Result;
    
    Result = "";
    
    for (i = 0; i < StrDado.length; i++)
    {
        c = StrDado.substr(i, 1);
        
        for (j = 0; j < Dominio.length; j++)
        {
            if (c == Dominio.substr(j, 1))
                break;
        }
        
        if (j < Dominio.length)
            Result = Result + c;
    }
    
    return Result;
}	
	
function cancelKey(Evento)
{
    if (Evento)
    {
        Evento.keyCode = 0;
        Evento.returnValue = false;
    }
    else if (window.event)
    {
        window.event.keyCode = 0;
        window.event.returnValue = false;
    }
}

function clearFocus(Objeto)
{
    Objeto.value = "";
    Objeto.focus();
}

function keyNumber(Evento, Objeto)
{
    if (Evento)
    {
        if ((Evento.keyCode < 48) || (Evento.keyCode > 57))
        {
            cancelKey(Evento);
            return false;
        }
    }
    else if (window.event)
    {
        if ((window.event.keyCode < 48) || (window.event.keyCode > 57))
        {
            cancelKey(Evento);
            return false;
        }
    }
	
    return true;
}

function validaTamanhoFone(objeto){
    if (objeto.value.length < objeto.maxLength) {
        alert("Telefone Inválido");
        objeto.focus();
        return;
    }
}
// Mostra mensagens de erro do site
function mostraMensagem(msg){
    alert(msg);
}
// Bloqueia a tecla PrintScreen
function blockPrintScreen(){
    setInterval("window.clipboardData.clearData()",20);
}
// Bloqueia o botão direito do mouse
function click() {
    if (event.button==2||event.button==3) {
        oncontextmenu='return false';
    }
}
document.onmousedown=click
document.oncontextmenu = new Function("return false;")
function emConstrucao(){
   alert("Em construção");
}

function validaData(Objeto) {
if (Objeto.value == "")
        return true;
    
    var data = Objeto.value;
    
    var dia = parseInt(data.substr(0, 2), 10);
    var mes = parseInt(data.substr(3, 5), 10);
    var ano = parseInt(data.substr(6, 10), 10);
    
    if ((dia <= 31) && (mes <= 12) && (ano >= 1000)) {
        if ((data.substring(0, 1) == '0') && (data.substring(1, 2) != '0') || (data.substring(0, 1) != '0')) {
            if (data.substring(2, 3) == '/') {
                if ((data.substring(3, 4) == '0') && (data.substring(4, 5) != '0') || (data.substring(3, 4) != '0')) {
                    if (data.substring(5, 6) == '/') {
                        if ((data.substring(6, 7) == '0') || (data.substring(6, 7) == '') && (data.substring(7, 8) != '0')) {
                            window.alert('Ano inválido!');
                            Objeto.focus();
                            Objeto.value="";
                            return false;
                        } else {
                            if (mes == 2) {
                                if ((dia > 0 ) && (dia <= 29)) {
                                    if (dia == 29) {
                                        if ((ano % 4) == 0){                                            
                                            return true;
                                        } else {
                                            window.alert('Dia inválido!');
                                            Objeto.focus();
                                            Objeto.value="";
                                            return false;
                                        }
                                    }
                                } else {
                                    window.alert('Dia inválido!');
                                    Objeto.focus();
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                            
                            if ((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) {
                                if ((dia > 0 ) && (dia <= 30)) {
                                    return true;
                                } else {
                                    window.alert('Dia inválido!');
                                    Objeto.focus();
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                            
                            if ((mes == 1) || (mes == 3) || (mes == 5) || (mes ==7) || (mes == 8) || (mes == 10) || (mes == 12)) {
                                if ((dia > 0) && (dia <= 31)) {                                    
                                    return true;
                                } else {
                                    window.alert('Dia inválido!');
                                    Objeto.focus();
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                        }
                    } else {
                        window.alert("Formato da data deve ser (dd/mm/aaaa).");
                        Objeto.focus();
                        Objeto.value="";                                    
                        return false;
                    }
                } else {
                    window.alert('Mês inválido!');
                    Objeto.focus();
                    Objeto.value="";                                    
                    return false;
                }
            } else {
                window.alert('Formato da data deve ser (dd/mm/aaaa)!');
                Objeto.focus();
                Objeto.value="";
                return false;
            } 
        } else {
            window.alert('Dia inválido!');
            Objeto.focus();
            Objeto.value="";                                    
            return false;
        }
    } else {
        window.alert('Data inválida!');
        Objeto.focus();
        Objeto.value="";                                    
        return false;
    }
    return true;
}

function validaDataNoFocus(Objeto) {
if (Objeto.value == "")
        return true;
    
    var data = Objeto.value;
    
    var dia = parseInt(data.substr(0, 2), 10);
    var mes = parseInt(data.substr(3, 5), 10);
    var ano = parseInt(data.substr(6, 10), 10);
    
    if ((dia <= 31) && (mes <= 12) && (ano >= 1000)) {
        if ((data.substring(0, 1) == '0') && (data.substring(1, 2) != '0') || (data.substring(0, 1) != '0')) {
            if (data.substring(2, 3) == '/') {
                if ((data.substring(3, 4) == '0') && (data.substring(4, 5) != '0') || (data.substring(3, 4) != '0')) {
                    if (data.substring(5, 6) == '/') {
                        if ((data.substring(6, 7) == '0') || (data.substring(6, 7) == '') && (data.substring(7, 8) != '0')) {
                            window.alert('Ano inválido!');
                            Objeto.value="";
                            return false;
                        } else {
                            if (mes == 2) {
                                if ((dia > 0 ) && (dia <= 29)) {
                                    if (dia == 29) {
                                        if ((ano % 4) == 0){                                            
                                            return true;
                                        } else {
                                            window.alert('Dia inválido!');
                                            Objeto.value="";
                                            return false;
                                        }
                                    }
                                } else {
                                    window.alert('Dia inválido!');
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                            
                            if ((mes == 4) || (mes == 6) || (mes == 9) || (mes == 11)) {
                                if ((dia > 0 ) && (dia <= 30)) {
                                    return true;
                                } else {
                                    window.alert('Dia inválido');
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                            
                            if ((mes == 1) || (mes == 3) || (mes == 5) || (mes ==7) || (mes == 8) || (mes == 10) || (mes == 12)) {
                                if ((dia > 0) && (dia <= 31)) {                                    
                                    return true;
                                } else {
                                    window.alert('Dia inválido!');
                                    Objeto.value="";                                    
                                    return false;
                                }
                            }
                        }
                    } else {
                        window.alert("Formato da data deve ser (dd/mm/aaaa).");                        
                        Objeto.value="";                                    
                        return false;
                    }
                } else {
                    window.alert('Mês inválido!');
                    Objeto.value="";                                    
                    return false;
                }
            } else {
                window.alert('Formato da data deve ser (dd/mm/aaaa)!');                
                Objeto.value="";
                return false;
            }
        } else {
            window.alert('Dia inválido!');
            Objeto.value="";                                    
            return false;
        }
    } else {
        window.alert('Data inválida!');    
        Objeto.value="";                                    
        return false;
    }
    return true;
}


function mascData(v){
    v=v.replace(/\D/g,"")                            //Remove tudo o que não for dígito
    v=v.replace(/^(\d{2})(\d)/,"$1/$2")             //Coloca barra entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\/(\d{2})(\d)/,"$1/$2/$3") //Coloca barra entre o quarto e o quinto dígitos
    return v
    
}

function mascCep(campo) {
  var s = new String(campo.value);
  s = s.replace(/(\.|\(|\)|\/|\-| )+/g,'');
  tam = s.length + 1;
  if (tam > 5 && tam < 7)
    campo.value = s.substr(0,5) + '-' + s.substr(5, tam);
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value) 
} 

function somenteInteiros(ev) {
    var e= ev;
    
    if (browserIE()) {
      if (((e.keyCode < 48)  || (e.keyCode > 57)) && (e.keyCode != 8) && (e.keyCode != 0))
          e.returnValue = false;
    }
     else {
      if (((e.which < 48)  || (e.which > 57)) && (e.which != 8) && (e.which != 0))
         e.preventDefault();         
     }
}

function restrictKeyCode2(ev) {
    var e = ev;
    var key;

    if (browserIE()) {
        key = e.keyCode;
        if (key == 34 || key == 39 || key == 32)
            e.returnValue = false;
    } else {
        key = e.which;
        if (key == 34 || key == 39 || key == 32)
            e.preventDefault();
    }
}

function restrictKeyCode(ev) {
    var e = ev;
    var key;

    if (browserIE()) {
        key = e.keyCode;
        if (key == 34 || key == 39)
            e.returnValue = false;
    } else {
        key = e.which;
        if (key == 34 || key == 39)
            e.preventDefault();
    }
}

// Define o maxLength de TextArea
function maxLength(obj, limit) {
    if (obj.value.length >= limit) {
         obj.value = obj.value.substring(0, limit-1);
    }
} 

// Reseta todos os campos do form
function resetarForm(nome){
    document.forms[nome].reset();
}

function formatar_mascara(src, mascara, evento) {
      if (!browserIE()) { 
         if (evento.which == 8)
              return;
     }

	var campo = src.value.length;
	var saida = mascara.substring(0,1);
	var texto = mascara.substring(campo);
	if(texto.substring(0,1) != saida) {
		src.value += texto.substring(0,1);
	}
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function convertToDecimal(num) {
    x = 0;
     
    if(num < 0) {
        num = Math.abs(num);
        x = 1;
    } 

    if(isNaN(num))
      num = "0";
      
    cents = Math.floor((num*100+0.5)%100);    
    num = Math.floor((num*100+0.5)/100).toString();
    
    if(cents < 10) 
        cents = "0" + cents;
    
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+ '.' + num.substring(num.length-(4*i+3)); 
    
        ret = num + ',' + cents; 
        
    if (x == 1) 
        ret = ' - ' + ret;
    
return ret;

}

function browserIE() {
    var retorno = false;
    var browser= navigator.appName;
    
    if (browser == "Microsoft Internet Explorer") {
        retorno = true;
    }
    
    return retorno;

}

function corFundo_onfocus(obj) {
    obj.style.backgroundColor='#B9D487';
}

function corFundo_onblur(obj) {
    obj.style.backgroundColor='#FFFFFF';
}

function verificaNumeros(obj) {
  var i,j,c,qtd;
  var dominio = "0123456789";
  qtd = 0;
  for (i = 0; i < obj.length; i++) {
        c = obj.substr(i, 1);
        //alert(obj.substr(i, 1));
        for (j = 0; j < dominio.length; j++) {
            //alert(dominio.substr(j, 1));
            if (c == dominio.substr(j, 1))
                qtd++;
        }

  }

  if (qtd < obj.length)
      return false;

  return true;
}

function blurLogin(obj) {
     
    if (!verificaNumeros(obj.value)) {
        alert("O código de usuário " + obj.value + " é inválido. Este campo deve conter somente números!");
        obj.value = "";
    }

}

function converteData(data) {
    // Converte o Valor passado para data valida para a comparação
    var date = data == "" ? "01/01/1900" : data;

    var diaIni = date.substring(0 , date.indexOf("/"));

    if ( diaIni.substring(0,1) == "0" ) {
        diaIni = diaIni.substring(1, diaIni.length);
    }

    date = date.substring( ( date.indexOf("/") + 1 ), date.length );

    var mesIni = date.substring( 0 , date.indexOf("/") );

    if ( mesIni.substring(0,1) == "0" ) {
        mesIni = mesIni.substring(1, mesIni.length);
    }

    mesIni = ( parseInt( mesIni ) - 1 );
    date = date.substring( ( date.indexOf("/") + 1 ), date.length );

    var anoIni = parseInt(date);
    var dataRet = new Date( anoIni, mesIni, diaIni ).getTime();

    return dataRet;

}

function lastDayOfMonth(Year, Month)
{
    if (Month == 11) {
      NextYear = Year + 1;
      NextMonth = 0;
    } else { 
      NextYear = Year;
      NextMonth = Month;
    }
    return(new Date((new Date(NextYear, NextMonth,1))-1)).getDate();
}

function somenteInteirosNum(ev) {
    var e= ev;

    if (browserIE()) {
        if (((e.keyCode < 48)  || (e.keyCode > 57)) && (e.keyCode != 8) && (e.keyCode != 0))
            e.returnValue = false;
    }
    else {
        if (((e.which < 48)  || (e.which > 57)) && (e.which != 8) && (e.which != 0))
            e.preventDefault();
    }
}


function browserIE() {
    var retorno = false;
    var browser= navigator.appName;

    if (browser == "Microsoft Internet Explorer") {
        retorno = true;
    }

    return retorno;

}


// Formata o campo valor
function formataValorNumerico(campo) {
    campo.value = filtraCampo(campo);
    vr = campo.value;
    tam = vr.length;

    if ( tam <= 2 ){
        campo.value = vr ;
    }
    if ( (tam > 2) && (tam <= 5) ){
        campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ;
    }
    if ( (tam >= 6) && (tam <= 8) ){
        campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
    }
    if ( (tam >= 9) && (tam <= 11) ){
        campo.value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
    }
    if ( (tam >= 12) && (tam <= 14) ){
        campo.value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
    }
    if ( (tam >= 15) && (tam <= 18) ){
        campo.value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ;
    }

}

// limpa todos os caracteres especiais do campo solicitado
function filtraCampo(campo){
    var s = "";
    var cp = "";
    vr = campo.value;
    tam = vr.length;
    for (i = 0; i < tam ; i++) {
        if (vr.substring(i,i + 1) != "/" && vr.substring(i,i + 1) != "-" && vr.substring(i,i + 1) != "."  && vr.substring(i,i + 1) != "," ){
            s = s + vr.substring(i,i + 1);
        }
    }
    campo.value = s;
    return cp = campo.value
}
