/***
* Descrição.: formata um campo do formulário de
* acordo com a máscara informada...
* Parâmetros: - objForm (o Objeto Form)
* - strField (string contendo o nome
* do textbox)
* - sMask (mascara que define o
* formato que o dado será apresentado,
* usando o algarismo "9" para
* definir números e o símbolo "!" para
* qualquer caracter...
* - evtKeyPress (evento)
* Uso.......: <input type="textbox"
* name="xxx".....
* onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);">
* Observação: As máscaras podem ser representadas como os exemplos abaixo:
* CEP -> 99.999-999
* CPF -> 999.999.999-99
* CNPJ -> 99.999.999/9999-99
* Data -> 99/99/9999
* Tel Resid -> (99) 999-9999
* Tel Cel -> (99) 9999-9999
* Processo -> 99.999999999/999-99
* C/C -> 999999-!
* E por aí vai...
***/

function txtBoxFormat(strField, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

    if(window.event) { // Internet Explorer
      nTecla = evtKeyPress.keyCode; }
    else if(evtKeyPress.which) { // Nestcape / firefox
      nTecla = evtKeyPress.which;
    }
    //se for backspace não faz nada
    if (nTecla != 8){
    sValue = document.getElementById(strField).value;
    // alert(sValue);

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
   expressao = /[\.\/\-\(\)\,\;\: ]/gi;
     sValue = sValue.toString().replace(expressao, '');
     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) == "/"))
      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++;
    }

    document.getElementById(strField).value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
      else { // qualquer caracter...
        return true;
      } }
    else {
      return true;
    }
    }//fim do if que verifica se é backspace
}
//Fim da Função Máscaras Gerais

function validar(obj) { // recebe um objeto
    var s = (obj.value).replace(/\D/g,'');
    var tam=(s).length; // removendo os caracteres não numéricos
    
// se for CPF
    if (tam==11 ){
        if (!validaCPF(s)){ // chama a função que valida o CPF
            //alert("'"+s+"' Não é um CPF válido!" ); // se quiser mostrar o erro
            //obj.select();  // se quiser selecionar o campo em questão
          return false;
       }
        //alert("'"+s+"' É um CPF válido!" ); // se quiser mostrar que validou        
        //obj.value=maskCPF(s);    // se validou o CPF mascaramos corretamente
        return true;
    }
    else{
    	alert("Preencha seu CPF corretamente.");
    	return false;
    }
}
function validaCPF(s) {
       cpf = s;
       erro = new String;
       if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
             var nonNumbers = /\D/;
             if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
                if (cpf == "12345678909" || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                   erro += "Numero de CPF invalido!"
                }
             var a = [];
             var b = new Number;
             var c = 11;
             for (i=0; i<11; i++){
                  a[i] = cpf.charAt(i);
                  if (i < 9) b += (a[i] * --c);
             }
             if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
  	            b = 0;
    	        c = 11;
                for (y=0; y<10; y++) b += (a[y] * c--);
              if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
               if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                       erro +="Numero de CPF invalido!";
               }
               if (erro.length > 0){
                       alert(erro);
                       return false;
               }
               return true;
}
function validaCPF2(s) {
       cpf = s;
       erro = new String;
       if (cpf.length < 11) erro += "- São necessários 11 dígitos para verificação do CPF. \n";
             var nonNumbers = /\D/;
             if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
                if (cpf == "12345678909" || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
                   erro += "- Numero de CPF inválido.\n"
                }
             var a = [];
             var b = new Number;
             var c = 11;
             for (i=0; i<11; i++){
                  a[i] = cpf.charAt(i);
                  if (i < 9) b += (a[i] * --c);
             }
             if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
  	            b = 0;
    	        c = 11;
                for (y=0; y<10; y++) b += (a[y] * c--);
              if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
               if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
                       erro +="- Numero de CPF inválido.\n";
               }
               if (erro.length > 0){
                       //alert(erro);
                       return erro;
               }
               return x='';
}

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_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  
  var obj=MM_findObj(args[3]);
  var s = (obj.value).replace(/\D/g,'') ;
 // var errors=validaCPF2(s);
  
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]); var lid=val.id; var campo=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) {errors += '- '+lid+': Email inválido!\n'; campo.style.backgroundColor='#FFFFCC';}
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') {errors += '- '+lid+'\n'; campo.style.backgroundColor='#FFFFCC';} }
  } 
  
  var errorsNat = validaNacionalidade();
  var errorsEnd = validaEndereco();
  var errorsFone = validaTelefones('Telefone Residencial', 'Telefone Comercial', 'Telefone Recado', 'Telefone Celular');

  errors += errorsNat;
  errors += errorsEnd; 
  errors += errorsFone;
  if (errors) alert('Por favor verifique:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function validaTelefones(){
	var args = validaTelefones.arguments;
	var i,n=0;
	var tel;
	for(i=0; i<args.length; i++){
		tel = MM_findObj(args[i]);
		if(tel.value.length!=12){
			n++;
		}
	}
	if(n==4){
		for(i=0; i<args.length; i++){
			tel = MM_findObj(args[i]);
			tel.style.backgroundColor='#FFFFCC';
		}
		return '- Digite pelo menos um telefone para contato.\n';
	}
	else{
		return '';
	}
}

