﻿	/*
	VALIDAÇÕES.JS
	TODAS AS VALIDAÇÕES SÃO FEITAS UTILIZANDO A BIBLIOTECA LIVEVALIDATION
	
	COMO USAR:
	- A função inicializaValidacoesForm deve ser chamada após o carregamento da página, recebendo o id do formulário como parâmetro
	- Adicionar a classe OBRIGATORIO ao campo que precisa ter validação de PRESENÇA
		Se o MESMO campo OBRIGATÓRIO precisar de outras validações, adicionar outras classes, exemplo:
		* email: valida formato de e-mail
		* confirmacao_senha: valida se o valor é equilavente ao valor do campo cujo id é senha
		* numero: valida se o valor é numérico
		* imagem: valida o formato do arquivo adicionado
		* textfile: valida o formato do arquivo adicionado
	- Para campos NÃO OBRIGATÓRIOS, adicionar somente as classes ESPECÍFICAS para outras validações, como detalhado acima (email, numero, etc)
	*/

	var live_validation_options = { validMessage: " ", onlyOnSubmit: true }
	var obrigatorio_LV, email_LV, confirmacao_senha_LV, numero_LV, imagem_LV, cpf_LV, cnpj_LV;
	
	function inicializaValidacoesForm( id_form ){

		if( id_form != "" )
			id_form = "#"+id_form
		
		$( id_form+" .obrigatorio" ).each(function(){
		
			obrigatorio_LV = new LiveValidation(this, live_validation_options);
			obrigatorio_LV.add(Validate.Presence, {failureMessage: "Preencha o campo "+this.title+"."});
			
			if ( $(this).hasClass("email") ){
				obrigatorio_LV.add(Validate.Email, {failureMessage: "E-mail inválido."});
				
				if ( $(this).hasClass("unico") )
					obrigatorio_LV.add(
						Validate.Custom, 
						{against: function(value, args){return validaUnicidade(value, args.campo)}, args: {campo: "email"}, failureMessage: this.title+" já cadastrado."}
					);
			}

			if ( $(this).hasClass("confirmacao_senha") )
				obrigatorio_LV.add(Validate.Confirmation, {match: 'senha', failureMessage: "As senhas não são iguais."});
				
			if ( $(this).hasClass("numero") )
				obrigatorio_LV.add(Validate.Numericality, {notANumberMessage: this.title+" inválido."});
				
			if ( $(this).hasClass("imagem") )
				obrigatorio_LV.add(Validate.Format, {pattern: /\.(jpeg|jpg|gif|swf)$/i, failureMessage: "Arquivo inválido."});

			if ( $(this).hasClass("textfile") )
				obrigatorio_LV.add(Validate.Format, {pattern: /\.(doc|docx|rtf|pdf|txt)$/i, failureMessage: "Arquivo inválido."});

			if ( $(this).hasClass("cpf") )
				obrigatorio_LV.add(Validate.Custom, {against: function(value){return validaCPF(value)}, failureMessage: "CPF inválido."});
				
			if ( $(this).hasClass("cnpj") )
				obrigatorio_LV.add(Validate.Custom, {against: function(value){return validaCNPJ(value)}, failureMessage: "CNPJ inválido."});
				
		});
		
		$( id_form+" .email:not(.obrigatorio)" ).each(function(){
			email_LV = new LiveValidation(this, live_validation_options);
			email_LV.add(Validate.email_LV, {failureMessage: "E-mail inválido."})
		});
		
		$( id_form+" .confirmacao_senha:not(.obrigatorio)" ).each(function(){
			confirmacao_senha_LV = new LiveValidation(this, live_validation_options);
			confirmacao_senha_LV.add(Validate.Confirmation, {match: 'senha', failureMessage: "As senhas não são iguais."})
		});
		
		$( id_form+" .numero:not(.obrigatorio)" ).each(function(){
			numero_LV = new LiveValidation(this, live_validation_options);
			numero_LV.add(Validate.Numericality, {notANumberMessage: this.title+" inválido."})
		});
		
		$( id_form+" .imagem:not(.obrigatorio)" ).each(function(){
			imagem_LV = new LiveValidation(this, live_validation_options);
			imagem_LV.add(Validate.Format, {pattern: /^.*.(png|jpg|bmp|gif|jpeg|swf)$/i, failureMessage: "Arquivo inválido."})
		});
		
		$( id_form+" .cpf:not(.obrigatorio)" ).each(function(){
			cpf_LV = new LiveValidation(this, live_validation_options);
			cpf_LV.add(Validate.Custom, {against: function(value){return validaCPF(value)}, failureMessage: "CPF inválido."})
		});
		
		$( id_form+" .cnpj:not(.obrigatorio)" ).each(function(){
			cnpj_LV = new LiveValidation(this, live_validation_options);
			cnpj_LV.add(Validate.Custom, {against: function(value){return validaCNPJ(value)}, failureMessage: "CNPJ inválido."})
		});
		
	}

	function validaUnicidade( valor, campo ){
		var retorno = $.ajax({
			url: "valida_unicidade.asp?valor="+valor+"&campo="+campo,
			dataType: "text",
			type: "get",
			async:	false			
		}).responseText;
		
		if ( retorno=="false" )
			return false;
		
		return true;
	}
	
	function validaCPF( cpf ) {		
		/*	substitui (por expressão regular) os . e - por string vazia, pra retornar somente números
			\D = find a non-digit character
			g  = perform a global match (find all matches rather than stopping after the first match)
		*/
		cpf = cpf.replace(/\D/g,"")
		
		// precisa ter 11 dígitos
		if ( cpf.length < 11 ) return false;
			
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
			return false;		

		// validação dos números do cpf
		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])){ return false; }
		
		return true;
	}

	function validaCNPJ( cnpj ) {
		/*	substitui (por expressão regular) os . e - e / por string vazia, pra retornar somente números
			\D = find a non-digit character
			g  = perform a global match (find all matches rather than stopping after the first match)
		*/
		cnpj = cnpj.replace(/\D/g,"")
		
		// precisa ter 14 dígitos
		if ( cnpj.length < 14 ) return false;
		
		// validação dos números do cnpj
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		
		for (i=0; i<12; i++) {
			a[i] = cnpj.charAt(i);
			b += a[i] * c[i+1];
		}
		
		if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		
		b = 0;
		
		for (y=0; y<13; y++) { b += (a[y] * c[y]); }
		
		if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		
		if ((cnpj.charAt(12) != a[12]) || (cnpj.charAt(13) != a[13])){
			return false;
		}
		
		return true;
	}
	
	function insNumeric(obj,event)
	{
		var tecla = event.charCode;
		var ie = event.keyCode;
		if (!event) event = window.event;
		var code;
		if (event.keyCode) code = event.keyCode;
		else if (event.which) code = event.which; // Netscape 4.?
	//se nao for número nem parentesis ou espaço
		if ((code < 48 || code > 59) && (code != 8 ) ){
		  event.returnValue = false;
		  if (event.which){
			event.preventDefault();
		  }
		  return false;
		}else{
		  event.returnValue = true;
		  return true;
		}
	 }
	 
	 function formatar(id, mask)
	{
		src = document.getElementById(id);
		var i = src.value.length;
		var saida = mask.substring(0,1);
		var texto = mask.substring(i)
		if (texto.substring(0,1) != saida)
		{
			src.value += texto.substring(0,1);
		}
	}
	
	function janelaExterna(url)
	{
		var largura = window.width 
		var altura =  window.height
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var wleft = parseInt( ( parseInt(xScroll)-1100 ) /2 )
		largura = parseInt(xScroll)-1000
		altura = yScroll
	
		var winDt = window.open(url,'','left='+ wleft +',width=1050,height='+ altura +',scrollbars=1,status=1,toolbar=1,location=1,menubar=1,directories=1,resizable=1');
		winDt.focus();
	}
	
    $(document).ready(function(){
		//Abrir links em novas janelas
		$(".novaJanela").click(function(){
			wurl = $(this).attr("href")
			janelaExterna(wurl)
			return false
		})
	});

