//Função para validação do CADASTRO

//////////////////////////////////////////////////////////////////////////////////////////////////////////

//Função Padrão de Validação de Campos.
	//Exemplo de como usar
	//if ( fnTestaCampo ( "Nome" , form.nome , 0 , 'T' ) == false ) return false ;
	function fnTestaCampo(strLblCampo,strCampo,intTamanho,strTipo)
	{
		//T - Input Text Caracter
		//N - Input Text Inteiro
		//R - Radio Button
		//C - Checkbox
		//S - Select
        //E - Input Text Caracter E-Mail
		
		if ((strTipo == "T") || (strTipo == "E"))
		{
			if (strCampo.value.length == 0 || strCampo.value.length < intTamanho)
			{
				alert("Por favor, preencha o campo " + strLblCampo + " corretamente.");
				strCampo.focus();
				return false;
			}
            else if (strTipo == "E")
            {
                //	
                if ((strCampo.value.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) || (strCampo.value == "Email:") || (strCampo.value == "E-mail:")) 
            	{
            		alert("Por favor, preencha o campo " + strLblCampo + " corretamente.");
                    strCampo.focus();
            		return false;
            	}
            }
		}
        else if ( strTipo == "R" )
		{
            var contador ;
            var flag ;
            
            flag = false ;
            
            for ( contador = 0 ; contador < strCampo.length ; contador ++ )
            {
                if ( strCampo[contador].checked )
                {
                    flag = true ;
                }
            }
            
            if ( !flag )
            {
                alert("Por favor, preencha o campo " + strLblCampo + " corretamente.");
                return false ;
            }
		}
		else if ( strTipo == "C" )
		{
			if ( strCampo.checked  == false )
			{
				alert("Por favor, preencha o campo " + strLblCampo + " corretamente.");
				return false ;
			}
		}
		else if ( strTipo == "S" )
		{
			if ( strCampo.selectedIndex == -1 || strCampo.value == "" || strCampo.options[strCampo.selectedIndex].text == "")
			{
				alert("Por favor, preencha o campo " + strLblCampo + " corretamente.");
				return false;
			}
		}
	}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//Funcao da Mascara
