//valida cada campo obrigatorio do formulario e envia
//primeiro argumento é o próprio form
//depois vão os pares: 'campo,validação','campo2,validação2'
//exemplo: validaForm(this.form,'nome,obrigatorio','nome,alfabetico','email,email','cpf,cpf')
function validaForm()
{
	var frmVal = validaForm.arguments[0];

	var indArgs = 1;
	var FormOk  = true;

	while ((indArgs < validaForm.arguments.length) && (FormOk))
	{
		arrForm = validaForm.arguments[indArgs].split(",");
		if (!valida(frmVal.elements[arrForm[0]],arrForm[1]) && FormOk)
		{
			FormOk = false;
			return false;
		}
		indArgs++;
	}

	/*
	if(!verificaArray(frmVal.escolha))
	{
		alert("É necessário selecionar alguma opção.");
		return false;
	}
	*/
	return true;
}



// Início da Função de Validação

function valida(referenciaElemento,validacao) {

var valorCampo = referenciaElemento.value;
var nomeCampo = referenciaElemento.name;
var validacoes = new Array();

// Abaixo a declaracao das expressoes regulares

validacoes.obrigatorio = /[^\s]+/i;
validacoes.alfabetico = /[a-z]/i;
validacoes.alfanumerico = /[a-z_0-9]/i;
validacoes.texto = /[\w]/i;
validacoes.numerico = /^\d*$/;		
validacoes.data = /^\d{2}\/\d{2}\/\d{4}$/;
validacoes.email = /^[a-z]([a-z_.-0-9]*)@[a-z0-9]+(\.[a-z0-9]*)+$/i;
validacoes.moeda = /^(R\$\s?)?\d{1,3}(\.?\d{3})*(\,\d{2})?$/;
validacoes.telefone = /^\([1-9][1-9]\)|[1-9][1-9]\s\d{3,4}([\-\s]?\d{4})$/;
validacoes.cep = /^\d{5}(-?\d{3})$/;
validacoes.horario = /^([0-1][0-9]|[0-9]|2[0-3])[:,h][0-5]\d[:,m][0-5]\d[h,m,s]?$/i;
validacoes.uf = /^AC$|^AL$|^AP$|^AM$|^BA$|^CE$|^DF$|^ES$|^GO$|^MA$|^MT$|^MS$|^MG$|^PA$|^PB$|^PR$|^PE$|^PI$|^RJ$|^RN$|^RS$|^RO$|^RR$|^SC$|^SP$|^SE$|^TO$/i;
validacoes.sexo = /m|f/i;
validacoes.cpf = /(\d{3}\.?){2}(\d{3}-?)\d{2}$/i;
validacoes.cnpj = /(\d{8}\.?){2}(\d{3}-?)\d{2}$/i

//falta a validação de CNPJ

// Fim da declaração das Expressões Regulares

var mensagem = new Array();

// Mensagens de erro

mensagem.obrigatorio = "Este campo é obrigatório.";
mensagem.alfabetico = "Neste campo são permitidos somente letras.";
mensagem.alfanumerico = "Neste campo são permitidos letras, números e caracteres especiais.";
mensagem.texto = "Neste campo são permitidos letras, números e caracteres especiais.";
mensagem.numerico = "Este campo é numérico.";
mensagem.data = "Insira apenas data neste campo, no formato xx/xx/xxxx.";
mensagem.email = "Entre com um e-mail válido.";
mensagem.moeda = "Insira apenas valores de moeda.";
mensagem.telefone = "Entre com o código de área e o telefone.\nFormato: xx xxx-xxxx";
mensagem.cep = "Insira um CEP válido, com 8 dígitos.";
mensagem.horario = "Insira um horário válido.";
mensagem.uf = "Entre com uma UF válida.";
mensagem.sexo = "Sexo M ou F.";
mensagem.cpf = "Insira um CPF válido.";

// Fim das mensagens de erro


	//só aceita campo vazio se não for 'obrigatorio'
	if (valorCampo == null | valorCampo == "" && validacao != "obrigatorio") return true;
	if (referenciaElemento.length && validacao == "obrigatorio")
	{
		if(!verificaArray(referenciaElemento))
		{
			alert("É necessário selecionar alguma opção.");
			return false;
		}
	}
	
	var expressao = validacoes[validacao];
	var validado = expressao.test(valorCampo);
	
	//outras validações com cálculos
	if(validado)
	{
		switch(validacao)
		{
			case "cpf"	:
				valorCampo = valorCampo.replace(/\./g,"");
				valorCampo = valorCampo.replace(/-/g,"");
				validado = validaCpf(valorCampo);
				break;
			case "cnpj"	:
				validado = validaCnpj(valorCampo);
				break;
		}
	}
		if(!validado){
		alert(mensagem[validacao]);
		referenciaElemento.focus();
		referenciaElemento.select();
		
		return false
		} 
		
		else {		
		return true
		}
	
}

