﻿
$(document).ready(function() {
	$("div.completo").hide();
	$("div.ficha").hide();
	$("div.altera").hide();
	$("a.mostrarficha").click(function(e) {
		e.preventDefault();
		$("div.ficha").show();
		$("a.mostrarficha").hide();
	});
	$("a.mostraraltera").click(function(e) {
		e.preventDefault();
		$("div.altera").show();
		$("a.mostraraltera").hide();
	});
			
	$("a.simples").click(function(e) {
		e.preventDefault();
		var str = $(this).parents('div').attr('id');
		var id = str.substring(1,str.length);
		$("#s"+id).hide();
		$("#c"+id).show();
	}); 
	$("a.completo").click(function(e) {
		e.preventDefault();	
		var str = $(this).parents('div').attr('id');
		var id = str.substring(1,str.length);
		$("#s"+id).show();
		$("#c"+id).hide();
	}); 	


	$("div.contaba").hide();
	$("div.contaba:first").show();
	$("#abas a:first").addClass("selected");
	$("#abas a").click(function(e){
		e.preventDefault();
		$("div.contaba").hide();
		$("#abas a").removeClass("selected");
		$(this).addClass("selected");
		$($(this).attr("href")).show();
		
		if ($(this).attr("href") == "#tab1")
		{			
			var url = "admin/cadrevista/mostraPessoasExpediente/"; 
			var caixa = "div.#exp";	
			var dados = "&exp_id="+$('div[name=idExpediente]').attr('id') ;
		} 	
		else
		{
			var url = "admin/cadrevista/mostraDocumentos/";
			var caixa = "div.#doc";
			var dados = "&rev_id="+$('div[name=idRevista]').attr('id') ;
		}
		$.ajax({
			url: base_url+url,
			type: "POST",
			dataType: "html",
			data:dados,
			success: function(html) {
				$(caixa).html(html).show();
			}
		});
		return false;
	});


	//** Janela Modal
	//seleciona os elementos a com atributo name="modal"
	$("a[name=modal]").live('click',function(e) {
		//armazena o atributo href do link
		var url = $(this).attr('href');
		var caixa = $(this).attr('id');
		//cancela o comportamento padrão do link
		e.preventDefault();
		$.ajax({
			  url:url,
			  type: "POST",
			  dataType: "html",
		 	  success: function(html) {
				  $('#'+caixa).html(html).show();
		 	  }
		});

	});

    //*** Cadastro Pessoa Expediente  ***//
	$("[name=SubmitPessoa]").live("click",function(e) {
		e.preventDefault();
		$.ajax({
			  url:$("#formcadastroPessoa").attr("action"),
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroPessoa').serialize()+'&exp_id='+$("div[name=idExpediente]").attr('id')+'&SubmitPessoa=true',
		 	  success: function(html) 
			  {
				$('#exp').html(html).show();
		 	  }
		});
	});

	$("[name=DeletePessoa]").live("click",function(e) {
		e.preventDefault();	
		if ($("a.[name=DeletePessoa]").attr("href") )
		{
			url = $(this).attr("href"); 			
		}
		else
		{
			url = $("#formcadastroPessoa").attr("action"); 
		}
		$.ajax({
			  url:url,
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroPessoa').serialize()+'&exp_id='+$("div[name=idExpediente]").attr('id')+'&DeletePessoa=true',
		 	  success: function(html) {
				$('#exp').html(html).show();
		 	  }
		});
	});
    //*** Cadastro Pessoa Expediente  ***//


    //*** Cadastro Documento Revista  ***//
	$("[name=SubmitDocumento]").live("click",function(e) {
		e.preventDefault();
		$.ajax({
			  url:$("#formcadastroDocumento").attr("action"),
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroDocumento').serialize()+'&rev_id='+$("div[name=idRevista]").attr('id')+'&SubmitDocumento=true',
		 	  success: function(html) {
				$('#doc').html(html).show();
		 	  }
		});
	});

	$("[name=DeleteDocumento]").live("click",function(e) {
		e.preventDefault();	
		if ($("a.[name=DeleteDocumento]").attr("href") )
		{
			url = $(this).attr("href"); 			
		}
		else
		{
			url = $("#formcadastroDocumento").attr("action"); 
		}
		$.ajax({
			  url:url,
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroDocumento').serialize()+'&rev_id='+$("div[name=idRevista]").attr('id')+'&DeleteDocumento=true',
		 	  success: function(html) {
				$('#doc').html(html).show();
		 	  }
		});
	});


	$("[name=SubmitEnviaImg]").live("click",function(e) {
		e.preventDefault();			
		$.ajaxFileUpload({
			  url:$("#formcadastroImg").attr("action"),
			  type: "POST",
			  dataType: "json",
			  fileElementId:'userfileimg',
		 	  success: function(html) {
				$('#enviaimg').html(html).show();
		 	  },
			  error: function (data, status, e)
			  {
				alert(e);
			  }
		});
	});

	$("[name=SubmitAutor]").live("click",function(e) {
		e.preventDefault();
		$.ajax({
			  url:$("#formcadastroAutor").attr("action"),
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroAutor').serialize()+'&ace_id='+$("div[name=idAcervo]").attr('id')+'&SubmitAutor=true',
		 	  success: function(html) {
				$('#aut').html(html).show();
		 	  }
		});
	});

	$("[name=DeleteAutor]").live("click",function(e) {
		e.preventDefault();	
		if ($("a.[name=DeleteAutor]").attr("href") )
		{
			url = $(this).attr("href"); 			
		}
		else
		{
			url = $("#formcadastroAutor").attr("action"); 
		}
		$.ajax({
			  url:url,
			  type: "POST",
			  dataType: "html",
			  data: $('#formcadastroAutor').serialize()+'&ace_id='+$("div[name=idAcervo]").attr('id')+'&DeleteAutor=true',
		 	  success: function(html) {
				$('#aut').html(html).show();
		 	  }
		});
	});
    //*** Cadastro Documento Revista  ***//

	$("a#autores").live("click",function(e) {
		e.preventDefault();	
		$.ajax({
			  url: $(this).attr("href"),
			  type: "POST",
			  dataType: "html",
			  data: '&ace_id='+$("div[name=idAcervo]").attr('id'),
		 	  success: function(html) {
				$('#aut').html(html).show();
		 	  }
		});
		return false;
	});


	//**  Cadastro de Monografia **//
	$("div.contabaMono").hide();
	$("div.contabaMono:first").show();
	$("#abasMono a:first").addClass("selected");
	$("#abasMono a").click(function(e){
		e.preventDefault();
		$("div.contabaMono").hide();
		$("#abasMono a").removeClass("selected");
		$(this).addClass("selected");
		$($(this).attr("href")).show();
		
		if ($(this).attr("href") == "#tab1")
		{			
			var url = "admin/cadmonografia/mostraAutores/"+$('div[name=idAcervo]').attr('id'); 
			var caixa = "div.#aut";	
			var dados = "&ace_id="+$('div[name=idAcervo]').attr('id') ;
		} 	
		else
		{
			var url = "admin/cadmonografia/mostraOrientadores/";
			var caixa = "div.#ori";
			var dados = "&mon_id="+$('div[name=idMonografia]').attr('id') ;
		}
		$.ajax({
			url: base_url+url,
			type: "POST",
			dataType: "html",
			data:dados,
			success: function(html) {			
				$(caixa).html(html).show();
			}
		});
		return false;
	});

   $('input[name="pes_cpf"]').setMask('cpf');
   $('input[name="pes_cpfalt"]').setMask('cpf');
   $('input[name="pes_datanascimento"]').setMask('date');
   $('input[name="pes_dataalt"]').setMask('date');
   $('input[name="pes_ceplog"]').setMask('cep');
   $('input[name="pes_telefone"]').setMask('phone');
   
   
    // valida o formulário de inscrição
    $('#formcadastro').validate
    ({
        // define regras para os campos
        rules: {
            pes_nome: {
                required: true,
                minlength: 2
            },
            pes_email: {
                required: true,
                email: true
            },
            pes_datanascimento: {
				required: true,
				date: true
			},
			pes_cpf: {
				required: true,
				cpf: true
			}
        },
        // define messages para cada campo
        messages: {
            pes_nome: {
				required: "Preencha o seu nome",
				minlength: "Seu nome tem que ter mais de 2 letras!"
			},
			pes_email: {
				required: "Digite seu e-mail!",
				email: "E-mail inválido!"
			},
			pes_datanascimento: {
				required: "Digite sua data de nascimento!",
				date: "Data inválida!"
			},
			pes_cpf: { 
				required: "Digite seu CPF!",
				cpf: 'CPF inválido!'
			}
        }
    });
    
     // valida o formulário de alteração
    $('#formbusca').validate
    ({
        // define regras para os campos
        rules: {
            pes_dataalt: {
				required: true,
				date: true
			},
			pes_cpfalt: {
				required: true,
				cpf: true
			},
        },
        // define messages para cada campo
        messages: {
            pes_dataalt: {
				required: "Digite sua data de nascimento!",
				date: "Data inválida!"
			},
			pes_cpfalt: { 
				required: "Digite seu CPF!",
				cpf: 'CPF inválido!'
			}
        }
    });
});


