/* Variáveis =============================================================== */



emailValido = false;



/* Funções =============================================================== */



function valida_cpf(parametro, obrigatorio)

{

	/*if (parametro == null)

	{

		parametro = "";

	}

	else

	{

		parametro = parametro.toString();

	}

	if (obrigatorio == null)

	{

		obrigatorio = true;

	}

	if ((obrigatorio == false) && (parametro.length == 0))

	{

		return(true);

	}

	parametro = parametro.replace(/\.-/g, "");

	if (parametro.length != 11)

	{

		return(false);

	}

	var soma, digito;

	if ((parametro == "00000000000") || (parametro == "11111111111") || (parametro == "22222222222") || (parametro == "33333333333") || (parametro == "44444444444") || (parametro == "55555555555") || (parametro == "66666666666") || (parametro == "77777777777") || (parametro == "88888888888") || (parametro == "99999999999"))

	{

		return(false);

	}

	soma = 0;

	for (var i = 0; i < 9; i++)

	{

		soma += parseInt(parametro.charAt(i), 10) * (10 - i);

	}

	digito = soma - (Math.floor(soma / 11) * 11);

	if ((digito == 0) || (digito == 1))

	{

	digito = 0;

	}

	else

	{

		digito = 11 - digito;

	}

	if (digito != parseInt(parametro.charAt(9), 10))

	{

		return(false);

	}

	soma = digito * 2;

	for (var i = 0; i < 9; i++)

	{

		soma += parseInt(parametro.charAt(i), 10) * (11 - i);

	}

	digito = soma - (Math.floor(soma / 11) * 11);

	if ((digito == 0) || (digito == 1))

	{

		digito = 0;

	}

	else

	{

		digito = 11 - digito;

	}

	if (digito != parseInt(parametro.charAt(10), 10))

	{

		return(false);

	}*/

	return(true);

}



$.fn.verificaCampo = function(lb) {

	var vlr = this.val();

	if(vlr=='') { // || vlr==this.attr('defaultValue')

		nomeCampo = $(lb).text().slice(0,-2);

		msgErro += nomeCampo+'<br />';

		haErro = true;

	}

}



// Função que verifica se o e-mail é valido



checkMail = function(mail){

    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);

    if(typeof(mail) == "string") {

        if(er.test(mail)){ return true; }

    }else if(typeof(mail) == "object") {

        if(er.test(mail.value)){

			return true;

		}

    }else {

		return false;

	}

}



// Valida data de nascimento com base em variavel pre existente: dtLmt

validaNasc = function(nascimento) {

	ar_lmt = dtLmt.split('/');

	dia_lmt = Number(ar_lmt[0]);

	mes_lmt = Number(ar_lmt[1]);

	ano_lmt = Number(ar_lmt[2]);

	

	ar_nasc = nascimento.split('/');

	dia_nasc = Number(ar_nasc[0]);

	mes_nasc = Number(ar_nasc[1]);

	ano_nasc = Number(ar_nasc[2]);

	

	nasc_valido = true;



	if(ano_nasc > ano_lmt) {

		nasc_valido = false;

	}else if(ano_nasc == ano_lmt) {

		if(mes_nasc > mes_lmt) {

		nasc_valido = false;

		}else if(mes_nasc == mes_lmt) {

			if(dia_nasc > dia_lmt) nasc_valido = false;

		}

	}

	

	return nasc_valido;

}



/* Eventos =============================================================== */