function validaNacionalidade(){
	var erro = '';
	
	var pais 	= MM_findObj('Nacionalidade');
	var uf   	= MM_findObj('UF');
	var cidade  = MM_findObj('Naturalidade');
	
	
	if(pais.value==1){
		if(uf.value==""){
			erro += '- Estado\n';
			uf.style.backgroundColor='#FFFFCC';
		}
		else{
			if(cidade.value==""){
				erro += '- Naturalidade\n';
				cidade.style.backgroundColor='#FFFFCC';
			}
		}	
	}
	else if(pais.value==''){
		erro += '- Nacionalidade\n';
		pais.style.backgroundColor='#FFFFCC';
	}

	return erro;
}

function openLookupCep(){
   window.open("./sgn/inscricao/lookupCep.html","lookupCep","width=400,height=400,scrollbars=YES")
}

function retornaEndereco(id, tipoCep, id_logradouro, cep, id_uf, UF, id_cidade, cidade, tipo, endereco, id_bairro, bairro){
	var id = id;
	var tipoCep = tipoCep;
	var id_logradouro = id_logradouro;
	var cep = cep;
	var id_uf = id_uf;
	var UF = UF;
	var id_cidade = id_cidade;
	var cidade = cidade;
	var tipo = tipo;
	var endereco = endereco;
	var id_bairro = id_bairro;
	var bairro = bairro;
	
    //limpa os campos
	window.opener.document.inscricao.id_logradouro.value = '';
	window.opener.document.inscricao.tipoCep.value = '';
	window.opener.document.inscricao.CEP.value = '';
	window.opener.document.inscricao.CEP2.value = '';
	window.opener.document.inscricao.id_uf.value = '';
	window.opener.document.inscricao.end_estado.value = '';
	window.opener.document.inscricao.end_estado2.value = '';
	window.opener.document.inscricao.id_cidade.value = '';
	window.opener.document.inscricao.end_municipio.value = '';
	window.opener.document.inscricao.end_municipio2.value = '';
	window.opener.document.inscricao.end_tipo.value = '';
	window.opener.document.inscricao.end_tipo2.value = '';
	window.opener.document.inscricao.end_endereco.value = '';
	window.opener.document.inscricao.end_endereco2.value = '';
	window.opener.document.inscricao.id_bairro.value = '';
	window.opener.document.inscricao.end_bairro.value = '';
	window.opener.document.inscricao.end_bairro2.value = '';
	window.opener.document.inscricao.end_numero.value = '';
	window.opener.document.inscricao.end_complemento.value = '';
	
	//preenche com os valores
	window.opener.document.inscricao.id_logradouro.value = id_logradouro;
	window.opener.document.inscricao.tipoCep.value = tipoCep;
	window.opener.document.inscricao.CEP.value = cep;
	window.opener.document.inscricao.CEP2.value = cep;
	window.opener.document.inscricao.id_uf.value = id_uf;
	window.opener.document.inscricao.end_estado.value = UF;
	window.opener.document.inscricao.end_estado2.value = UF;
	window.opener.document.inscricao.id_cidade.value = id_cidade;
	window.opener.document.inscricao.end_municipio.value = cidade;
	window.opener.document.inscricao.end_municipio2.value = cidade;
	window.opener.document.inscricao.end_tipo.value = tipo;
	window.opener.document.inscricao.end_tipo2.value = tipo;
	window.opener.document.inscricao.end_endereco.value = endereco;
	window.opener.document.inscricao.end_endereco2.value = endereco;
	window.opener.document.inscricao.id_bairro.value = id_bairro;
	window.opener.document.inscricao.end_bairro.value = bairro;
	window.opener.document.inscricao.end_bairro2.value = bairro;
	
	//bloqueio dos campos e alteracao de css
	if(tipoCep=='logradouro'){
		window.opener.document.inscricao.CEP2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_estado2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_municipio2.style.backgroundColor = '#DFDFDF';
		
		window.opener.document.inscricao.end_tipo2.disabled = true;
		window.opener.document.inscricao.end_tipo2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_endereco2.disabled = true;
		window.opener.document.inscricao.end_endereco2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_bairro2.disabled = true;
		window.opener.document.inscricao.end_bairro2.style.backgroundColor = '#DFDFDF';
		
	}
	else if(tipoCep=='cidade'){
		window.opener.document.inscricao.CEP2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_estado2.style.backgroundColor = '#DFDFDF';
		window.opener.document.inscricao.end_municipio2.style.backgroundColor = '#DFDFDF';
		
		window.opener.document.inscricao.end_tipo2.disabled = false;
		window.opener.document.inscricao.end_tipo2.style.backgroundColor = '#F1F1F1';
		window.opener.document.inscricao.end_endereco2.disabled = false;
		window.opener.document.inscricao.end_endereco2.style.backgroundColor = '#F1F1F1';
		window.opener.document.inscricao.end_bairro2.disabled = false;
		window.opener.document.inscricao.end_bairro2.style.backgroundColor = '#F1F1F1';
	}
	
	window.close();
}


