
////////////////////////////////////////////////////////////////////////////////////////
// validaData(): Valida a data sendo digitada                                         //
// <input type="text" name="data" onKeyPress="return validaData(this, event.which);"> //
////////////////////////////////////////////////////////////////////////////////////////
validaData = function(obj, key)
{

   var retVal = scrutinizeKeyVal(obj, key);

   if (retVal == -1) // scrutinizeKeyVal returned false: Key value does not match mask //
   {
      return false;
   }
   else if (retVal == 0) // scrutinizeKeyVal returned true: Key value does match mask //
   {
      return true;
   }
   else if (retVal == 1) // scrutinizeKeyVal encountered delimiter character //
   {
      //////////////////////////////////////////////////////
      // This will cancel the current keypress event and  //
      // force the separator char to be appended in field //
      //////////////////////////////////////////////////////
      obj.value = obj.value + lastKeyStrokeVal + sepChar;
      return false;
   }
} //end validaData()

// retorna true se alguma das opcoes do check esta marcada
//   exemplo:
//     if (checkRadio("frmPesquisaAssunto", "assuntoHierarquiaUnidade"))
checkRadio = function(formname, checkname) {
    var radio = eval("document.forms."+formname+"."+checkname);
    if (radio == undefined) {
        return false;
    }
    if (radio.length == undefined) {
        return radio.checked;
    }
    var checked = false;
    for (c=0;c<radio.length;c++) {
        if (radio[c].checked) {
            checked = true;
            break;
        }
    }
    return checked;
}

// retorna true se alguma das opcoes do checkbox esta marcada
//   exemplo:
//     if (checkBox("frmPesquisaAssunto", "assuntoHierarquiaUnidade"))
checkBox = function(formname, checkname) {
    var checkbox = eval("document.forms."+formname+"."+checkname);
    if (checkbox == undefined) {
        return false;
    }
    if (checkbox.length == undefined) {
        return checkbox.checked;
    }
    var checked = false;
    for (c=0;c<checkbox.length;c++) {
        if (checkbox[c].checked) {
            checked = true;
            break;
        }
    }
    return checked;
}

// desmarca os demais checkboxs identificados pelo checkname, que tenham
// valores diferentes do ojb.value. Exemplo:
//    onclick="uncheckOther('frmSelecionarGrupo', 'idGrupoUsuario', this)"
uncheckOther = function(formname, checkname, obj) {
    var checkbox = eval("document.forms."+formname+"."+checkname);
    if (checkbox != undefined && checkbox.length != undefined) {
        for (k=0; k<checkbox.length; k++) {
            if (checkbox[k].value != obj.value) {
                checkbox[k].checked = false;
            }
        }
    }
}

// so permite a digitacao de numeros
// obs: o caracter tecla == 32, foi retirado para nao deixar usar espaços
//deve ser colocado no onkeypress (mozilla) E onkeydown (IE)
validNumber = function(event) {
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla = event.which;
        tab_key = 0;
        del_key = 0;
        ins_key = 0;
    } else {
        tecla = event.keyCode;
        tab_key = 9;
        del_key = 0;
        ins_key = 0;
    }

    var valido = "0123456789";

	/** Correção - Caracteres inválidos
     *  if (tecla >= 35 && tecla <=  40) || //end, home e setas
     *  TABELA ASCII
     *  # 35
     *  $ 36
     *  % 37
     *  & 38
     *  ' 39
     *  ( 40
     */

    if ((tecla == ins_key && !String.fromCharCode(tecla) != "-") ||
        (tecla == del_key && !String.fromCharCode(tecla) != ".") ||
        (tecla == 8) )
        return true;
    else if (tecla == tab_key)
        return true;
    else if (valido.indexOf(String.fromCharCode(tecla)) != -1)
        return true;
    else
        return false;
}


//Permite a digitação apenas de números
validarDigitos = function(event) {
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla = event.which;
        tab_key = 0;
        del_key = 0;
        ins_key = 0;
    } else {
        tecla = event.keyCode;
        tab_key = 9;
        del_key = 46;
        ins_key = 45;
    }
	
    var valido = "0123456789";

    if (tecla == tab_key || tecla == 8 || valido.indexOf(String.fromCharCode(tecla)) != -1)
        return true;
    else
        return false;
}


// So permite a digitacao de caracteres alfa-numericos.
// Forma de uso:
//     <input type='text' name='campo' onKeyPress="return validAlfaNumerico(event);">
validaAlfaNumerico = function(event) {

    var teste = false;
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla = event.which;
        tab_key = 0;
        del_key = 0;
        ins_key = 0;
    } else {
        tecla = event.keyCode;
        tab_key = 9;
        del_key = 46;
        ins_key = 45;
    }

    if ((tecla == ins_key && !String.fromCharCode(tecla) != "-") ||
        (tecla == del_key && !String.fromCharCode(tecla) != ".") ||
        (tecla == 8) ) {
        teste = true;
    }
    else if (tecla == tab_key) {
        teste = true;
    }
    else if ((tecla >= 48 && tecla <= 57) ||   // 0 - 9
        (tecla >= 65 && tecla <= 90) ||  	   // A - Z
        (tecla >= 97 && tecla <= 122)) {   	   // a - z
        teste = true;
    }

    return teste;
}