function fnMascara(objeto, evt, mask)
{ 
	var LetrasU = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var LetrasL = 'abcdefghijklmnopqrstuvwxyz';
	var Letras  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';	
	var Numeros = '0123456789';
	var Fixos  = '().-:/ ';
	var Charset = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_/`abcdefghijklmnopqrstuvwxyz{|}~";

	evt = (evt) ? evt : (window.event) ? window.event : "";
	var value = objeto.value;
	if (evt) {
 	var ntecla = (evt.which) ? evt.which : evt.keyCode;
 	tecla = Charset.substr(ntecla - 32, 1);
 	if (ntecla < 32) return true;

 	var tamanho = value.length;
 	if (tamanho >= mask.length) return false;

 	var pos = mask.substr(tamanho,1);
 	while (Fixos.indexOf(pos) != -1)
	 	{
 	 		value += pos;
 	 		tamanho = value.length;
 	 		if (tamanho >= mask.length) return false;
 	 		pos = mask.substr(tamanho,1);
		}

 	switch (pos) 
		{
   			case '#' : if (Numeros.indexOf(tecla) == -1) return false; break;
   			case 'A' : if (LetrasU.indexOf(tecla) == -1) return false; break;
   			case 'a' : if (LetrasL.indexOf(tecla) == -1) return false; break;
   			case 'Z' : if (Letras.indexOf(tecla) == -1) return false; break;
   			case '*' : objeto.value = value; return true; break;
   			default : return false; break;
 		}
	}
	objeto.value = value;
	return true;
}

/////////////////////////////////////////////////////////////////////////////////////////////////

//verifica CPF
function fVerificaCPF(campo) {
	var CPF = campo.value; // Recebe o valor digitado no campo
	CPF = CPF.replace("-", "");
	CPF = CPF.replace(".", "");
	CPF = CPF.replace(".", "");
	
	if( (CPF == '11111111111') || (CPF == '22222222222') || (CPF == '33333333333') || (CPF == '44444444444') ||
  		(CPF == '55555555555') || (CPF == '66666666666') || (CPF == '77777777777') || (CPF == '88888888888') ||
   		(CPF == '99999999999') || (CPF == '00000000000') )
	{
		  document.getElementById('cpf_erro').style.display = '';
		  document.getElementById('cpf_ok').style.display = 'none';
		  return false;				  
	}
	else
	{
		
		// Aqui começa a checagem do CPF
		var posicao, i, soma, dv, dv_informado;
		var digito = new Array(10);
		dv_informado = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado
		
		// Desemembra o número do CPF na array DIGITO
		for (i=0; i<=8; i++) {
		  digito[i] = CPF.substr( i, 1);
		}
		
		// Calcula o valor do 10º dígito da verificação
		posicao = 10;
		soma = 0;
		   for (i=0; i<=8; i++) {
			  soma = soma + digito[i] * posicao;
			  posicao = posicao - 1;
		   }
		digito[9] = soma % 11;
		   if (digito[9] < 2) {
				digito[9] = 0;
		}
		   else{
			   digito[9] = 11 - digito[9];
		}
		
		// Calcula o valor do 11º dígito da verificação
		posicao = 11;
		soma = 0;
		   for (i=0; i<=9; i++) {
			  soma = soma + digito[i] * posicao;
			  posicao = posicao - 1;
		   }
		digito[10] = soma % 11;
		   if (digito[10] < 2) {
				digito[10] = 0;
		   }
		   else {
				digito[10] = 11 - digito[10];
		   }
		
		// Verifica se os valores dos dígitos verificadores conferem
		dv = digito[9] * 10 + digito[10];
		   if (CPF.length > 0)
		   {
			   if (dv != dv_informado)  
			   {
				  document.getElementById('cpf_erro').style.display = '';
				  document.getElementById('cpf_ok').style.display = 'none';
				  return false;
			   }
			   else
			   {
				  document.getElementById('cpf_erro').style.display = 'none';
				  document.getElementById('cpf_ok').style.display = '';
				  return false;
			   }
			}
			else
			{
				document.getElementById('cpf_erro').style.display = 'none' ;
				document.getElementById('cpf_ok').style.display = 'none' ;
			}
		}
}

//verifica CNPJ
function fun_gera_verificacao_cnpj(CNPJ)
{
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessarios preencher corretamente o numero do CNPJ! \n\n";
	
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
	{
		if (erro.length == 0) erro += "É necessarios preencher corretamente o numero do CNPJ! \n\n";
	}
	//substituir os caracteres que nao sao numeros
	if(document.layers && parseInt(navigator.appVersion) == 4)
	{
		x = CNPJ.substring(0,2);
		x += CNPJ.substring(3,6);
		x += CNPJ.substring(7,10);
		x += CNPJ.substring(11,15);
		x += CNPJ.substring(16,18);
		CNPJ = x;
	}
	else
	{
		CNPJ = CNPJ.replace(".","");
		CNPJ = CNPJ.replace(".","");
		CNPJ = CNPJ.replace("-","");
		CNPJ = CNPJ.replace("/","");
	}
	
	if( (CNPJ == '11111111111111') || (CNPJ == '22222222222222') || (CNPJ == '33333333333333') || (CNPJ == '44444444444444') ||
		(CNPJ == '55555555555555') || (CNPJ == '66666666666666') || (CNPJ == '77777777777777') || (CNPJ == '88888888888888') ||
		(CNPJ == '99999999999999') || (CNPJ == '00000000000000') )
	{
		  document.getElementById('cnpj_erro').style.display = '';
		  document.getElementById('cnpj_ok').style.display = 'none';
		  return false;				  
	}
	else
	{
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificacao de CNPJ suporta apenas numeros! \n\n";
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		
		for (i=0; i<12; i++)
		{
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		b = 0;
		
		for (y=0; y<13; y++)
		{
			b += (a[y] * c[y]);
		}
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]))
		{
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0)
		{
		    document.getElementById('cnpj_erro').style.display = '';
		    document.getElementById('cnpj_ok').style.display = 'none';
			return false;
		}
		else
		{
			document.getElementById('cnpj_erro').style.display = 'none';
			document.getElementById('cnpj_ok').style.display = '';
		}
		return true;
	}
}
//Ainda Cnpj
function fun_toggle_instrucoes(div){
	_div = document.getElementById(div);

	novo_display = (_div.style.display == 'block') ? 'none' : 'block';
	novo_display_selects = (novo_display == 'none') ? '' : 'none';

	_div.style.display = novo_display;
	showOrHideAllDropDowns(novo_display_selects);
}

function showOrHideAllDropDowns(newState) {
	var elements = document.documentElement.getElementsByTagName('select');

	for (var i=0; i<elements.length; i++) {
		elements[i].style.display = newState;
	}
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////

//valida Cadastro
function verificaCadastro (form){
	if ( fnTestaCampo ( "Tipo" , form.tipopessoa , 0 , 'R' ) == false )
	return false ;
	
	for (i=0; i<form.tipopessoa.length; i++){
	
	if (form.tipopessoa[i].checked){
	resposta = form.tipopessoa[i].value
	
	if (resposta == "F"){
	
	if ( fnTestaCampo ( "CPF" , form.cpf , 0 , 'T' ) == false )
	return false ; 

	if (form.cpf.value==""){
	alert("Atenção!\nO campo CPF deve ser preenchido.");
	form.cpf.focus();
	return false;
	}
	
	else{
	fVerificaCPF(form.cpf);
	if(document.getElementById('cpf_ok').style.display == 'none'){
	alert("Atenção!\nDigite um CPF válido.");
	return false;
	}
	}

	if ( fnTestaCampo ( "Nome" , form.nome , 0 , 'T' ) == false )
	return false ;
	
	if ( fnTestaCampo ( "Profissão" , form.profissao , 0 , 'T' ) == false )
	return false ; 
	}

	else if(resposta == "J"){
	if ( fnTestaCampo ( "CNPJ" , form.cnpj , 0 , 'T' ) == false )
	return false ; 

	if (form.cnpj.value==""){
	alert("Atenção!\nO campo CNPJ deve ser preenchido.");
	form.cnpj.focus();
	return false;
	}
	
	else{
	var cnpj_valido = fun_gera_verificacao_cnpj(form.cnpj.value);
	if(document.getElementById('cnpj_ok').style.display == 'none'){
	alert("Atenção!\nDigite um CNPJ válido.");
	return false;
	}
	}

	if ( fnTestaCampo ( "Razão Social" , form.razaosocial , 0 , 'T' ) == false )
	return false ; 

	if ( fnTestaCampo ( "Cargo" , form.cargo , 0 , 'T' ) == false )
	return false ;
	}	
	}
	}

	if ( fnTestaCampo ( "Empresa" , form.empresa , 0 , 'T' ) == false )
	return false ; 

	if ( fnTestaCampo ( "Endereço" , form.endereco , 0 , 'T' ) == false )
	return false ; 

	if ( fnTestaCampo ( "E-mail" , form.email , 0 , 'E' ) == false )
	return false ; 
	
	if ( fnTestaCampo ( "Senha" , form.str_senha , 0 , 'T' ) == false )
	return false ;
	
	if ( fnTestaCampo ( "Telefone" , form.telefone , 13 , 'T' ) == false )
	return false ;
	
	if ( fnTestaCampo ( "Cidade" , form.cidade , 0 , 'T' ) == false )
	return false ; 
	
	if ( fnTestaCampo ( "Estado" , form.estado , 0 , 'S' ) == false )
	return false ; 

	/*if ( fnTestaCampo ( "Comentários" , form.comentario , 0 , 'T' ) == false )
	return false ;*/
}

//troca jurídica por física
function fnMuda_FisJur(tipo){
	if (tipo == 'F'){
		//Aparecem esses campos
		document.getElementById('fis_cpf').style.display = '';
		document.getElementById('fis_nome').style.display = '';
		document.getElementById('fis_prof').style.display = '';
		
		//Esconde esses campos
		document.getElementById('jur_cnpj').style.display = 'none';
		document.getElementById('jur_razaosocial').style.display = 'none';
		document.getElementById('jur_cargo').style.display = 'none';	
	}
	
	else if(tipo == 'J'){
		//Esconde esses campos
		document.getElementById('fis_cpf').style.display = 'none';
		document.getElementById('fis_nome').style.display = 'none';
		document.getElementById('fis_prof').style.display = 'none';
		
		//Aparecem esses campos
		document.getElementById('jur_cnpj').style.display = '';
		document.getElementById('jur_razaosocial').style.display = '';
		document.getElementById('jur_cargo').style.display = '';
	}

}