/******************************* INSTRUCOES ******************************
 * 
 * @author Aline de Jesus Matos Santos
 * 
 * 1) Defina o button do formulario com class="btn_envia"
 *
 * 2) Para que um campo input seja validado, utilize o class="required"
 *    Ex. <input type="text" id="nome" class="required">
 *
 * 3) Para validacoes especificas, utilize:
 *    - Email: class="required email"
 *    - CPF  : class="required cpf"
 *    - Data : class="required data"
 *    - CNPJ : class="required cnpj"
 *    - Nome : class="required sobrenome"
 * 
 * 4) O alert aparecera o "id" do campo
 *
 * 5) Nos campos type radio ou checkbox, o alert sera o "name"
 *
 * 6) Acrescente quantas funcoes quiser, desde que siga essa estrutura:
 *    - validaNOMEDACLASSE(valor)
 * ***********************************************************************
 */

$(document).ready(initValidate);

/**
 * Funcao disparada quando a pagina carrega
 */
function initValidate() 
{
	var retorno = $('#btn_envia').click(validacoes);
	 $('#btn_cadastrado').click(validacoes);
}

/**
 * Controla as validacoes
 */ 
function validacoes()
{
	if ($('#confirmaAva').val() == 1) {
		$('#formCadastrado').submit();
		return false;
	}
	
	// Valida confirmação do email	
	if(!validaCONFIRMAEMAIL()){
		alert('E-mail de confirmação não confere com o E-mail de cadastro.');	
		return false;
	}
	
	// Valida confirmação da senha	
	//if(!validaCONFIRMASENHA()){
	//	alert('Senha de confirmação não confere com a Senha de cadastro.');	
	//	return false;
	//}	
	
	var msg    = 'Por favor preencha corretamente os seguintes campo(s): \n';
	var error  = 0;
	var count  = 1;
	var classe = '';
	var aux	   = '';
	var valor  = '';
	var nome   = '';
	
	// Percorre os campos requeridos e verifica se foram preenchidos
	$('.required').each(function(i){
        if ($(this).val() == '') {
            msg += '\n' + count + ') ' + this.id;
			msg = msg.toUpperCase();
            error++; count++;
        }else{
			classe = $(this).attr('class').split(' ');
			// Faz as validacoes especificas
			if(classe.length > 1){
				aux   = $.trim(classe[1]).toUpperCase();
				valor = $('.'+$.trim(classe[1])).val();
				func = ('valida' + aux + '("' + valor + '")');
				if(!eval(func)){
					msg += '\n' + count + ') ' + this.id + ' INVÁLIDO(A)';
					msg = msg.toUpperCase();
					error++; count++;
				}
			} 
		}
		// Valida os campos do tipo radio e checkbox 
        if($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox'){
        	if((nome != this.name) && $("input[name='"+this.name+"']:checked").length == 0){
        		msg += '\n' + count + ') ' + this.name;
        		msg = msg.toUpperCase();
        		nome = this.name;
                error++; count++;
        	}
        }
	});
	
	msg = msg.replace('FIELDS[', '');
	msg = msg.replace(']', '');
	
	if (error > 0){
		alert(msg); return false;
	}else{
		if($('#flag').val() != 1)
			$('#formCadastro').submit();
		else
			enviaEmail();
	}
}

/************************************** TIPOS DE VALIDACOES ESPECIFICAS *********************************************/

/**
 * Valida CPF
 * Joao Henrique - http://www.jotaquery.com.br
 */
function validaCPF(cpf)
{ 
	var i;
	var cpf   = cpf.replace('.','');
	var cpf   = cpf.replace('.','');
	var value = cpf.replace('-','');
	var c 	  = value.substr(0, 9);
	var dv 	  = value.substr(9, 2);
	var d1 	  = 0;
	for (i = 0; i < 9; i++){ d1 += c.charAt(i) * (10 - i);}
	if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1) return false; 
	d1 *= 2;
	for (i = 0; i < 9; i++){ d1 += c.charAt(i) * (11 - i);}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) return false;
	
	//Karla
	var digitosIguais = 1;
	var soma,resultado,digitos,numeros;
	
	if(cpf.length < 11)
		return false;
	
	for(i=0; i< cpf.length-1; i++){
		if(cpf.charAt(i) != cpf.charAt(i+1)){
			digitosIguais = 0;
			break;
		}
		if(!digitosIguais){
			numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
		}else{
			return false;
		}
	}
	
	return true;
}

/**
 * Valida CNPJ
 * Autor: Shiguenori Suguiura Junior - http://blog.shiguenori.com
 */
function validaCNPJ(cnpj)
{
	cnpj = jQuery.trim(cnpj);
	cnpj = cnpj.replace('/','');
	cnpj = cnpj.replace('.','');
	cnpj = cnpj.replace('.','');
	cnpj = cnpj.replace('-','');
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	if (cnpj.length < 14 && cnpj.length < 15) return false;
	for (i = 0; i < cnpj.length - 1; i++){ if (cnpj.charAt(i) != cnpj.charAt(i + 1)){ digitos_iguais = 0; break; } }
	if (!digitos_iguais){
		tamanho = cnpj.length - 2;
		numeros = cnpj.substring(0,tamanho);
		digitos = cnpj.substring(tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){ soma += numeros.charAt(tamanho - i) * pos--; if (pos < 2) pos = 9; }
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(0)) return false;
		tamanho = tamanho + 1;
		numeros = cnpj.substring(0,tamanho);
		soma = 0;
		pos = tamanho - 7;
		for (i = tamanho; i >= 1; i--){ soma += numeros.charAt(tamanho - i) * pos--; if (pos < 2) pos = 9; }
		resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
		if (resultado != digitos.charAt(1)) return false;
		return true;
   }else{
      return false;
   }
}

/**
 * Valida Data
 * Joao Henrique - http://www.jotaquery.com.br
 */
function validaDATA(data)
{
	if (data.length == 10) { er = /(0[0-9]|[12][0-9]|3[01])[-.\/](0[0-9]|1[012])[-.\/][0-9]{4}/;
		if (er.exec(data)) { return true; } else { return false; }
	} else {
		return false;
	}
}

/**
 * Valida Email
 * Joao Henrique - http://www.jotaquery.com.br
 */
function validaEMAIL(email)
{
    
	er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
	if (er.exec(email)) {return true;} else { return false;}
}

function validaCONFIRMAEMAIL(email)
{
    if($('#verificacao_do_email').val() == $('#email').val())
	{
		return true;
	}
	else
	{
		return false;
	}
}

function validaCONFIRMASENHA(senha)
{
    if($('#senha').val() == $('#conf_senha').val())
	{
		return true;
	}
	else
	{
		return false;
	}
}

/**
 * Valida Sobrenome
 */
function validaSOBRENOME(nome)
{
    er = /\D{2,} \D{2,}/i;
	if (er.exec(nome)) {return true;} else { return false;}
}

function limpaCampo(){
	document.formLogAva1.email.value = '';
	document.formLogAva1.senha.value = '';
	document.formLogAva2.email.value = '';
	document.formLogAva2.senha.value = '';
}
function validaNADA(data)
{
	return true;
}