// so permite a digitacao de espaços depois do 1 caractere
//   exemplo:
//     <input type='text' name='numero' onKeyUp="return validSpace(event);">
validSpace = function(txt, event) {
	if (txt.value.indexOf(" ") == 0) {
        while(txt.value.substr(0,1) == " ") {
	    	txt.value = txt.value.substr(txt.value.indexOf(" ")+1,txt.value.length);
        }
	}
}

// so permite a digitacao de espaços depois do 1 caractere
//   exemplo:
//     <input type='text' name='numero' onKeyPress="return validSpace2(event);">
validSpace2 = function(txt, event) {
    var teste = false;
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla= event.which;
    }
    else {
        tecla= event.keyCode;
    }
    if (tecla == 32) {
        teste = txt.value != "";
    }else {
    	teste = true;
    }
   return teste;
}

// so permite a digitacao de data
// DEPRECIADA - Use validaData
//   exemplo:
//     <input type='text' name='data' onKeyPress="return validDate(this, event);">
validDate = function(obj, event) {
	if(event == undefined){
		event = new Object();
        event.keyCode
	}
	if ((event.keyCode) == 47) {
        numDig = obj.value;
        tamDig = numDig.length;
        if ( (tamDig == 3) || (tamDig == 6) ) {
            return true;
        }

    }
    else if (((event.keyCode) > 47) && ((event.keyCode) < 58)) {
        numDig = obj.value;
        tamDig = numDig.length;
        if (tamDig > 9) {
            return false;
        }
        if (tamDig == 2) {
            obj.value = numDig.substr(0,2)+"/";
        }
        else if (tamDig == 5) {
            obj.value = numDig.substr(0,5)+"/";
        }
        else if (tamDig == 9) {
            obj.value = numDig.substr(0,10);
        }
        return true;
    }
    else {
        return false;
    }
}

//return o valor do radio selecionado
valorRadio = function(obj) {
    var valor = undefined;
    if (obj != undefined) {
       if (obj.length == undefined && obj.checked) {
          valor = obj.value;
       }
       else {
           for (i=0;i<obj.length;i++) {
              if (obj[i].checked) {
                 valor = obj[i].value;
                 break;
              }
           }
       }
    }
    return valor;
}

// validar login
validarLogin = function(event) {
   var teste = validarSenha(event);

   if (teste == false) {
      if(navigator.appName.indexOf("Netscape")!= -1) {
         tecla= event.which;
      }
      else {
        tecla= event.keyCode;
     }

     if (tecla == undefined) {
        tecla = event;
     }

     // 95 --> [_]
     if (tecla == 95 || tecla == 45 || tecla == 46 ) {
        teste = true;
     }
   }
   return teste;
}

// Verifica se o caractere do evento é válido. São válidos caracteres
// alfanuméricos, além de teclas de navegação (tab, shift + tab, setas de
// navegação), backspace e delete.
//
// Correção (Matheus e Oto): o método original não permitia o uso dos caracteres
// de navegação, backspace e delete no campo. Foi acrescentado o código que
// permite o uso desses caracteres.
// Revisado por: Gustavo Nunes Ferreira
validarSenha = function(event) {
  var teste = false;
  var tecla_backspace = 8;

  if (navigator.appName.indexOf("Netscape") != -1) {
    tecla = event.which;
  }
  else {
    tecla = event.keyCode;
  }

  /* Intervalos testados:
   * 48 ~ 57  = 0 ~ 9
   * 65 ~ 90  = A ~ Z
   * 97 ~ 122 = a ~ z
   */
  if ((tecla >=  48 && tecla <=  57) ||
    (tecla >=  65 && tecla <=  90) ||
    (tecla >=  97 && tecla <= 122)) {

    teste = true;
  }
 if (navigator.appName.indexOf("Netscape") != -1) {
  //Permite a utilização das teclas: TAB, Delete, Home, End, Seta p/ Esquerda, Seta p/ Direita
  if ((event.keyCode == 9) || (tecla == tecla_backspace) || (event.keyCode == 127) ||
      (event.keyCode == 36) || (event.keyCode == 35) || (event.keyCode == 37)      ||
      (event.keyCode == 39) || (event.keyCode == 46) ) {
      return true;
  }
 }
  return teste;
}

// validar login colado
validarLogin2 = function(login) {
   var teste = true;
   var caracter;

   for (i=0; i<login.value.length; i++) {
      caracter = login.value.charCodeAt(i);

      teste = validarLogin(caracter);
      if (!teste) {
         alert("Login inválido.");
         login.value = "";
         login.focus();
         break;
      }
   }
}

// validar senha colado
validarSenha2 = function(senha) {
   var teste = true;
   var caracter;

   for (i=0; i<senha.value.length; i++) {
      caracter = senha.value.charCodeAt(i);
      teste = validarSenha(caracter);
      if (!teste) {
         alert("Senha inválida.");
         senha.value = "";
         senha.focus();
         break;
      }
   }
}

