//***************************************************************************************
//  Funções específicas para determinados campos
//  Retorno: 0 = Erro
//           1 = Ok

// *** Descrição das funções ***
// -------------------------------------------------------------------------
// ------------- Funções revisadas -----------
// -------------------------------------------------------------------------
// function consisteCGC_CPF(form, campo, pessoa, obrigatorio)
// function consisteCGC(form, campo, obrigatorio)
// function consisteCPF(form, campo, obrigatorio)
// function consisteCEP (form, campo) - faz a consistência do CEP
// function consisteValor (form, campo, obrigatorio) - faz a consistência de valores
// -------------------------------------------------------------------------
// ----------------------- Funções de uso geral ----------------------------
// -------------------------------------------------------------------------
// function Trim(str) - retira espaços em branco da esquerda e direita
// function LTrim(str) - retira espaços em branco do lado esquerdo
// function RTrim(str) - retira espaços em branco do lado direito
// function verificaAlfa(strAver) 
// function DateDiffAno (datafim, datainicio) - faz a diferença entre anos
// function DateDiffDias (datafim, datainicio) - faz a diferença entre dias
// function verificaData (form, campo, obrigatorio) - verifica se a data informada é válida
// function DiferencaDatas( form, nome, valordatacompare )
// function eliminaNaoNumerico (form, campo) - elimina todos os caracteres não numéricos de uma string
//***************************************************************************************