function limpaEndereco(){
	document.getElementById('CEP').value = '';
	document.getElementById('CEP2').value = '';
	document.getElementById('id_logradouro').value = '';
	document.getElementById('tipoCep').value = '';
	document.getElementById('end_estado').value = '';
	document.getElementById('end_estado2').value = '';
	document.getElementById('id_uf').value = '';
	document.getElementById('end_municipio').value = '';
	document.getElementById('end_municipio2').value = '';
	document.getElementById('id_cidade').value = '';
	document.getElementById('end_tipo').value = '';
	document.getElementById('end_tipo2').value = '';
	document.getElementById('end_endereco').value = '';
	document.getElementById('end_endereco2').value = '';
	document.getElementById('end_numero').value = '';
	document.getElementById('end_complemento').value = '';
	document.getElementById('end_bairro').value = '';
	document.getElementById('end_bairro2').value = '';
	document.getElementById('id_bairro').value = '';
	
	document.getElementById('CEP2').style.backgroundColor = '#DFDFDF';
	document.getElementById('end_estado2').style.backgroundColor = '#DFDFDF';
	document.getElementById('end_municipio2').style.backgroundColor = '#DFDFDF';
	
	document.getElementById('end_tipo2').disabled = false;
	document.getElementById('end_tipo2').style.backgroundColor = '#F1F1F1';
	document.getElementById('end_endereco2').disabled = false;
	document.getElementById('end_endereco2').style.backgroundColor = '#F1F1F1';
	document.getElementById('end_bairro2').disabled = false;
	document.getElementById('end_bairro2').style.backgroundColor = '#F1F1F1';
	
	document.getElementById('end_numero').style.backgroundColor = '#F1F1F1';
	document.getElementById('end_complemento').style.backgroundColor = '#F1F1F1';
	
	
}