// retorna true se todos os cheacks do pai estiver marcado
//   exemplo:
//     if (checkRadio("frmPesquisaAssunto", "assuntoHierarquiaUnidade"))
verificarClicados = function(formname, checkname) {
    var valorPai;
    var radio = eval("document.forms."+formname+"."+checkname);
    if (radio == undefined) {
        return false;
    }
    if (radio.length == undefined) {
        return radio.checked;
    }
    var checked = false;
    for (c=0;c<radio.length;c++) {
        if (radio[c].checked) {
            checked = true;
        }
    }
    return checked;
}

verificaMaiorData = function(dataMenor, dataMaior) {
    dataMenorStr = dataMenor.substr(6,4) + dataMenor.substr(3,2) + dataMenor.substr(0,2);
    dataMaiorStr = dataMaior.substr(6,4) + dataMaior.substr(3,2) + dataMaior.substr(0,2);
    return eval(dataMenorStr < dataMaiorStr);
}

/*
******************************************************************************
Criado para verificar se o ano digitado é menor que o ano corrente.

Autor: Fabricio Duarte Nogueira

ano digitdo, ano corrente
******************************************************************************
*/
verificarAno = function(ano, anocorrente) {
    if (ano < anocorrente){
        return -1;
    }
    else if (ano == anocorrente){
       return 0;
    }
    else{
      return 1;
    }
}
/*
******************************************************************************
Criado para incluir casas decimais.

Autor: Fabricio Duarte Nogueira

valor do campo, tamanho das casas
******************************************************************************
*/
casaDecimal = function(valor, decimais) {
   var indice = valor.indexOf(".");
   if (indice == -1) {
   		indice = valor.indexOf(",");
   }
   if (indice == -1) {
       valor = valor + ",";
       indice = valor.indexOf(",");
   }
   var numeroCasas = valor.length - indice;
   for (i=numeroCasas; i<=decimais; i++) {
	   valor = valor + "0";
   }
   return valor;
}
/*
******************************************************************************
Criado para permitir a digitacao de numeros, "." ou ",".

Autor: Fabricio Duarte Nogueira

//   exemplo:
//     <input type='text' name='numero' onKeyPress="return validNumber2(event);">
******************************************************************************
*/

validNumber2 = function(event) {
    var teste = false;
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla= event.which;
    }
    else {
        tecla= event.keyCode;
    }
    if (tecla >=  48 && tecla <=  57) {
        teste = true;
    }
    if ((tecla == 44) || (tecla == 46)) {
	    teste = true;
    }
    return teste;
}

//validar o cadastro de valisigla
validarSigla = function(event){
    return validarSenha(event);
}

//validar o cadastro de sigla
validarSigla2 = function(sigla){
    var teste = true;
   var caracter;

   for (i=0; i<sigla.value.length; i++) {
      caracter = sigla.value.charCodeAt(i);
      teste = validarSigla(caracter);
      if (!teste) {
         alert("Sigla inválida.");
         sigla.value = "";
         sigla.focus();
         break;
      }
   }
}


/*
******************************************************************************
Criado para permitir o uso da mascara de entrada em um telefone

Autor: Welisson Seara de Carvalho

//   exemplo:
//     <input type='text' name='numero' onKeyPress="return validaTelefone(obj,event);">
******************************************************************************
*/


validaTelefone = function(obj, event) {
            var numDig = obj.value;
            var tamDig = numDig.length;
            var teste=false;


            if((event.keyCode) >= 48 && (event.keyCode) <= 57 && tamDig <= 8 && tamDig !=4){
                obj.value = numDig.substr(0,tamDig);
                teste=true;
            }
            else if((event.keyCode) >= 48 && (event.keyCode) <= 57 && tamDig == 4){
                    concatena= numDig.substr(0,tamDig);
                    obj.value = concatena + "-";
                    teste=true;
            }
            return teste;
}



/*
******************************************************************************
Criado para permitir o uso da mascara de entrada em cep

Autor: Welisson Seara de Carvalho

//   exemplo:
//     <input type='text' name='numero' onKeyPress="return validaCep(obj,event);">
******************************************************************************
*/


validaCep = function(obj, event) {
		var numDig = obj.value;
		var tamDig = numDig.length;
		var teste=false;

		if (navigator.appName.indexOf("Netscape")!= -1) {
			tecla = event.which;

			if (tecla == 0 || tecla == 8) {
				teste = true;
			}
		} else {
			tecla = event.keyCode;
		}

		if(tecla == 8 || tecla == 0)
			return true;

		if(tecla >= 48 && tecla <= 57 && tamDig <= 8 && tamDig !=5){
			obj.value = numDig.substr(0, tamDig);
			teste=true;
		}
		else if(tecla >= 48 && tecla <= 57 && tamDig == 5){
			obj.value = numDig.substr(0, tamDig) + "-";
			teste=true;
		}
	    
		return teste;
}


/*
******************************************************************************
Criado para incluir zeros à esquerda de campos com valores numéricos,
somente se o campo for diferente de vazio

Autor: Cristian de Freitas Benigno
Adaptação: Fabricio e Junio

//   exemplo:
//     <input type='text' name='numero' maxlength="12" onBlur="incluiZeros(obj);">
******************************************************************************
*/

