	/*
	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
	- 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: "Valor inválido!"});
				
			if ( $(this).hasClass("imagem") )
				obrigatorio_LV.add(Validate.Format, {pattern: "/\.(jpeg|jpg|gif)$/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: "Valor 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)$/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!"})
		});
		
		/*
		if (validaDatas() == false)	{
			return false
		}		
		if (validaValorFloat() == false) {
			return false
		}*/
	}

	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;
	}