// ------------------------------------------------------------------------------------------------------>
// ----  Verifica CGC e CPF  ----
// ------------------------------------------------------------------------------------------------------>
function consisteCGC_CPF(form, campo, pessoa, obrigatorio)
{
	var retorno;

	if (pessoa=="F")
		eval("retorno = consisteCPF(form, form." + campo + ".name, obrigatorio)");
	else if (pessoa=="J")
		eval("retorno = consisteCGC(form, form." + campo + ".name, obrigatorio)");
	else //caso nao tenha sido determinado se e F ou J
		retorno=true;
	return retorno;
}
// ------------------------------------------------------------------------------------------------------>
// ----  Verifica CGC  ----
// ------------------------------------------------------------------------------------------------------>
function consisteCGC(form, campo, obrigatorio)
{
	var tamanho;
	var noCGC;
	var digito_verificador;
	var soma;
	var peso;
	var i;

	eval("noCGC=eliminaNaoNumerico(form, form." + campo + ".name)");
	if ((obrigatorio) && (noCGC.length==0))
	{
        alert(retornaNmCampo(campo) + ": Preenchimento obrigatório.");
	    eval("form." + campo + ".focus()");
        return 0;
	}
	if ((!obrigatorio) && (noCGC.length==0)) return 1;

	if (noCGC.length != 14)
	{
		alert(retornaNmCampo(campo) + ": Tamanho inválido");
		eval("form." + campo + ".focus()");
		return 0;
	}

	//  calculo 1º dígito do CGC
	soma=0;
	peso=5;
	for (i=0;i<12;i++)
	{
		soma+=peso*(parseInt(noCGC.charAt(i), 10));
		peso--;
		if (peso==1) peso=9;
	}
	digito_verificador = 11-(soma % 11);
	if ((soma % 11)<2) digito_verificador=0;
	if (parseInt(noCGC.charAt(12), 10)!=digito_verificador)
	{
        alert(retornaNmCampo(campo) + " Inválido");
		eval("form." + campo + ".focus()");
        return 0;
	}

	//  calculo 2º dígito do CGC
	soma=0;
	peso=6;
	for (i=0;i<12;i++)
	{
		soma+=peso*(parseInt(noCGC.charAt(i), 10));
		peso--;
		if (peso==1) peso=9;
	}
	soma = soma + digito_verificador * 2;
	digito_verificador = 11-(soma % 11);
	if ((soma % 11)<2) digito_verificador=0;
	if (parseInt(noCGC.charAt(13), 10)!=digito_verificador)
	{
        alert(retornaNmCampo(campo) + " Inválido");
		eval("form." + campo + ".focus()");
        return 0;
	}

	eval("form." + campo + ".value = noCGC.substring(0,2) + '.' + " +
	     "noCGC.substring(2,5) + '.' + noCGC.substring(5,8) + '/' + " +
		 "noCGC.substring(8,12) + '-' + noCGC.substring(12,14)");
	return 1;
}
// ------------------------------------------------------------------------------------------------------>
// ----  Verifica CPF  ----
// ------------------------------------------------------------------------------------------------------>
function consisteCPF(form, campo, obrigatorio) {
	var tamanho;
	var noCPF;
	var digito_verificador;
	var soma;
	var i;

	eval("noCPF=eliminaNaoNumerico(form, form." + campo + ".name)");

	// retorna erro caso o usuário tenha preenchido todos valores iguais
	if ((noCPF.substring (0, 9) == "000000000") ||
		(noCPF.substring (0, 9) == "111111111") ||
		(noCPF.substring (0, 9) == "222222222") ||
		(noCPF.substring (0, 9) == "333333333") ||
		(noCPF.substring (0, 9) == "444444444") ||
		(noCPF.substring (0, 9) == "555555555") ||
		(noCPF.substring (0, 9) == "666666666") ||
		(noCPF.substring (0, 9) == "777777777") ||
		(noCPF.substring (0, 9) == "888888888") ||
		(noCPF.substring (0, 9) == "999999999") || 
		(noCPF.substring (0, 9) == "123456789"))
	{
		alert (retornaNmCampo (campo) + ": Inválido");
		eval ("form." + campo + ".focus ()");
		return 0;
	}
	
	if ((obrigatorio) && (noCPF.length==0))
	{
        alert(retornaNmCampo(campo) + ": Preenchimento obrigatório.");
	    eval("form." + campo + ".focus()");
        return 0;
	}
	if ((!obrigatorio) && (noCPF.length==0)) return 1;
	if (noCPF.length != 11)
	{
		alert(retornaNmCampo(campo) + ": Tamanho inválido");
		eval("form." + campo + ".focus()");
		return 0;
	}

	//  calculo 1º dígito do CPF
	soma=0;
	for (i=0;i<9;i++)
		soma+=(10-i)*(parseInt(noCPF.charAt(i), 10));
	digito_verificador = 11-(soma % 11);
	if ((soma % 11)<2) digito_verificador=0;
	if (parseInt(noCPF.charAt(9), 10)!=digito_verificador)
	{
        alert(retornaNmCampo(campo) + " Inválido");
		eval("form." + campo + ".focus()");
        return 0;
	}

	//  calculo 2º dígito do CPF
	soma=0;
	for (i=0;i<10;i++)
		soma+=(11-i)*(parseInt(noCPF.charAt(i), 10));
	digito_verificador = 11-(soma % 11);
	if ((soma % 11)<2) digito_verificador=0;
	if (parseInt(noCPF.charAt(10), 10)!=digito_verificador)
	{
        alert(retornaNmCampo(campo) + " Inválido");
		eval("form." + campo + ".focus()");
        return 0;
	}
	eval("form." + campo + ".value = noCPF.substring(0,3) + '.' + " +
		 "noCPF.substring(3,6) + '.' + noCPF.substring(6,9) + '-' + " + 
	     "noCPF.substring(9,11)");
	return 1;
}
// ------------------------------------------------------------------------------------------------------>
// verifica se a data informada é válida
// ------------------------------------------------------------------------------------------------------>
function verificaData (form, campo, obrigatorio)
{
	var numberDate;
	var Dia;
	var Mes;
	var erroData;
	var aux;
	var barra="/";
	var menos="-";
	var tamData;

	eval ("numberDate = eliminaNaoNumerico (form, form." + campo + ".name)");

	if (parseInt (numberDate.length, 10) == 0) {
		eval ("form." + campo + ".value = ''");

		if (obrigatorio) {
			alert (retornaNmCampo (campo) + ": Preenchimento obrigatório.");

			eval ("form." + campo + ".focus()");

			return 0;
		}
		else
		{
			return 1;
		}
	}

	if (parseInt(numberDate.length, 10) != 8) {
		alert(retornaNmCampo(campo) + ": Use o formato DD/MM/AAAA");

		eval("form." + campo + ".focus()");

		return 0;
	}

	eval("form." + campo + ".value = numberDate.substring(0,2) + '/' + " + "numberDate.substring(2,4) + '/' + numberDate.substring(4,8)");

	eval("numberDate = form." + campo + ".value.substring(6, 10)");

	if (parseInt(numberDate, 10) < 1850) {
		alert(retornaNmCampo(campo) + ": Ano Inválido");

		eval("form." + campo + ".focus()");

		return 0;
	}

	eval("Mes = form." + campo + ".value.substring(3, 5)");

	if ((parseInt(Mes, 10) > 12)  ||
            (parseInt(Mes, 10) <  1))
	{
		alert(retornaNmCampo(campo) + ": Mês Inválido");

		eval("form." + campo + ".focus()");

		return 0;
	}

	eval("Dia = form." + campo + ".value.substring(0, 2)");

	// consiste o dia para abril, junho, setembro e novembro
	if ( (parseInt (Dia, 10) >  30)   &&
       	    ((parseInt (Mes, 10) ==  4)   ||
             (parseInt (Mes, 10) ==  6)   ||
       	     (parseInt (Mes, 10) ==  9)   ||
             (parseInt (Mes, 10) == 11)))
	{
		alert (retornaNmCampo(campo) + ": Dia Inválido");
		eval ("form." + campo + ".focus()");

		return 0;
	}
	else {
		// consiste o dia para fevereiro
		if (parseInt (Mes, 10) ==  2) {
			// verifica se o ano é divisivel por 400
			if ((parseInt (numberDate, 10) % 400) == 0) {
				// o ano é bissexto
				if (parseInt (Dia, 10) > 29) {
					alert (retornaNmCampo(campo) + ": Dia Inválido");
					eval ("form." + campo + ".focus()");

					return 0;
				}
			}
			else {
				// verifica se o ano é divisivel por 100
				if ((parseInt (numberDate, 10) % 100) == 0) {
					// o ano não é bissexto
					if (parseInt (Dia, 10) > 28) {
						alert (retornaNmCampo(campo) + ": Dia Inválido");

						eval ("form." + campo + ".focus()");

						return 0;
					}
				}
				else {
					// verifica se o ano é divisivel por 4
					if ((parseInt (numberDate, 10) % 4) == 0) {
						// o ano é bissexto
						if (parseInt (Dia, 10) > 29) {
							alert (retornaNmCampo(campo) + ": Dia Inválido");

							eval ("form." + campo + ".focus()");

							return 0;
						}
					}
					else {
						// o ano não é bissexto
						if (parseInt (Dia, 10) > 28) {
							alert (retornaNmCampo(campo) + ": Dia Inválido");

							eval ("form." + campo + ".focus()");

							return 0;
						}
					}
				}
			}
		}
		else {
			// consiste o dia para janeiro, março, maio, 
                        // julho, agosto, outubro e dezembro
			if ((parseInt (Dia, 10) > 31)  ||
        		    (parseInt (Dia, 10) <  1))
			{
				alert (retornaNmCampo(campo) + ": Dia Inválido");

				eval ("form." + campo + ".focus()");

				return 0;
			}
		}
	}
	return 1;
}
// ------------------------------------------------------------------------------------------------------>
// faz a consistência de valores
// ------------------------------------------------------------------------------------------------------>
function consisteValor (form, campo, obrigatorio)
{
	var indPontoDec; // localizacao do ponto decimal
	var valor; // valor do campo
	var valorLimpo = ""; // valor filtrado (apenas numeros e virgula)
	var cont = 0; // contador
	var indPonto = 0; // localizacao do último ponto
	var indVirgula = 0; // localizacao da última virgula
	var numero = "0123456789"; // domínio de dígitos válidos
	var qtPonto = 0; // qtde de pontos de milhar
	var qtResto = 0; // resto de indPontoDec / 3
	var limite = 0; // limite da colocação do ponto de milhar

	// obtém o valor armazenado no campo limpando os espaços à direita e à esquerda
	eval ("valor = Trim (form." + campo + ".value)");

	// verifica se o campo está preenchido
	if (valor.length == 0) {
		// verifica se o campo é obrigatório
		if (obrigatorio) {
			return 0;
		}
		else {
			return 1;
		}
	}

	// descobre qual o último separador que está sendo utilizado
	indVirgula = valor.lastIndexOf (',');
	indPonto = valor.lastIndexOf('.');

	if (indVirgula == indPonto)
	{
		indPontoDec = -1;
	}
	else
	{
		if (indVirgula > indPonto)
		{
			indPontoDec = indVirgula;
		}
		else
		{
			indPontoDec = indPonto;
		}
	}

	// limpa dígitos não numéricos do valor
	for (cont = 0; cont < valor.length; cont++)
	{
		if (numero.indexOf (valor.charAt (cont)) != -1)
		{
			valorLimpo += valor.charAt (cont);
		}

		// substitui ponto decimal por vírgula
		if ((cont + 1) == indPontoDec)
		{
			cont++;
			valorLimpo += ',';
		}
		else
		{
			if ((cont        == 0)  &&
                            (indPontoDec == 0))
			{
				valorLimpo += ','
			}
		}
	}

	if (valorLimpo.indexOf (",") == -1)
	{
		valorLimpo += ",00";
	}

	if (valorLimpo.indexOf (",") == (valorLimpo.length - 1))
	{
		valorLimpo += "00";
	}

	if (valorLimpo.indexOf (",") == (valorLimpo.length - 2))
	{
		valorLimpo += "0";
	}

	if (valorLimpo.indexOf (",") < (valorLimpo.length - 3))
	{
		alert (retornaNmCampo (campo) + ": Utilize apenas duas casas decimais.");

		eval ("form."+campo+".focus ()");

		return 0;
	}

	// retira zeros à esquerda
	while (valorLimpo.charAt (0) == '0')
	{
		valorLimpo = valorLimpo.substring (1, valorLimpo.length);
	}

	// transforma ",xx" em "0,xx"
	if (valorLimpo.charAt (0) == ',')
	{
		valorLimpo = '0' + valorLimpo;
	}

	// coloca separação de milhar
	indPontoDec = valorLimpo.lastIndexOf (',');
	qtPonto = Math.floor (indPontoDec / 3);
	qtResto = indPontoDec % 3;

	if (qtResto == 0)
	{
		limite = 1;
	}
	else
	{
		limite = 0;
	}

	for (cont = (qtPonto - 1); cont >= limite; cont--)
	{
		valorLimpo = valorLimpo.substring (0, qtResto + cont * 3) + '.' + valorLimpo.substring (qtResto + cont * 3, valorLimpo.length);
	}

	// verifica o tamanho
	if (valorLimpo.length > 16)
	{
		alert (retornaNmCampo (campo) + ": Tamanho inválido");

		eval ("form."+campo+".focus ()");

		return 0;
	}

	eval ("form." + campo + ".value = valorLimpo");

	return 1
}
// ------------------------------------------------------------------------------------------------------>
// .
// ------------------------------------------------------------------------------------------------------>
function checkEmail (oField) {
	  msg = "";
	  EmailText = oField.value;

	  if ((EmailText.search(/;/i) == -1) &&
	   	(EmailText.search(/,/i) == -1) &&
	   	(EmailText.indexOf("..") == -1) &&
	   	(EmailText.indexOf(".@") == -1) &&
	   	(EmailText.indexOf("@.") == -1) &&
	   	(EmailText.search(/ /i) == -1) &&
	   	(EmailText.search(/\"/i) == -1) &&
	   	(EmailText.search(/\'/i) == -1) &&
	   	(EmailText.indexOf("^") == -1) &&
	   	(EmailText.search(/`/i) == -1) &&
	   	(EmailText.search(/~/i) == -1) &&
	   	(EmailText.search(/ç/i) == -1) &&
	   	(EmailText.length != 0) &&
	   	(EmailText.search(/@/i) >= 2) &&
	   	(EmailText.substr(0,1) != ".") && /*Não pode começar com ponto*/
	   	(EmailText.substr(EmailText.length-1) != ".") && /*Não pode terminar com ponto*/
	   	(EmailText.indexOf("hotmail.com.br") == -1) &&
	   	(EmailText.indexOf("aol.com.br") == -1))
		  return msg;
	else if (EmailText.indexOf("hotmail.com.br") >= 0) {
		msg = "Atenção: O E-mail HOTMAIL não termina com .BR\nEle será automaticamente corrigido";
		oField.value = EmailText.replace("hotmail.com.br", "hotmail.com");
		oField.focus();
		return msg;
	}
	else if (EmailText.indexOf("aol.com.br") >= 0) {
		msg = "Atenção: O E-mail AOL não termina com .BR\nEle será automaticamente corrigido";
		oField.value = EmailText.replace("aol.com.br", "aol.com");
		oField.focus();
		return msg;
	}
	else if (EmailText.indexOf(" ") >= 0) {
		msg = "Atenção: O E-mail não deve conter espaços em branco\nEle será automaticamente corrigido";
		while(EmailText.indexOf(" ") >= 0)
			EmailText= EmailText.replace(" ", "");
			
		oField.value = EmailText
		oField.focus();
		return msg;
	}
	else {
		msg = "Formato do endereço de E-mail Incorreto!";
		oField.select();
		oField.focus();
		return msg; 
	}
}
// ------------------------------------------------------------------------------------------------------>
// faz a consistência do CEP
// ------------------------------------------------------------------------------------------------------>
function consisteCEP (form, campo)
{
	var noCEP;
	var menos = "-";
	var zeros = "000";

	eval ("noCEP = eliminaNaoNumerico (form, form." + campo + ".name)");

	// retorna erro caso o usuário tenha preenchido somente zeros
	if ((noCEP.substring (0, 5) == "00000") ||
		(noCEP.substring (0, 5) == "11111") ||
		(noCEP.substring (0, 5) == "22222") ||
		(noCEP.substring (0, 5) == "33333") ||
		(noCEP.substring (0, 5) == "44444") ||
		(noCEP.substring (0, 5) == "55555") ||
		(noCEP.substring (0, 5) == "66666") ||
		(noCEP.substring (0, 5) == "77777") ||
		(noCEP.substring (0, 5) == "88888") ||
		(noCEP.substring (0, 5) == "99999"))
	{
		alert (retornaNmCampo (campo) + ": CEP inválido");
		eval ("form." + campo + ".focus ()");
		return 0;
	}

	// verifica se o cep está preenchido
	if (noCEP.length == 0)
	{
		alert (retornaNmCampo (campo) + ": CEP inválido");
		eval ("form." + campo + ".focus ()");
		return 0;
	}

	// verifica se o CEP foi digitado com 5 números
	if (noCEP.length == 5)
	{
		// concatena "-000" no fim do campo
		eval ("form." + campo + ".value = noCEP + '-000'");
		return 1;
	}

	// verifica se o CEP foi digitado com 8 números
	if (noCEP.length == 8)
	{
		// formata o CEP
		eval ("form." + campo + ".value = noCEP.substring (0, 5) + '-' + noCEP.substring (5, 8)");
		return 1;
	}

	// qualquer tamanho diferente de 5 e 8, retorna erro
	if ((noCEP.length != 5) && (noCEP.length != 8))
	{
		alert (retornaNmCampo (campo) + ": tamanho inválido");
		eval ("form." + campo + ".focus ()");
		return 0;
	}
}
// ------------------------------------------------------------------------------------------------------>
// .
// ------------------------------------------------------------------------------------------------------>
function verificaAlfa(strAver) 
{
   var i = 0;
   var j = 0;
   var comp;
   var teste = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";
   var subteste;
   var substrAver;
   var flgvg=0;

   if (strAver=="")
      return 1;
  
   comp = 52;

   while ( j < strAver.length)
   {
      substrAver = strAver.charAt(j);
      i=0;
      while ( i < comp)
      {
          if (strAver.charAt(j)==teste.charAt(i))
             break;
          else
          {
             if (i == (comp-1))
                return 0;
          }
          i++;       
      }
      j++;
   }
   return 1;
}
// ------------------------------------------------------------------------------------------------------>
// retira espaços em branco do lado esquerdo
// ------------------------------------------------------------------------------------------------------>
function LTrim (str)
{
	var whitespace = new String (" \t\n\r");
	var s = new String (str);

	// verifica se existe algum espaço à esquerda
	if (whitespace.indexOf (s.charAt (0)) != -1)
	{
		var j = 0;
		var i = s.length;

		// Busca o indice onde termina os espaços em branco
		// ou até terminar a string (só possuía brancos)
		while ((j                                 <   i)  &&
                       (whitespace.indexOf (s.charAt (j)) != -1))
		{
			j++;
		}

		// Pega a sub-string do primeiro caracter não branco pra frente
		s = s.substring (j, i);
	}

	return s;
}
// ------------------------------------------------------------------------------------------------------>
// retira espaços em branco do lado direito
// ------------------------------------------------------------------------------------------------------>
function RTrim (str)
{
	var whitespace = new String(" \t\n\r");
	var s = new String (str);

	// verifica se existe album espaço à direita
	if (whitespace.indexOf (s.charAt (s.length - 1)) != -1)
	{
		var i = (s.length - 1);

		// Busca, direta pra esquerda, o indice onde termina os espaços
		//  em branco ou até terminar a string (só possuía brancos)
		while ((i >=  0)  && (whitespace.indexOf (s.charAt (i)) != -1)) {
			i--;
		}

		// Pega a sub-string do inicio até o indice encontrado na busca
		s = s.substring (0, (i + 1));
	}

	return s;
}
// ------------------------------------------------------------------------------------------------------>
// retira espaços em branco da esquerda e direita
// ------------------------------------------------------------------------------------------------------>
function Trim (str)
{
	return RTrim (LTrim (str));
}
// ------------------------------------------------------------------------------------------------------>
// elimina todos os caracteres não numéricos de uma string
// ------------------------------------------------------------------------------------------------------>
function eliminaNaoNumerico (form, campo)
{
	var valor;
	var tamanho;
	var cont;
	var valorNumerico = "";
	var numero = "0123456789";

	// obtém o conteúdo do campo
	eval ("valor = form." + campo + ".value");

	// obtém o tamanho do campo
	tamanho = valor.length;

	// percorre o string
	for (cont = 0; cont < parseInt (tamanho, 10); cont++)
	{
		// verifica se o caractere atual do campo existe na string de controle
		if (numero.indexOf (valor.charAt (cont)) != -1)
		{
			valorNumerico += valor.charAt (cont);
		}
	}

	return valorNumerico;
}
// ------------------------------------------------------------------------------------------------------>
// Converte uma string formatada com ponto e virgula para Number...
// Converte uma string formatada com ponto e virgula para Number...
// ------------------------------------------------------------------------------------------------------>
function conv(valor)
{
  var i;
  var1= new String();
  
  for(i=0; i < valor.length; i++)
  {
	if(valor.charAt(i) == ",")
	{
		var1 += ".";
		continue;	
	}

    if(valor.charAt(i) != ".")
      var1 += valor.charAt(i);
  }
	
  return parseFloat(var1);
}
// ------------------------------------------------------------------------------------------------------>
// faz a diferença entre dias
// ------------------------------------------------------------------------------------------------------>
function DateDiffDias (datafim, datainicio)
{
        var DiffData;

	// criação dos strings contendo as datas passadas como parâmetro, para manipulação
       	var DtFim = new String (datafim);
        var DtIni = new String (datainicio);

	var MesFim = parseInt (DtFim.substring (3, 5), 10);
	var MesIni = parseInt (DtIni.substring (3, 5), 10);

	// subtrai conversão dos meses para o padrão do objeto 
        // date do JavaScript (JAN = 0, FEV = 1, ... DEC = 11)
	MesFim--;
	MesIni--;

	// criação dos objetos do tipo Date (JavaScript) para cálculo da diferença
	var DataFim = new Date (parseInt (DtFim.substring (6, 10), 10), MesFim, parseInt (DtFim.substring (0, 2), 10));
	var DataIni = new Date (parseInt (DtIni.substring (6, 10), 10), MesIni, parseInt (DtIni.substring (0, 2), 10));
	
	// cálculo da diferença entre as datas
	DiffData = DataFim - DataIni;

	// converte o total de milissegundos para dias
	DiffData = ((((DiffData / 1000) / 60) / 60) / 24);

	return DiffData;
}
// ------------------------------------------------------------------------------------------------------>
// faz a diferença entre anos
// ------------------------------------------------------------------------------------------------------>
function DateDiffAno (datafim, datainicio)
{
        var DtFim = new String (datafim);
        var DtIni = new String (datainicio);
        var IntAux;

	// subtrai os anos
	IntAux = parseInt (DtFim.substring (6, 10), 10) - parseInt (DtIni.substring (6, 10), 10);

	// obtem o mês e o dia das datas de início e fim, no formato MMDD
	var MesDiaFim = new String (DtFim.substring (3, 5) + DtFim.substring (0, 2));
	var MesDiaIni = new String (DtIni.substring (3, 5) + DtIni.substring (0, 2));

	// verifica se a diferença entre os anos foi maior que 0
	if (IntAux > 0)
	{
		// verifica se ainda não completou um ano
		if (MesDiaFim < MesDiaIni)
		{
			// subtrai um ano
			IntAux--;
		}
	}
	else
	{
		// verifica se a diferença entre os anos foi menor que 0
		if (IntAux < 0)
		{
			// verifica se já completou um ano
			if (MesDiaFim > MesDiaIni)
			{
				// soma um ano
				IntAux++;
			}
		}
	}

	return IntAux;
}
// ------------------------------------------------------------------------------------------------------>
// .
// ------------------------------------------------------------------------------------------------------>
function DiferencaDatas( form, valordatamenor, valordatamaior )
{
	var diferenca;

	if (!(verificaData (form, valordatamenor, true)))
	{
		return false;
	}

	diferenca = DateDiffDias (valordatamaior, eval("form." + valordatamenor + ".value"));
	
	if ( parseInt( diferenca, 10) <= 0 ) {
		alert (retornaNmCampo(valordatamenor) + ": Deve ser menor que " + valordatamaior);
		eval ("form." + valordatamenor + ".focus()");
		return false;
	}
	return true;
}

// ------------------------------------------------------------------------------------------------------>
// .
// ------------------------------------------------------------------------------------------------------>
function retornaNmCampo (campo) {
	return campo;
}
// ------------------------------------------------------------------------------------------------------>
// .
// ------------------------------------------------------------------------------------------------------>
function AbrirJanela(szURL, bBarras, intWidth, intHeight, szWinName)
{
   var szWinOpts;

   szWinOpts = "position=center,toolbar=no,location=no,directories=no,";
   if((intWidth==0) || (intHeight==0)) {
      szWinOpts = szWinOpts + "status=yes,";
   }
   else {
      szWinOpts = szWinOpts + "status=yes,width=" + intWidth + ",height=" + intHeight;
   }
   szWinOpts = szWinOpts + "menubar=no,scrollbars=";
   if(bBarras) {
      szWinOpts = szWinOpts + "yes";
   }
   else {
      szWinOpts = szWinOpts + "no";
   }
   szWinOpts = szWinOpts + ",resizable=yes";

   window.open(szURL, szWinName, szWinOpts);
}
// ------------------------------------------------------------------------------------------------------>
// FUNCOES ANTIGAS
// ------------------------------------------------------------------------------------------------------>


/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function DifDatas(szData1,szData2) {
   var dtPri = new Date(szData1.substr(6,4),szData1.substr(3,2),szData1.substr(0,2)); 
   var dtSeg = new Date(szData2.substr(6,4),szData2.substr(3,2),szData2.substr(0,2)); 

   return(Math.round((dtSeg-dtPri)/(1000*60*60*24)));
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valCEP(szVal)
{
   if(szVal.length != 9 || szVal.indexOf("-") == -1 )
	{
      return(false);
   }
	else
	{
	//   var pat    = /((\d{2})(.)(\d{3})(-)(\d{3}))/;
   	var pat    = /((\d{5})(-)(\d{3}))/;
   	var cepdiv = szVal.match(pat);

   	if(cepdiv==null)
      	return(false);
		
	   return(true);
	}
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valData(szVal){
   var datePat = /(\d{2})(\/)(\d{2})(\/)(\d{4})/;
   var datadiv = szVal.match(datePat);


   if(datadiv==null){
      return(false);
   }

   var dia = datadiv[1];
   var mes = datadiv[3];
   var ano = datadiv[5];

   if(dia<1 || dia>31 || mes<1 || mes>12){
      return(false);
   }
   if((mes==4 || mes==6 || mes==9 || mes==11) && dia>30){
      return(false);
   }
   if(mes==2){
      if(dia>29){
         return(false);
      }
      else{
         if(dia==29 && !valAnoBi(ano)){
            return(false);
         }
      }
   }
   return(true);
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valString(szBuf)
{
   if(szBuf.length == 0)
      return(false);

   szBuf = szBuf.toUpperCase();

   if(
      (szBuf == "ASDF") ||
      (szBuf == "QWER") ||
      (szBuf == "1234")
     )
      return(false);

   return(true);
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function MascaraNumero(oCampo,decimais,bSigned)
{
	var iKey = document.event.keyCode;
	var bDec = (decimais!="" && decimais>0);

	if(!bDec)
	{
		if(iKey==46 || iKey==44)
			return(false);
	}

	if(!bSigned)
	{
		if(iKey==45)
			return(false);
	}

	if( iKey!=13 && iKey!=27 && iKey!=44 && iKey!=45 && iKey!=46 && !(iKey>=48 && iKey<=57) )
		return(false);

	if(iKey==44 || iKey==46)
	{
		if(oCampo.value.indexOf(",")!=-1)
		{
			return(false);
		}
		if(iKey==46)
		{
			oCampo.value += ',';
			return(false);
		}
	}

	if(iKey==45)
	{
		if(oCampo.value.length>0)
			return(false);
	}
	if(bDec)
	{
		if(oCampo.value.indexOf(",")!=(-1))
		{
			if((oCampo.value.length-oCampo.value.indexOf(",")-1) >= decimais)
			{
				return(false);
			}
		}
		return(true);
	}
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valCPFCNPJ(sVal)
{
   var bErr = false;
   bErr = valCNPJ(sVal);
   if(!bErr)
      bErr = valCPF(sVal);

   return(bErr);
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valCNPJ(pcgc) {
	// verifica o tamanho
	if (pcgc.length != 14) { sim=false }
	else { sim=true }

	if (sim ) { // verifica se e numero 
		for (i=0;((i<=(pcgc.length-1))&& sim); i++) {
			val = pcgc.charAt(i)
			// alert (val)
			if ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") && (val!="5")&&(val!="6")&&(val!="7")&&(val!="8"))
				sim=false
		}
		if (sim) {  // se for numero continua
			m2 = 2
			soma1 = 0
			soma2 = 0

			for (i=11;i>=0;i--) {
				val = eval(pcgc.charAt(i))
				m1 = m2

				if (m2<9) { m2 = m2+1 }
				else {m2 = 2}

				soma1 = soma1 + (val * m1)
				soma2 = soma2 + (val * m2)
			}  // fim do for de soma

			soma1 = soma1 % 11

			if (soma1 < 2) { d1 = 0 }
			else { d1 = 11- soma1 }

			soma2 = (soma2 + (2 * d1)) % 11

			if (soma2 < 2) { d2 = 0 }
			else { d2 = 11- soma2 }

			if ((d1==pcgc.charAt(12)) && (d2==pcgc.charAt(13))) { return(true); }
			else return(false);
		}
	}
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function valCPF(pcpf)
{
	if (pcpf.length != 11) { sim=false }
	else { sim=true }

	if (sim)  // valida o primeiro digito
	{
		for (i=0;((i<=(pcpf.length-1))&& sim); i++) {
			val = pcpf.charAt(i)
			if ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4") && (val!="5")&&(val!="6")&&(val!="7")&&(val!="8"))
				sim=false
		}

		if (sim) {
			soma = 0
			for (i=0;i<=8;i++) {
				val = eval(pcpf.charAt(i))
				soma = soma + (val*(i+1))
			}
			resto = soma % 11
			if (resto>9) dig = resto -10
			else  dig = resto

			if (dig != eval(pcpf.charAt(9))) {
				sim=false
			}
			else {  // valida o segundo digito
				soma = 0
				for (i=0;i<=7;i++) {
					val = eval(pcpf.charAt(i+1))
					soma = soma + (val*(i+1))
				}

				soma = soma + (dig * 9)
				resto = soma % 11

				if (resto>9) dig = resto -10
				else  dig = resto

				if (dig != eval(pcpf.charAt(10))) { sim = false }
				else sim = true
			}
		}
	}
	if (sim)
		return(true);
	else
		return(false);
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function NumberFormat( num )
{
   num = num.toString();
   pos = num.indexOf(".");
   if(pos != -1)
   {
      dec = num.substr(pos+1);
      while(dec.length < 2)
      {
         num += "0";
         dec += "0";
      }
   }
   else
   {
      num += ",00";
   }
   return "R$ " + num.replace(".",",");
}
/* ------------------------------------------------------------------------------------------------------------------------------------------------*/
function MascaraData(objAtual) {
   campo = eval (objAtual);
   caracteres = '1234567890';
   iKey = window.event.keyCode;

   if( ( (iKey==13) || (iKey==27) || (iKey==46) || (iKey==44) || ((iKey>=48)&&(iKey<=57)) ) &&  campo.value.length < 10 )
   {
      if (campo.value.length == 2) 
         campo.value = campo.value + "/";
      if (campo.value.length == 5) 
         campo.value = campo.value + "/";
   }
   else
   {
      event.returnValue = false;
   }
   event.returnValue = true;
}