incluiZeros = function(obj) {
    var numDig = obj.value;
    var tamDig = obj.value.length;
    maxDig = obj.getAttribute("maxlength");
    var zeros = "";
    if(numDig != "") {
       for (x=0;x<(maxDig-tamDig);x++) {
    		zeros = zeros + "0";
       }
       obj.value = zeros + numDig;
    }
}


/*
******************************************************************************
Criado para validar números de telefone no formato 0000-0000 ou 00000000. Telefones vazios são considerados válidos.

Autor: Cristian de Freitas Benigno

//   exemplo:
//Fone: <input name="tel" type="text" maxlength="9">
//<input type="button" value="validar" onclick="if (validarFone(tel)) {alert('Fone válido!!!');}else{alert('Fone inválido!');}">
******************************************************************************
*/

validarFone = function(obj) {
    var numDig = obj.value;
    var tamDig = obj.value.length;
    var valoresvalidos = /^[0-9]+$/;
    if (numDig != "") {
        if (tamDig != 9) {
            if (tamDig == 8) {
        		if (!(valoresvalidos.test(numDig.substring(0,4)))) {
                    return false;
                }
                else if (!(valoresvalidos.test(numDig.substring(4,8)))) {
                    return false;
                }
                else {
                    return true;
                }
            }
            else {
	            return false;
            }
        }
        else {
            if (!(valoresvalidos.test(numDig.substring(0,4)))) {
                return false;
            }
            else if (!(valoresvalidos.test(numDig.substring(5,9)))) {
                return false;
            }
            else if (numDig.substring(4,5) != "-") {
                return false;
            }
            else {
                return true;
            }
        }
    }
    else {
    	return true;
    }
}

/*
******************************************************************************
Criado para validar CEP nos formatos 00000-000 ou 00000000. CEP's vazios são considerados válidos.

Autor: Cristian de Freitas Benigno

//   exemplo:
//CEP: <input name="tel" id="tel1" type="text" maxlength="9">
//<input type="button" value="validar" onclick="if (validarCep(tel)) { alert('Válido!!!');}else{alert('Inválido!');}">
******************************************************************************
*/

validarCep = function(obj) {
    var numDig = obj.value;
    var tamDig = obj.value.length;
    var valoresvalidos = /^[0-9]+$/;
    if (numDig != "") {
        if (tamDig != 9) {
            if (tamDig == 8) {
        		if (!(valoresvalidos.test(numDig.substring(0,5)))) {
                    return false;
                }
                else if (!(valoresvalidos.test(numDig.substring(5,8)))) {
                    return false;
                }
                else {
                    return true;
                }
            }
            else {
	            return false;
            }
        }
        else {
            if (!(valoresvalidos.test(numDig.substring(0,5)))) {
                return false;
            }
            else if (!(valoresvalidos.test(numDig.substring(6,9)))) {
                return false;
            }
            else if (numDig.substring(5,6) != "-") {
                return false;
            }
            else {
                return true;
            }
        }
    }
    else {
    	return true;
    }
}


replaceText = function(string,text,by) {
// Replaces text with by in string

    var strLength = string.length,
        txtLength = text.length;

    if ((strLength == 0) || (txtLength == 0))
      return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replaceText(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

/*
******************************************************************************
Criado para inserir mascara de hora HH:mm.

Autor: Igor Lucas

Para usar, coloque no campo de texto a chamada: onKeyPress="return validTime(event, this);"
******************************************************************************
*/
validTime = function(event, object) {
    var teste = false;

    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla = event.which;

        if (tecla == 0 || tecla == 8) {
            teste = true;
        }
    } else {
        tecla = event.keyCode;
    }

   if (tecla >=  48 && tecla <=  57) { // 0 a 9
       teste = true;
   }

   var text = object.value;
   if (tecla >=  48 && tecla <=  57) {
      text = replaceText(text, ':', '');

      if (text.length >= 2) {
          object.value = text.substring(0,2) + ":" + text.substring(2,text.length);
       }
   }
   return teste;
}


var horaMask = /^([0-1][0-9]|[2][0-3]):[0-5][0-9]$/;

formatoHora = function(object) {

      var teste = true;
      if (object.value != null && object.value != "") {
        if(!horaMask.test(object.value)){
          teste = false;
        }
      }

      return teste;
}


/*
******************************************************************************
Criado para validar a mascara de hora HH:mm.

Autor: Igor Lucas

Para usar, faça a chamada: isTimeValid('o objeto do form', 'A mensagem a ser enviada ao usuário, ou vazio caso não seja usada.');
******************************************************************************
*/
isTimeValid = function(object, message) {
  var teste = true;

  if (object.value != null && object.value != "") {
    if (object.value.indexOf(":") == -1 || object.value.length != 5) {
      teste = false;
    } else {
      hour = object.value.substr(0, 2);
      minute = object.value.substr(3, 5);
      if (isNaN(hour) || isNaN(minute)) {
        teste = false;
      } else if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
        teste = false;
      }
    }
  }

  if (!teste) {
    if (message != null && message != "") {
      alert(message);
    }
    return false;
  }
  return true;
}

isValidTime = function(object) {
  var teste = true;

  if (object.value != null && object.value != "") {
    if (object.value.indexOf(":") == -1 || object.value.length != 5) {
      teste = false;
    } else {
      hour = object.value.substr(0, 2);
      minute = object.value.substr(3, 5);
      if (isNaN(hour) || isNaN(minute)) {
        teste = false;
      } else if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
        teste = false;
      }
    }
  }

  return teste;
}