$(document).ready(function() {

	// Aplica máscaras

	$('input[rel*=data]').mask('99/99/9999');

	$('input[rel*=cep]').mask('99999-999');

	$('input[rel*=cpf]').mask('999.999.999-99');

	// $('input[rel*=rg]').mask('999.999.999-9');

	$('input[rel*=telefone]').mask('(99) 9999-9999');

	

	// Carrega cidades

	$('#cp_uf').change(function() {

		$('#cp_cidade').html('<option>Carregando cidades...</option>');

		$.get("php/ac_municipios.php", { uf: this.value },

			function(data){

				cidades_uf = data.split(';');

								

				codHtml = '<option value="" selected="selected">Selecione a cidade</option>';



				for(i=0;i<(cidades_uf.length-1);i++) {

					vlrs = cidades_uf[i].split(':');

					codHtml += '<option value="'+vlrs[0]+'">'+vlrs[1]+'</option>';

				}

				$('#cp_cidade').html(codHtml);

			}

		);

	});

	

	// Verifica e-mail

	$("#cp_email").blur(function() {

		$.get("php/ac_email.php", { email: $('#cp_email').val() },

			function(data){

				if(!checkMail($("#cp_email").val())) {

					msgEmail = '&nbsp;&nbsp;<strong>X</strong> Formato do e-mail inválido!';

					$('#verifica_email').attr('class', 'email_invalido');

				}else if(data=='valido') { 

					msgEmail = '&nbsp;&nbsp;<strong>V</strong> Email válido!';

					$('#verifica_email').attr('class', 'email_valido');

				}else if(data=='invalido') {

					msgEmail = '&nbsp;&nbsp;<strong>X</strong> Email já cadastrado!';

					$('#verifica_email').attr('class', 'email_invalido');

				}

				$('#verifica_email').html(msgEmail);

			}

		);

	});

	

	

	

	

	$('#formCadastro').submit(function() {

		msgErro = '<p>Por favor, preencha o(s) campo(s) abaixo:<br />';

		haErro = false;

		

		cpfNum = $('#cp_cpf').val().replace('.','');

		cpfNum = cpfNum.replace('.','');

		cpfNum = cpfNum.replace('-','');

		

		$("input").each(function() {

			cpAv = $(this);

			lbAv = null;

			$('label').each(function() {

				if(($(this).attr('for')==cpAv.attr('id')) && ($(this).text().slice(-2,-1)=='*')) {

					cpAv.verificaCampo(this);

				}

			});

		});

		$("select").each(function() {

			cpAv = $(this);

			lbAv = null;

			$('label').each(function() {

				if(($(this).attr('for')==cpAv.attr('id')) && ($(this).text().slice(-2,-1)=='*')) {

					cpAv.verificaCampo(this);

				}

			});

		});
		

		

		// Checa campos vazios

		if(haErro) {

			$('#divErro').css('display','block');

			$('#divErro').html(msgErro);

			window.scroll(0,250);

			return false;

		

		// Checa se o estado e cidade estão selecionados

		}else if($('#cp_uf').val()=='' || $('#cp_cidade').val()=='') {

			$('#divErro').css('display','block');

			$('#divErro').html('<p>Por favor, selecione um <strong>estado</strong> e uma <strong>cidade</strong>!</p>');

			window.scroll(0,250);

			return false;

		// Checa se o e-mail é valido

		}else if(!valida_cpf(cpfNum, true)) {

			$('#divErro').css('display','block');

			$('#divErro').html('<p>Por favor, insira um CPF válido!</p>');

			window.scroll(0,250);

			return false;

		}else if(!checkMail($("#cp_email").val())) {

			$('#divErro').css('display','block');

			$('#divErro').html('<p>Por favor, insira um e-mail válido!</p>');

			window.scroll(0,250);

			return false;

		

		// Verifica a idade minima

		}else if(!validaNasc($("#cp_nascimento").val())) {

			$('#divErro').css('display','block');

			$('#divErro').html('<p>Desculpe, a idade mínima para se tornar um usuário do aboa é de <strong>12 anos</strong>.</p>');

			window.scroll(0,250);

			return false;

		

		// Verifica se a senha possui 5 caracteres

		}else if ($('#cp_senha').val().length < 5) {

			$('#divErro').html('<p>A senha deve ter no mínimo 5 caracteres.</p>');

			$('#divErro').css('display','block');

			window.scroll(0,250);

			return false;

		

		// Verifica se Senha e Conf Senha são iguais

		}else if($('#cp_senha').val() != $('#cp_senha2').val()) {

			$('#divErro').html('<p>A senha digitada no campo "Senha" não é igual à do campo "Conf. Senha".</p>');

			$('#divErro').css('display','block');

			window.scroll(0,250);

			return false;

		}else {

			return true;

		}

	});

});
