// Verifica se o usuário marcou se vai ou não atualizar o endereço
// Se marcou que "sim", valida os campos de endereço
// Retorna true- endereço ok, ou false- endereço errado
function validaEndereco() {

	// Precisamos verificar se os campos de atualização de endereço foram preenchidos
	if ( f.SG_UF.value != 'EX' && f.txtTipoLogradouro.value == 'XX' ) {
		aviso(f.txtTipoLogradouro,"Selecione o tipo de logradouro");
		return false;
	}

	if ( f.txtLogradouro.value == '' ) {
		aviso(f.txtLogradouro,"Preencha o campo de logradouro");
		return false;
	}

	// Cep só pode conter dígitos
	if ( ContaDigitos( f.txtCep.value ) != f.txtCep.value.length ) {
		aviso(f.txtCep,"Campo CEP só pode conter dígitos");
		return false;
	}

	// Cep precisa ser preenchido, e com 8 dígitos
	if ( f.SG_UF.value == 'EX' ) {
		if ( ContaDigitos( f.txtCep.value ) == 0 ) {
			aviso(f.txtCep,"Preencha o CEP");
			return false;
		}
	} else {
		if ( ContaDigitos( f.txtCep.value ) != 8 ) {
			aviso(f.txtCep,"Preencha o CEP corretamente (8 dígitos)");
			return false;
		}
	}
	
	// Primeiro verificamos estado, depois cidade
	if ( f.SG_UF.options.selectedIndex == 0 ) {
		aviso(f.SG_UF,"Unidade da Federação deve ser selecionada");
		return false;
	}

	// Se foi selecionado exterior, verificamos o combo país,
	// senão verificamos o campo cidade
	if ( f.SG_UF.value != 'EX' ) {
		if ( f.MUNICIPIO.options.selectedIndex == 0 ) {
			aviso(f.MUNICIPIO,"Selecione o município");
			return false;
		}
	} else {
		if ( f.Pais.options.selectedIndex == 0 ) {
			aviso(f.Pais,"Selecione o país");
			return false;
		}
	}
	if ( !validaFones() )
		return false;

	return true;

}

// Verifica o campo e-mail. Pode ser vazio,
// mas se for preenchido testa o formato da string
function verifica_email() {

		if (isEmpty(f.email.value))
			return true;

		if (!valida_mail(f.email.value)) {
			  aviso(f.email,"Digite um e-mail válido.");
			  return false;
		}
}
function valida_mail(valor) {
	prim = valor.indexOf("@")
	if(prim < 2) return false;
	if(valor.indexOf("@",prim + 1) != -1) return false
	if(valor.indexOf(".") < 1) return false;
	if(valor.indexOf("zipmeil.com") > 0) return false;
	if(valor.indexOf("hotmeil.com") > 0) return false;
	if(valor.indexOf(".@") > 0) return false;
	if(valor.indexOf("@.") > 0) return false;
	if(valor.indexOf(".com.br.") > 0) return false;
	if(valor.indexOf("/") > 0) return false;
	if(valor.indexOf("[") > 0) return false;
	if(valor.indexOf("]") > 0) return false;
	if(valor.indexOf("(") > 0) return false;
	if(valor.indexOf(")") > 0) return false;
	if(valor.indexOf("..") > 0) return false;
	if(valor.indexOf(",") > 0) return false;
	if(valor.indexOf(".") == (valor.length - 1)) return false;
	return true;
}
function validaBens(bem) {

    if (!EhNumero(bem))
       return false;

 var vlBem = limpaStringNumerica( bem.value );

  if (vlBem > 20000)
      return aviso(bem,"Não pode utilizar a declaração simplificada on-line, o contribuinte cujo valor do patrimônio em 31/12/2004 é superior a R$20.000,00.");
  return true;
}
function validaOcup(natur,ocup){

	var natureza = natur.options[natur.selectedIndex].value;
	if (isEmpty(ocup.value)) {
		if ( natureza != "13" && natureza != "61" && natureza != "71" && natureza != "72" && natureza != "81" && natureza != "62" )
		{
			return aviso(ocup,"Código de ocupação deve ser informado.");
		}
		return true;
	}

	if (!isInteger(ocup.value) )
		return aviso(ocup,'Código de ocupação deve ser numérico.');

	return true;
}