isValidStringTime = function(s) {
  var teste = true;

  if (s != undefined && s != null && s != "") {
    if (s.indexOf(":") == -1 || s.length != 5) {
      teste = false;
    } else {
      hour = s.substr(0, 2);
      minute = s.substr(3, 5);
      if (isNaN(hour) || isNaN(minute)) {
        teste = false;
      } else if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
        teste = false;
      }
    }
  } else {
    teste = false;
  }

  return teste;
}

////////////////////////////////////////////////////
//Globally defined -- you could move these around //
//to each function to make the code more modular  //
////////////////////////////////////////////////////

var dtFormat = "DD/MM/YYYY";
var sepChar = '/';
var fullDateMask = /[0-3][0-9]\/[01][0-9]\/[1-2][0-9][0-9][0-9]/;
var lastKeyStrokeVal;
var currMask;
var monthVal;
var dayVal;
var yearVal;
var autoFillVal = '=';
var day1Val;
var day2Val;


//////////////////////////////////////////////////////////
// returnCurrentDate() : return the current system date //
// in DD/MM/YYYY format                                 //
//////////////////////////////////////////////////////////
returnCurrentDate = function()
{
   d = new Date();
   dia = parseInt(d.getDate());
   mes = parseInt(d.getMonth())+1;
   dia = dia < 10?"0" + dia:dia;
   mes = mes < 10?"0" + mes:mes;

   var myDate = (dia + sepChar + mes + sepChar + getAnoCompleto(d.getYear()));

   return myDate;
}

////////////////////////////////////////////////////////////
// scrutinizeKeyVal() : apply mask to the keystroke value //
// when each keystroke is typed                           //
////////////////////////////////////////////////////////////
scrutinizeKeyVal = function(obj, key)
{
   ////////////////////////////////////////////////////////////////////
   // If using IE, the "String.fromCharCode(window.event.keyCode)"   //
   // will return the key value pressed. For Netscape, the "which"   //
   // keyword will return the keyvalue. NOT TESTED WITH NETSCAPE YET //
   ////////////////////////////////////////////////////////////////////

   var length = parseInt(obj.value.length);
   var keyCode;

   if(window.event){

     keyCode = window.event.keyCode;
     lastKeyStrokeVal = String.fromCharCode(window.event.keyCode); // IE = Only
     if (lastKeyStrokeVal == autoFillVal)
     {
        obj.value = returnCurrentDate();
        return -1;
     }
   } else {
     keyCode = key;
     lastKeyStrokeVal = String.fromCharCode(key); // NS = Only
     if (lastKeyStrokeVal == autoFillVal)
     {
        obj.value = returnCurrentDate();
        return -1;
     }
   }

   if(keyCode == undefined || keyCode == "" || keyCode == 0 || keyCode == 8){
   		return 0;
   }

   /////////////////////////////////////////////////////////
   // The date format is dd/mm/yyyy and leading zeros are //
   // required in the Months and Days fields              //
   /////////////////////////////////////////////////////////

   /////////////////////////////////////////////
   // FIRST CHARACTER TYPED - day field       //
   // The first char typed should be a 0,1,2,3//
   /////////////////////////////////////////////
   if (length == 0)
   {
     currMask = /^[0-3]/;
     if (!compareValue(lastKeyStrokeVal, currMask))
     {
        return -1;
     }
     day1Val = lastKeyStrokeVal;
   }
   //////////////////////////////////////////////////////////
   // SECOND CHARACTER TYPED - day field                   //
   // The fifth char typed should be a number              //
   // if first char is 0, second char may only be 1-9      //
   // if first char is 1 or 2, second char may only be 0-9 //
   // if first char is 3, second char may only be 0-1      //
   //////////////////////////////////////////////////////////
   if (length == 1)
   {
     if (day1Val == 0)
     {
        currMask = /^[1-9]/;
     }
     else if ((day1Val == 1) || (day1Val == 2))
     {
        currMask = /^[0-9]/;
     }
     else if (day1Val == 3)
     {
        currMask = /^[0-1]/;
     }
     else
     {
        return -1;
     }
     if (!compareValue(lastKeyStrokeVal, currMask))
     {
        return -1;
     }
     day2Val = lastKeyStrokeVal;
     return 1;
   }
   ////////////////////////////////////////////
   // THE THIRD OR SIXTH CHARACTER TYPED     //
   // This character should be the delimiter //
   // char for the date format "MM/DD/YYYY"  //
   ////////////////////////////////////////////
   if ((length == 2) || (length == 5))
   {
      currMask = /^\//;
      if (!compareValue(lastKeyStrokeVal, currMask))
      {
         return -1;
      }
   }
   ///////////////////////////////////////////////////////
   // THE FOURTH CHARACTER TYPED - month field            //
   // The fourth char typed should be a number...0,1,2,3//
   // We can't check for leap year yet because we don't //
   // have the year value yet. This will need to be     //
   // done after the date field is populated...         //
   ///////////////////////////////////////////////////////
   if (length == 3)
   {
     currMask = /^[0-1]/;
     if (!compareValue(lastKeyStrokeVal, currMask))
     {
        return -1;
     }
   }
   //////////////////////////////////////////////////////////
   // THE FIFTH CHARACTER TYPED - month field                //
   // if first char is 1, second char may only be 0,1,2    //
   //////////////////////////////////////////////////////////
   if (length == 4)
   {
     if (obj.value.charAt(length -1) == 1)
     {
        currMask = /^[0-2]/; //months 10,11,12
     }
     else
     {
        currMask = /^[1-9]/; //months 01-09
     }
     if (!compareValue(lastKeyStrokeVal, currMask))
     {
        return -1;
     }
     //////////////////////////////////
     // capture the month value and  //
     // Autofill the first delimiter //
     //////////////////////////////////
     monthVal = obj.value + lastKeyStrokeVal;
     return 1;
   }
   //////////////////////////////////////////////////////////////
   // THE SEVENTH CHARACTER TYPED - year field                 //
   // Safe to assume this character is going to be a 1 or 2... //
   //////////////////////////////////////////////////////////////
   if (length == 6)
   {
      currMask = /^[1-2]/;
      if (!compareValue(lastKeyStrokeVal, currMask))
      {
         return -1;
      }
   }
   ///////////////////////////////////////////////////////////
   // THE EIGHTH, NINTH, TENTH CHARACTER TYPED - year field //
   ///////////////////////////////////////////////////////////
   if ((length == 7) || (length == 8) || (length == 9))
   {
      currMask = /^[0-9]/;
      if (!compareValue(lastKeyStrokeVal, currMask))
      {
         return -1;
      }
   }
   /////////////////////////////////////////////////////////
   // Finally, do a mask check for the date val so far... //
   /////////////////////////////////////////////////////////
   if (compareValue(lastKeyStrokeVal, currMask))
   {
      return 0;
   }
   else
   {
      return -1;
   }
} //end scrutinizeKeyVal()