function validaEndereco(){
	var erro = '';
	
	var tipoCep			= MM_findObj('tipoCep');
	var id_logradouro	= MM_findObj('id_logradouro');
	var cep				= MM_findObj('CEP');
	var cep2			= MM_findObj('CEP2');
	var id_uf 			= MM_findObj('id_uf');
	var end_estado 		= MM_findObj('end_estado');
	var end_estado2 	= MM_findObj('end_estado2');
	var id_cidade		= MM_findObj('id_cidade');
	var end_municipio 	= MM_findObj('end_municipio');
	var end_municipio2 	= MM_findObj('end_municipio2');
	var end_tipo 		= MM_findObj('end_tipo');
	var end_tipo2 		= MM_findObj('end_tipo2');
	var end_endereco  	= MM_findObj('end_endereco');
	var end_endereco2  	= MM_findObj('end_endereco2');
	var end_numero  	= MM_findObj('end_numero');
	var end_complemento = MM_findObj('end_complemento');
	var id_bairro 		= MM_findObj('id_bairro');
	var end_bairro 		= MM_findObj('end_bairro');
	var end_bairro2 	= MM_findObj('end_bairro2');
	
	
	if(tipoCep.value=='logradouro'){
		if(id_logradouro.value=='' || cep.value=='' || cep2.value=='' || cep.value!=cep2.value){
			erro += '- CEP\n';
			cep2.style.backgroundColor='#FFFFCC';
		}
		if(id_cidade.value=='' || end_municipio.value=='' || end_municipio2.value=='' || end_municipio.value!=end_municipio2.value){
			erro += '- Município\n';
			end_municipio2.style.backgroundColor='#FFFFCC';
		}
		if(id_uf.value=='' || end_estado.value=='' || end_estado2.value=='' || end_estado.value!=end_estado2.value){
			erro += '- Estado (Endereço)\n';
			end_estado2.style.backgroundColor='#FFFFCC';
		}
		if(end_tipo.value=='' || end_tipo2.value=='' || end_tipo.value!=end_tipo2.value){
			erro += '- Tipo de logradouro\n';
			end_tipo2.style.backgroundColor='#FFFFCC';
		}
		if(end_endereco.value=='' || end_endereco2.value=='' || end_endereco.value!=end_endereco2.value){
			erro += '- Endereço\n';
			end_endereco2.style.backgroundColor='#FFFFCC';
		}
		if(id_bairro.value=='' || end_bairro.value=='' || end_bairro2.value=='' || end_bairro.value!=end_bairro2.value){
			erro += '- Bairro\n';
			end_bairro2.style.backgroundColor='#FFFFCC';
		}
	}
	
	
	else if(tipoCep.value=='cidade'){
		if(cep.value=='' || cep2.value=='' || cep.value!=cep2.value){
			erro += '- CEP\n';
			cep2.style.backgroundColor='#FFFFCC';
		}
		if(id_cidade.value=='' || end_municipio.value=='' || end_municipio2.value=='' || end_municipio.value!=end_municipio2.value){
			erro += '- Município\n';
			end_municipio2.style.backgroundColor='#FFFFCC';
		}
		if(id_uf.value=='' || end_estado.value=='' || end_estado2.value=='' || end_estado.value!=end_estado2.value){
			erro += '- Estado (Endereço)\n';
			end_estado2.style.backgroundColor='#FFFFCC';
		}
		if(end_tipo2.value==''){
			erro += '- Tipo de logradouro\n';
			end_tipo2.style.backgroundColor='#FFFFCC';
		}
		if(end_endereco2.value==''){
			erro += '- Endereço\n';
			end_endereco2.style.backgroundColor='#FFFFCC';
		}
		if(end_bairro2.value==''){
			erro += '- Bairro\n';
			end_bairro2.style.backgroundColor='#FFFFCC';
		}
	}

	else if(tipoCep.value!='cidade' && tipoCep.value!='logradouro'){
		erro += '- Formulário de Endereço\n';
		cep2.style.backgroundColor='#FFFFCC';
		end_municipio2.style.backgroundColor='#FFFFCC';
		end_estado2.style.backgroundColor='#FFFFCC';
		end_tipo2.style.backgroundColor='#FFFFCC';
		end_endereco2.style.backgroundColor='#FFFFCC';
		end_bairro2.style.backgroundColor='#FFFFCC';
		end_numero.style.backgroundColor='#FFFFCC';
		end_complemento.style.backgroundColor='#FFFFCC';
		
	}

	return erro;
}