// Valida o combo natureza da d
function validaNat(nat){

	if (nat.options[nat.selectedIndex].value == "0")
		return aviso(nat,"Natureza da ocupação deve ser selecionada.");

	if (!isInteger(nat.options[nat.selectedIndex].value) )
		return aviso(nat,'Natureza da ocupação deve ser numérica.');

	//  if (nat.options[nat.selectedIndex].value == "0") return aviso(f.CD_OCUP,"Declaração de espólio não pode ser apresentada em formulário on line.")
	return true;
}

// Valida o campo com o número do banco da restituição
// Deve ser numérico com 3 dígitos
function validaBanco(){

	if ((f.NR_BANCO.value.length != 3))
		return aviso(f.NR_BANCO,'Informe Código de Banco com 3(três) dígitos numéricos.');

	if (!isInteger(f.NR_BANCO.value) )
		return aviso(f.NR_BANCO,'Código de Banco deve ser numérico.');

	return true;
}


function validaCPF(rcpf1,c,bAceitaBranco) {

	if ((ContaDigitos(rcpf1.value) > 11 )) {
	   return aviso(rcpf1, c + " inválido.");
	}

	if ( bAceitaBranco == true && rcpf1.value == '' )
		return true;

	var CPFaux = RetiraCaracteresInvalidos(rcpf1.value,11);
	var NR_CPF = CPFaux.substr(0,9);
	var rcpf2 = CPFaux.substr(9,2);

	if ((isEmpty(NR_CPF)) && (isEmpty(foco)) && bAceitaBranco == false) {
		return aviso(rcpf1, c + " inválido.");
	}

	if( CPFaux == "00000000000" || CPFaux == "00000000191" || CPFaux == "99999999999")
		return aviso(rcpf1,c + " inválido.");

  d1 = 0;
  for (i=0;i<9;i++)
    d1 += NR_CPF.charAt(i)*(10-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (rcpf2.charAt(0) != d1)
    return aviso(rcpf1,c+" inválido.");

  d1 *= 2;
  for (i=0;i<9;i++)
    d1 += NR_CPF.charAt(i)*(11-i);
  d1 = 11 - (d1 % 11);
  if (d1>9) d1 = 0;

  if (rcpf2.charAt(1) != d1)
    return aviso(rcpf1,c+" inválido.");

  return true;

}

function validaTIT(campoTit) {

	var valorTit = campoTit.value;

	// Campo título de eleitor é opcional
	if (valorTit.length == 0)
		return true;

	// Completa o campo com zeros à esquerda
	valorTit = PoeZeros(valorTit,13);

	if( !( isInteger(valorTit)) ) {
		campoTit.value = '';
		alert("Número do título eleitoral deve ser numérico.");
		return true;
	}

	campoTit2 = valorTit.substr(11,2);
	j = valorTit.substr(9,2);

	if ( (j<1) || (j>28) ) {
		campoTit.value = '';
		alert("Número do título eleitoral inválido.");
		return true;
	}

	d1 = 0;
	for (i=0;i<9;i++)
		d1 += valorTit.charAt(i)*(10-i);

	d1 = (d1 % 11);
	if (d1<=1)
	{
		if (j<=2)
			d1 = 1 - d1;
		else
			d1 = 0;
	}
	else
		d1 = 11 - d1;

	if (campoTit2.charAt(0) != d1) {
		campoTit.value = '';
		alert("Número do título eleitoral inválido.")
		return true;
	}
	d1 *= 2;
	for (i=9;i<11;i++)
		d1 += valorTit.charAt(i)*(13-i);

	d1 = (d1 % 11);
	if (d1<=1)
	{
		if (j<=2)
			d1 = 1 - d1;
		else
			d1 = 0;
	}
	else
		d1 = 11 - d1;

	if (campoTit2.charAt(1) != d1) {
		campoTit.value = '';
		alert("Número do título eleitoral inválido.")
	}
	return true;
}
function PoeZeros(valor,tam) {

	while( valor.length < tam )
		valor = '0'.toString() + valor.toString();

	return valor;
}
function EhNumero(field) {
        if (field.value.length == 0) return true;
        if (!isFloat(field) )
 //           return aviso(field,"Digite um valor numérico com no máximo 13 dígitos.\nNão utilize ponto.\nOs centavos devem ser separados por vírgula.\n       Ex.:   1387,98");
   return aviso(field,"Digite os campos de valores com centavos, inclusive centavos 00, sem ponto nem vírgula.");
        return true;
    }

function EhNumeroPuro(field) {
        var valor = field.value;
        if ( !isInteger(valor) )
            return aviso(field,"Digite um valor numérico sem valores decimais.\nEx.:   13");

        return true;
    }

function isDigit (c){

	    return ((c >= "0") && (c <= "9"))
    }

function isInteger (s) {

    var i;

    if (isEmpty(s))
       if (isInteger.arguments.length == 1) return false;

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}

function isMes (s) {

//  Testa se é mes válido
//
   if (isEmpty(s)) return false;
   return ((s.length == 2) && isIntegerInRange (s, 1, 12));
}

function isDia (s) {

    if (isEmpty(s)) return false;
    return ((s.length == 2) && isIntegerInRange (s, 1, 31));
}

function isAno (s) {

    if (isEmpty(s)) return false;
    if (!isInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function diasInFevereiro (ano){

    return (  ((ano % 4 == 0) && ( (!(ano % 100 == 0)) || (ano % 400 == 0) ) ) ? 29 : 28 );
}

function validaData (dia, mes, ano) {

    if (isEmpty(ano.value) && isEmpty(mes.value) && isEmpty(dia.value)) return aviso(dia,"Informe a data de nascimento.");

    if (!(isAno(ano.value) && isMes(mes.value) && isDia(dia.value))) return aviso(dia,"Data de nascimento inválida.");

    var intAno = parseInt(ano.value,10);
    var intMes = parseInt(mes.value,10);
    var intDia = parseInt(dia.value,10);
    dias = new Array(13);
    dias[1] = 31;
    dias[2] = diasInFevereiro(intAno);
    dias[3] = 31;
    dias[4] = 30;
    dias[5] = 31;
    dias[6] = 30;
    dias[7] = 31;
    dias[8] = 31;
    dias[9] = 30;
    dias[10] = 31;
    dias[11] = 30;
    dias[12] = 31;

    if (intDia > dias[intMes]) return aviso(dia,"Data de nascimento inválida.");

    if (ano.value.length == 2)
	ano.value = "19" + ano.value;

    if (ano.value > "2004") return aviso(dia,"Data de nascimento inválida.");

    if (ano.value < "1850") return aviso(dia,"Ano informado inválido.");

    return true;
}

//Verifica se CPF é válido
function TestaCPF(strCPF) {
	var Soma;
	var Resto;

	Soma = 0;
	strCPF  = RetiraCaracteresInvalidos(strCPF,11);

	if (strCPF == "00000000000")
		return false;

	for (i=1; i<=9; i++)
		Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (11 - i);

	Resto = (Soma * 10) % 11;

	if ((Resto == 10) || (Resto == 11))
		Resto = 0;

	if (Resto != parseInt(strCPF.substring(9, 10)) )
		return false;

	Soma = 0;
	for (i = 1; i <= 10; i++)
	   Soma = Soma + parseInt(strCPF.substring(i-1, i)) * (12 - i);

	Resto = (Soma * 10) % 11;
	if ((Resto == 10) || (Resto == 11))
		Resto = 0;

	if (Resto != parseInt(strCPF.substring(10, 11) ) )
		return false;

	return true;
}

//Verifica se CNPJ é válido
function TestaCNPJ(cgc) {
    var CGC1, CGC2, Matriz;
    var Soma, Digito;
    var i , j;
    var ContIni , ContFim;
    var controle;
	cgc  = RetiraCaracteresInvalidos(cgc,14);
	if  (cgc == "00000000000000")
		return false;

	CGC1 = cgc.substring(0,12);
    CGC2 = cgc.substring(12,14);
    controle = "";
    ContIni = 1;
    ContFim = 12;
    K = 0;
    for (j = 1; j <= 2; j++)
    {
		Soma = 0;
		for (i = ContIni; i <=ContFim; i++)
		{
			Mult = (ContFim + 1 + j - i);
			if (Mult > 9) Mult = Mult - 8;
			Soma = Soma + (parseInt(CGC1.substring(i - j, i-K)) * Mult);
		}

		if (j == 2) Soma = Soma + (2 * Digito);
		Digito = (Soma * 10) % 11;
		if (Digito == 10) Digito = 0;
		controle = controle + Digito;
		ContIni = 2;
		K=1;
		ContFim = 13;
    }

	if (controle != CGC2) return false; return true;
}

// Valida o campo "fonte pagadora", que pode ser vazio, um cpf ou um cgc
function validaFontePagadora( podeVazio ) {

	var obj = f.NR_FONTE_PAGADORA;
	var valor = obj.value;

	// A fonte pagadora pode estar vazia
	if ( podeVazio && valor == '' )
		return true;

	// Pode ser tanto CPF quanto CNPJ
	if ( TestaCPF(valor) || TestaCNPJ(valor) )
		return true;

	if ( !podeVazio )
		aviso( obj, "CNPJ/CPF da única fonte pagadora em branco ou inválido." );
	else
		aviso( obj, "CNPJ/CPF da única fonte pagadora inválido." );
	
	return false;

}

function isFloat (f) {
	var i;
    var decimalPointDelimiter = ",";
    var seenDecimalPoint = false;
    var posDecPoint = 0;
    var s = f.value.replace( /\./g, '' );

    if (isEmpty(s))
       if (isFloat.arguments.length == 1) return false;
         else return true;

    if (s == decimalPointDelimiter) return false;

    for (i = 0; i < s.length; i++)
    {
        var c = s.charAt(i);
        if ( (c == decimalPointDelimiter) && !seenDecimalPoint){
              posDecPoint = i;
              seenDecimalPoint = true }
         else {
              if (!isDigit(c)) return false;}
    }
//    if (!seenDecimalPoint)
//       {f.value += ",00";}
//    else
//        {  s = f.value + "00";
//           f.value= s.charAt(0);
//           for (i = 1; i <= (posDecPoint+2); i++){
//               f.value += s.charAt(i);
//           }
//           if (posDecPoint == 0 ) f.value = "0"+f.value;
//        }

    if (f.value.length > 17)
			return false;
    return true;
}

function isEmpty(s){
    return ((s == null) || (s.length == 0))
}

// Verifica se há somente dígitos na string
// Retorna true se todos forem dígitos ou false caso contrário
function somenteDigito( str ) {
	var re = /^[0-9]+$/;
	if ( re.exec( str ) )
		return true;
	return false;
}
// Valida todos os campos de telefone
function validaFones() {

	if ( !isEmpty( f.txtdddtel.value ) && !somenteDigito( f.txtdddtel.value ) ) {
		aviso( f.txtdddtel, "DDD inválido." );
		return false;
	}

	if ( !isEmpty( f.txttelefone.value ) && !somenteDigito( f.txttelefone.value ) ) {
		aviso( f.txttelefone, "Telefone inválido." );
		return false;
	}

	if ( !isEmpty( f.txtdddfax.value ) && !somenteDigito( f.txtdddfax.value ) ) {
		aviso( f.txtdddfax, "DDD do fax inválido." );
		return false;
	}

	if ( !isEmpty( f.txtfax.value ) && !somenteDigito( f.txtfax.value ) ) {
		aviso( f.txtfax, "Fax inválido." );
		return false;
	}

	return true;

}