////////////////////////////////////////////////////////
// isValidDate(): Determines if a date value is valid //
// Uses the date format "DD/MM/YYYY"                  //
////////////////////////////////////////////////////////
isValidDate = function(obj)
{
   var s = new String;
   s = obj.value;
   dayVal = s.charAt(0) + s.charAt(1);
   monthVal = s.charAt(3) + s.charAt(4);
   yearVal = s.charAt(6) + s.charAt(7) + s.charAt(8) + s.charAt(9);

   if (isNaN(dayVal) || dayVal == "" || isNaN(monthVal) || monthVal == "" || isNaN(yearVal) || yearVal == "")
   {
      return false;
   }

   if (parseInt(dayVal) > parseInt(daysInMonth(monthVal, yearVal)))
   {
      obj.focus();
      obj.select();
      return false;
   }
   return true;
}  //end isValidDate()

isValidStringDate = function(s) {
  if (s != undefined && s != null && s.length == 10) {
    if (s.charAt(2) != '/' || s.charAt(5) != '/') {
       return false;
    }
		
    var dayVal = s.charAt(0) + s.charAt(1);
    var monthVal = s.charAt(3) + s.charAt(4);
    var yearVal = s.charAt(6) + s.charAt(7) + s.charAt(8) + s.charAt(9);
	
    if (isNaN(dayVal) || dayVal == "" || isNaN(monthVal) || monthVal == "" || isNaN(yearVal) || yearVal == "") {
       return false;       
    }
    if (parseInt(monthVal, 10) < 1 || parseInt(monthVal, 10) > 12 || parseInt(dayVal, 10) < 1 || parseInt(dayVal, 10) > parseInt(daysInMonth(monthVal, yearVal), 10)) {
       return false;
    }

  } else {
    return false;
  }

  return true;
}  //end isValidStringDate()

/////////////////////////////////////////////
// daysInMonth(): Determines the number of //
// allowable days in a month.              //
/////////////////////////////////////////////
daysInMonth = function(charMonth, charYear)
{
   if ((charMonth == "01") || (charMonth == "03") || (charMonth == "05")
       || (charMonth == "07") || (charMonth == "08") || (charMonth == "10")
       || (charMonth == "12"))
      return 31;

   if (charMonth == "02")
   {
      if (isLeapYear(parseInt(charYear, 10)))
         return 29;
      return 28;
   }

   if ((charMonth == "04") || (charMonth == "06") || (charMonth == "09")
       || (charMonth == "11"))
      return 30;
}


//////////////////////////////////////////////
// isLeapYear(): Determines if year is leap //
//////////////////////////////////////////////
isLeapYear = function(intYear)
{
   return (intYear % 400 == 0 || (intYear % 4 == 0 && intYear % 100 != 0));
}


//////////////////////////////////////////////////
// compareValue(): Compares a value to its mask //
// (both args are passed in)                    //
//////////////////////////////////////////////////
compareValue = function(cmpVal, mask)
{
  if(!cmpVal.match(mask))
  {
     return false;
  }
  else
  {
     return true;
  }
}

