$(document).ready(function(){
	$("#data_nascimento").mask("99/99/9999");
	$("#cep").mask("99999-999");
	$("#telefone").mask("(99) 9999-9999");
	$("#celular").mask("(99) 9999-9999");
	$("#cpf").mask("999.999.999-99");
	
	/*
	$("#cpf").blur(function(){
		if($("#cpf").val()!=""){
			$("#floatCarregando").ajaxStart(function(){
				$(this).slideDown("slow");
			});
		
			$.post("ajax/verifica_cpf_evento.php", {
				evento : $("#id_evento").val(),
				num_cpf : $("#cpf").val()
			}, function(dados){
				if(dados=="tem"){
					alert("Este CPF já está cadastrado neste evento!");
					$("#cpf").focus();
				}
				
				$("#floatCarregando").ajaxStop(function(){
					$(this).slideUp("slow");
				});
			});
			
			return false;
		}
	});
	*/
	
	$("#testform").submit(function(){
		var err=0; 	// Para validação dos erros 
		var msg="";	// Para concatenar as mensagens
		var tot=0;	// Para verificar a quantidade de itens quem tem a classe "tam" (relacionada ao tamanho do brinde)
	
		$(".obrigatorio").each(function(){

			if($(this).attr("type")!="radio"){ // Varre todos os itens que não são radio button e faz as devidas verificações
				if($(this).val()==""){
					err = 1;
					msg = msg + $(this).attr("msg");
				}else{
					// Faz verificações para campos preenchidos como E-mail e CPF
					if($(this).attr("id")=="email"){
						if(valida_email($(this).val())==false){
							err = 1;
							msg = msg + "Campo <b>E-MAIL</b> no formato inválido!<br>";
						}
					}
					
					if($(this).attr("id")=="cpf"){
						if(valida_cpf($(this).val())==false){
							err = 1;
							msg = msg + "O <b>CPF</b> informado é inválido!<br>";
						}
					}
				}
			}else{
				var tam = 0;
				$(".tam:checked").each(function(){ // Varre todos os itens que são radio button e que tenham a classe "tam"
					tam=1;
				});

				if(tam==0){
					tot = tot + 1;
			
					if(tot==1){ // Para pegar somente a mensagem do primeiro item caso todos estejam desmarcados
						err = 1;
						msg = msg + $(".tam").attr("msg");
					}
				}
			}
		});

		if(err==1){
			$("#fundo_erro, #erro").fadeIn("slow");
			$(".msg").html(msg);
		}else{
			return true;
		}

		return false;
	});
	
	$("#absoluto").click(function(){
		var tot = $("#absoluto:checked").length;	
			
		var valor = parseFloat($("#valor").val())
		var absoluto_valor = parseFloat($("#absoluto_valor").val());
			
		if(tot==1){
			var total = (valor + absoluto_valor);
		
			$("#valor").val(number_format(total,2,".",""));
			$("#txt_valor").html("R$ "+number_format(total,2,",","."));
		}else{
			var total = (valor - absoluto_valor);
			
			$("#valor").val(number_format(total,2,".",""));
			$("#txt_valor").html("R$ "+number_format(total,2,",","."));
		}
	});

});



function valida_email(email){
	expreg=/([a-z0-9_\.\-])+\@(([a-z0-9])+\.)+((gov|com|org|net|biz|info)|([a-z]{2}))$/;
	
	if(expreg.exec(email)){
		return true;
	}else{
		return false;
	}
		
}     

function number_format(number, decimals, dec_point, thousands_sep){
	var n = !isFinite(+number) ? 0 : +number, 
	prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
	sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
	s = '',
	toFixedFix = function (n, prec) {
	var k = Math.pow(10, prec);
	return '' + Math.round(n * k) / k;        };
	
	// Fix for IE parseFloat(0.55).toFixed(0) = 0;
	s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
	
	if (s[0].length > 3) {
		s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    
	}
	if ((s[1] || '').length < prec) {
		s[1] = s[1] || '';
		s[1] += new Array(prec - s[1].length + 1).join('0');
	}    
	
	return s.join(dec);
}

function valida_cpf(cpf){
	var numeros, digitos, soma, i, resultado, digitos_iguais;
	digitos_iguais = 1;

	while (cpf.indexOf(".")!=-1 || cpf.indexOf("/")!=-1 || cpf.indexOf("-")!=-1){
        	cpf=cpf.replace("-","");
	       	cpf=cpf.replace("/","");
           	cpf=cpf.replace(".","");
	}

	if (cpf.length < 11){
		return false;
    	}
    	
    	for (i=0; i<cpf.length - 1; i++) {
		if (cpf.charAt(i) != cpf.charAt(i + 1)){
			digitos_iguais = 0;
			break;
		}
	}
	
	if (!digitos_iguais){
		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;
      }
}