function verificaArray(arr)
{
	var ok = false;
	if(arr)
	{
		if(arr.length)
		{
			for(i=0;i<arr.length;i++) if(arr[i].checked) ok = true;
		}
		else if(arr.checked) ok = true;
	}
	return ok;
}

function validaCpf(s) {
	var varFirstChr = s.charAt(0);
	var vaCharCPF = false;

	for ( var i=0; i<=10; i++ ) { 
		var c = s.charAt(i);
        if((c < '0') || (c > '9')) { 
			return false;
	    } 
        if( c != varFirstChr ) vaCharCPF = true; 
	} 
	
    if(!vaCharCPF) { 
		return false;
    } 	

	soma=0;
	for (i=0; i < 9; i++) { 
		soma += (10 - i) * (eval(s.charAt(i)));	
	} 

	digito_verificador = 11 - (soma % 11);
	if ((soma % 11) < 2) digito_verificador = 0;
	if (eval(s.charAt(9)) != digito_verificador) {
		return false;
	} 

	soma=0;
	for ( i=0; i<9; i++ ) {
		soma += (11-i) * ( eval(s.charAt(i)) ); 
	}
	soma += 2 * ( eval(s.charAt(9)) );
	digito_verificador = 11 - (soma % 11);
	if ((soma % 11) < 2) digito_verificador = 0;
	if (eval(s.charAt(10)) != digito_verificador) { 
		return false; 
	} 

	return true;
}

function validaCNPJ(s)
{
var c;
var Soma1, Soma2, Digito1, Digito2, i;
var CGC;
var V;

function CriaArray (n) 
{
 this.length = n 
}
V = new CriaArray(14)
 
CGC = "";
Soma1 = 0;
Soma2 = 0;
Digito1 = 0;
Digito2 = 0;
 
for (i = 0; i < s.length; i++)
{
   c = s.substring(i, i+1);
   if ((c >= '0') && (c <= '9'))
      CGC = CGC + c;
}
 
if (CGC.length == 14)
{
 for (i = 0; i < CGC.length; i++)
 {
  V[i] = parseFloat(CGC.substring(i, i + 1));
    }
 Soma1 = (V[11] * 2) + (V[10] * 3) + (V[9] * 4) + (V[8] * 5) + 
             (V[7] * 6) + (V[6] * 7) + (V[5] * 8) + (V[4] * 9) + 
             (V[3] * 2) + (V[2] * 3) + (V[1] * 4) + (V[0] * 5);
    Soma2 = (V[12] * 2) + (V[11] * 3) + (V[10] * 4) + (V[9] * 5) + 
             (V[8] * 6) + (V[7] * 7) + (V[6] * 8) + (V[5] * 9) + 
             (V[4] * 2) + (V[3] * 3) + (V[2] * 4) + (V[1] * 5) + 
             (V[0] * 6);
 
 Digito1 = Soma1 - parseInt(Soma1 / 11) * 11;
 if ((Digito1 == 0) || (Digito1 == 1)) 
  Digito1 = 0;
 else
  Digito1 = 11 - Digito1;
     
 Digito2 = Soma2 - parseInt(Soma2 / 11) * 11;
 if ((Digito2 == 0) || (Digito2 == 1))
  Digito2 = 0;
 else
  Digito2 = 11 - Digito2;
  
 if ((Digito1 == V[12]) && (Digito2 == V[13]) && (Soma1 != 0) && (Soma2 != 0))
 {
  return true;
 }
}
return false;
}

function ValidaEmail(email) {
	var achou_ponto=false;
	var achou_arroba=false;
	var achou_caracter=false;
	for (var i=0; i<email.length; i++) {
		if (email.charAt(i)=="@") achou_arroba=true;
		else if (email.charAt(i)==".") achou_ponto=true;
		else if (email.charAt(i)!=" ") achou_caracter=true;
	}

	if (achou_ponto == true && achou_arroba == true && achou_caracter == true)
	{
			return true;
		}
		else
		{	
			return false;
		}
}