///////////////////////////////////////////////////////////////////////////////////////
// Só permite a digitação de caracteres de texto no campo, suprimindo a digitação de //
// números e caracteres especiais                                                    //
// <input type="text" name="nome" onKeyPress="return validText(event);">             //
validText = function(event){
	var test1 = validarSenha(event);
	var test2 = !validNumber(event);
	var teste = (test1 && test2);
	var tecla;

    if (navigator.appName.indexOf("Netscape")!= -1) {
    	tecla = event.which;
    } else {
        tecla = event.keyCode;
    }

	if (!teste) {
        if (tecla == 0 || tecla == 8 || tecla == 32)
        	return true;
        else
        	return false;
	} else {
        return true;
	}
}



/////////////////////////////////////////////////////////////////////////////////////
// so permite a digitacao de espaços depois do 1 caractere  na inclusao            //
// exemplo:                                                                        //
// <input type='text' name='numero' onKeyPress="return validaSpace(this,event);">  //
////////////////////////////////////////////////////////////////////////////////////
validaSpace = function(obj, event) {
    var teste = true;
    var aux;
    if (navigator.appName.indexOf("Netscape")!= -1) {
        tecla= event.which;
    }
    else {
        tecla= event.keyCode;
    }
    if (tecla == 32) {
        aux=obj.value;
       	if(aux.length == 0 ){
    		teste = false;
    	}
    }
    return teste;
}