//**** Função para campo lookup  ********//
function lookup(inputString,consulta,caixa)
{
   	if(inputString.length == 0)
	{
   	    //$('#suggestions').hide();
		$('#'+caixa).hide();
   	}
	else
	{
   	    $.post
		(
			base_url+consulta, 
			{valor: ""+inputString+""}, 
			function(data)
			{
				if(data.length >0)
				{
					$('#'+caixa).show();
					$('#'+caixa).html(data);
       			 }
    		}
		);
   	}
};

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function validarCPF(){
	/*if ($('input[name="pes_cpf"]').attr('value').length == 0)
	{
		cpf_normal = $('input[name="pes_cpfalt"]').attr('value');
	}
	else
	{
		cpf_normal = $('input[name="pes_cpf"]').attr('value');
	}

	var cpf = soNumeros(cpf_normal);   
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
 	   cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	   cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	   cpf == "88888888888" || cpf == "99999999999")
	{
	   window.alert("CPF: "+cpf_normal+" inválido. Tente novamente.");
	   return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9)))
	{
	 window.alert("CPF: "+cpf_normal+" inválido. Tente novamente.");
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF: "+cpf_normal+" inválido. Tente novamente.");
	 return false;
   }
   return true;*/
 }


function fill(caixa) 
{
	setTimeout("$('#"+caixa+"').hide();", 200);
};

function fillValue(caixaId, caixaValor, id,valor) 
{
	$("[name="+caixaId+"]").val(id);
   	$("[name="+caixaValor+"]").val(valor);
};
//**** Função para campo lookup  ********//


function enviaarquivo(caminho) 
{ 
	window.open(caminho, "", "toolbar=no,height=300,width=650"); 
	return false; 
}

/*jQuery.validator.addMethod("verificaCPF", function(value, element) 
{
	value = value.replace('.','');
	value = value.replace('.','');
	cpf = value.replace('-','');
	while(cpf.length < 11) cpf = "0"+ cpf;
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) return false;
	return true;
}, "Informe um CPF válido."); // Mensagem padrão */