/*
******************************************************************************
Criado para validar campos de nome nas telas de cadastro

Para usar, faça a chamada: verificarCampoNome(nome.value, "campo Nome do Servidor");
******************************************************************************
*/
	verificarCampoNome = function(str, campo) {
	    var reTest = new RegExp(/^[a-z ç ã á â ê é í õ ô ó ü ú ']+$/i);
	    //var reMatch = new RegExp("pai |mãe |desconhecid[oa] |não |nada |sem |ignorad[oa] |  | pai$| mãe$| desconhecid[oa]$| não$| nada$| sem$| ignorad[oa]$","i");
	    var reMatchEspaco = new RegExp(" ","i");
	
	    for (var i=0;i < str.length-1; i++) {
	        if((str.charAt(i) == str.charAt(i+1)) && (str.charAt(i+1) == str.charAt(i+2))){
	            return "Caracter está se repetindo no "+campo+"\n";
	            break;
	        }
	        if(str.length > 3){
	            if(str.charAt(i) == " " && str.charAt(i+2) == " "){
	                if(str.charAt(i+1) != "e" && str.charAt(i+1) != "E"){
	                    return "Caracter inválido no "+campo+"\n";
	                    break;
	                }
	            }
	            if(str.length > 5) {
	                if(str.charAt(i) == str.charAt(i+2) && str.charAt(i+1) == str.charAt(i+3) &&
	                        str.charAt(i+2) == str.charAt(i+4) && str.charAt(i+3) == str.charAt(i+5)) {
	                    return "Caracter está se repetindo no "+campo+"\n";
	                    break;
	                }
	            }
	        }
	    }
	
	    if(!(reTest.test(str))){
	        return "Caracter inválido no "+campo+"\n";
	    }
	    //else if(str.match(reMatch)){
	    //    return "Dado inválido no "+campo+"\n";
	    //}
	    else if(!(str.match(reMatchEspaco))){
	        return "Falta sobrenome no "+campo+"\n";
	    }
	    else if((str.charAt(0) == " ") || (str.charAt(str.length-1) == " ")){
	        return "Espaços além do permitido no "+campo+"\n";
	    }
	    else if (str.toLowerCase() == "em branco"){
	        return "Dado inválido no "+campo+"\n";
	    }
	    else{
	        return "";
	    }
	}

/*
******************************************************************************
Criado para validar a data de nascimento de acordo com o numero de anos informado.
Verifica se a pessoa que possui esta data de nascimento tem a idade informada em anos
Autor: Igor Lucas
Para usar, faça a chamada: validaDataNascimento(dtNascimento.value, '18');
******************************************************************************
*/
validaDataNascimento = function(dtNacimento, years) {
    var now = new Date();
    var dia = now.getDate();
    var mes = now.getMonth() + 1;
    var ano = getAnoCompleto(now.getYear()) - years;
    dia = dia < 10?"0" + dia:dia;
    mes = mes < 10?"0" + mes:mes;

    var myDate = (dia + '/' + mes  + '/' + ano);
    return !verificaMaiorData(myDate,dtNacimento)

}

comparaDatas = function(datainicial,datafinal){

    var mesAno = datainicial.substring(datainicial.indexOf("/")+1);

    diaA = datainicial.substring(0,datainicial.indexOf("/"));
    mesA = mesAno.substring(0,mesAno.indexOf("/"));
    anoA = mesAno.substring(mesAno.indexOf("/")+1);

    diaA = diaA.length == 1?"0" + diaA:diaA;
    mesA = mesA.length == 1?"0" + mesA:mesA;

    mesAno = datafinal.substring(datafinal.indexOf("/")+1);

    diaB = datafinal.substring(0,datafinal.indexOf("/"));
    mesB = mesAno.substring(0,mesAno.indexOf("/"));
    anoB = mesAno.substring(mesAno.indexOf("/")+1);

    diaB = diaB.length == 1?"0" + diaB:diaB;
    mesB = mesB.length == 1?"0" + mesB:mesB;

    Datainicio = anoA + mesA + diaA;
    Datafinal = anoB + mesB + diaB;

    ini = eval(Datainicio);   
    fim = eval(Datafinal);
    
    result = fim - ini;

    if(result > 0){
        return "maior";
    }
    else if(result < 0){
        return "menor";
    }
    else return "igual";

}

comparaHora = function(horainicial, horafinal){
	var hor1 = horainicial.substring(0,2);
	var hor2 = horafinal.substring(0,2);

    if(hor1 > hor2){
        return "maior";
    }
    else if(hor1 < hor2){
    	return "menor";
    }
    else{
        var min1=horainicial.substring(3);
        var min2= horafinal.substring(3);

        if(min1 > min2){
           return "maior";
        }
        else if(min1 < min2){
            return "menor";
        }
    }
}

// retorna a quantidade de checks marcados
//   exemplo:
//     if (countCheck("frmPesquisaAssunto", "assuntoHierarquiaUnidade"))
countCheck = function(formname, checkname) {
    var checkbox = eval("document.forms."+formname+"."+checkname);
    if (checkbox == undefined) {
        return false;
    }
    var checked = 0;
    if (checkbox.length == undefined) {
        checked = (checkbox.checked) ? 1 : 0;
    } else {
        for (c=0;c<checkbox.length;c++) {
            if (checkbox[c].checked) {
                checked ++;
            }
        }
    }
    return checked;
}

// corrige a função getYear
getAnoCompleto = function(ano) {
   return 1900 + ano;
}


    // Adiciona uma função para ser executada no load da pagina
    addLoadEvent = function(w, func) {
      var oldonload = w.onload;
      if (typeof w.onload != 'function') {
        w.onload = func;
      } else {
        w.onload = function() {
          oldonload();
          func();
        }
      }
    }

    somarHoras = function(hora1, hora2) {
        horas = hora1.split(":")[0]/1 + hora2.split(":")[0]/1;
        minutos = hora1.split(":")[1]/1 + hora2.split(":")[1]/1;

        if (minutos >=180) { horas++; minutos = minutos - 60; }
        if (minutos >=120) { horas++; minutos = minutos - 60; }
        if (minutos >= 60) { horas++; minutos = minutos % 60; }
        if (minutos < 10) minutos = "0" + minutos;

        hora3 = horas +":"+ minutos;
        return hora3;
    }

    repeatStr = function(str, n) {
        var result = '';
        for (var i = 1; i <= n; i++)
            result = result + str;
        return result;
    }


	/*
	Remove caracteres que não são numéricos
	exemplo: onblur="removeNaN(this);"
	*/
	removeNaN = function(field) {
		var valid = "0123456789";
		var result = "";
		for (var i = 0; i < field.value.length; i++) {
			if (valid.indexOf(field.value.charAt(i)) != -1)
				result += field.value.charAt(i);
		}
		field.value = result;
	}


    verificarDados = function(str, campo) {
        var reTest = new RegExp(/^[a-z ç ã á â ê é í õ ô ó ü ú ']+$/i);
        var reVogais = new RegExp(/^[a ã á â e ê é i í o õ ô ó u ü ú]+$/i);
        var reMatch = new RegExp("^pai |^mãe |desconhecid[oa] |^não |^nada |ignorad[oa] |  | pai | mãe | pai$| mãe$| desconhecid[oa]| não | nada | não$| nada$| ignorad[oa]$","i");
        var reMatchEspaco = new RegExp(" ","i");

        for (var i=0;i < str.length-1; i++) {
            if((str.charAt(i) == str.charAt(i+1)) && (str.charAt(i+1) == str.charAt(i+2))){
                return "Caracter está se repetindo no "+campo+".\n";
                break;
            }
            if(str.length > 3){
                if(str.charAt(i) == " " && str.charAt(i+2) == " "){
                    if(!reVogais.test(str.charAt(i+1))){
                        return "Caracter inválido no "+campo+".\n";
                        break;
                    }
                }
                if(str.length > 5){
	                if(str.charAt(i) == str.charAt(i+2) && str.charAt(i+1) == str.charAt(i+3) &&
	                        str.charAt(i+2) == str.charAt(i+4) && str.charAt(i+3) == str.charAt(i+5)) {
                        return "Caracter está se repetindo no "+campo+".\n";
                        break;
                    }
                }
            }
        }

        if(!(reTest.test(str))){
            return "Caracter inválido no "+campo+".\n";
        }
        else if(str.match(reMatch)){
            return "Dado inválido no "+campo+".\n";
        }
        else if(!(str.match(reMatchEspaco))){
            return "Falta sobrenome no "+campo+".\n";
        }
        else if((str.charAt(0) == " ") || (str.charAt(str.length-1) == " ")){
            return "Espaços além do permitido no "+campo+".\n";
        }
        else{
            return "";
        }
    }
    
    //valida digito verificador cpf
    validRgDv = function(event){
	    if (!validNumber(event)){
		    if (navigator.appName.indexOf("Netscape")!= -1) {
		        tecla = event.which;
		    } else {
		        tecla = event.keyCode;
		    }
	    if (tecla == 88 || tecla ==  120) // X && x
	        return true;
    	else
	        return false;
	    }
	}

