		
/* ===================================================================
 Autor: Patrick J. Levy 
 Data: 18/10/2010
 Versão: 2.4

 funcões para validação automatica de formulário - Jquery
 Dependencias: jquery-1.4.2

 Ativar: <form validaForm="true">
 Exigir dados: <input type="text" valida="Especifique o valor para o xxxx">
 Aplicar mascara/formato: <input type="text" mascara="cep|data|hora|hora2|cpf|cnpj|email">
 Valor maximo no memo: <textarea maxlenght="100">
 Contagem de caracteres no memo : <textarea name="xxx"></textarea><span id="xxx_len"></span>
 Valida radio/check (só na primeira): <input type="radio" valida="Especifique uma opção">
 A funçao de validação também pode ser chamada pelo js: validaForm(form);
/ =================================================================== */

$(function(){
	//preparação :
	
			   
	$('textarea').each(function(){	   
		nome = $(this).attr('name');
		maxlen = $(this).attr('maxlength');
		curlen = $(this).val().length;
		if (!!maxlen){
			$('#'+nome+'_len').html(curlen+'&nbsp;caracteres. (máx: '+maxlen+')');
		} else {
			$('#'+nome+'_len').html(curlen+'&nbsp;caracteres.');
		}		
	});
	
	//validações OnBlur:
	$('[formato=data]').blur(function () {checkDate(this);});
	$('[formato=hora]').blur(function () {checkTime(this);});
	$('[formato=hora2]').blur(function () {checkTime(this);});
	$('[formato=email]').blur(function () {checkBlur(this,'email');});
	$('[formato=cep]').blur(function () {checkBlur(this,'cep');});	
	$('[formato=cpf]').blur(function () {checkBlur(this,'cpf');});		
	$('[formato=cnpj]').blur(function () {checkBlur(this,'cnpj');});			
	$('textarea').blur(function () {checkMemo(this);});
	
	//dummy function:
	$('input[dummy], textarea[dummy]').blur(function(){
		dummyBlur(this);
	});
	$('input[dummy], textarea[dummy]').focus(function(){
		dummyFocus(this);
	});	
	
	$('textarea').bind('keypress', function(e){	
		nome = $(this).attr('name');
		maxlen = $(this).attr('maxlength');
		lenfld = $('#'+nome+'_len');

		var valor = $(this).val();
		var key	= (e.keyCode ? e.keyCode : e.charCode);
		var ch	= String.fromCharCode(key);
		var str	= valor + ch;
		var pos	= str.length;
		
		if (!!maxlen){
			if (pos <= maxlen){
				$('#'+nome+'_len').html(pos+'&nbsp;caracteres. (máx: '+maxlen+')');						 
			} else {
				alert('Texto muito longo. Máximo permitido: '+maxlen);
				return false;	
			}
		} else {
			$('#'+nome+'_len').html(pos+'&nbsp;caracteres.');
		}
	});

	//validações OnTheFly e aplicação de mascara:
	$('[formato]').bind('keypress', function(e){
		formato = $(this).attr('formato');
		//recupera dados da formatacao:		
		var formatRule  = rules[formato];
		var validaStr 	= formatRule.valida;
		var mascaraStr 	= formatRule.mascara;
		valor 	  = $(this).val();
		
		var key = (e.keyCode ? e.keyCode : e.charCode);
		var ch = String.fromCharCode(key);
		var str   = valor + ch;
		var pos   = str.length;
		
		//valida:
		if (validaStr != ''){
			if (validaStr.indexOf(ch.toLowerCase()) < 0 && key != 9) {
				return false;	
			}			
		}
		
		//aplica a mascara:		
		if (mascaraStr != ''){
			if (pos <= mascaraStr.length) {
				if (mascaraStr.charAt(pos - 1) != ' ' ) {
					str = valor + mascaraStr.charAt(pos - 1) + ch;
				}
				$(this).val(str);
				return false;	
			} else {
				return false;	
			}
		}
			
	});
		   
	//busca por formulários com atributo de validar form
	$('[validaForm=true]').submit(function(){
		//verifica se existe validação geral do form:
		validaForm($(this));
	});
	
	$('a.submit').click(function(){
		form = $(this).closest('form');
		if(validaForm($(form))){
			$(form).trigger('submit');
			return false;		
		}
	})
	
	$('a.ajx_submit').click(function(){
		ajx_submit($(this));	
	})	
	
	$('a.ajx_consume').click(function(){
		ajx_consume($(this));	
	})	
	
	if ($('div#lista')){
		$('a.ajx_consume').trigger('click');	
	}	
});

function lista(){
	$('a.ajx_consume').trigger('click');	
}

function ajx_submit(subButton){
	form = $(subButton).closest('form');
	if(validaForm($(form))){
		var btClass = subButton.attr('class');
		subButton.attr('class', 'botao xs_gry');
		$('label.loader').html('<img src="../img/anm_loader_sml.gif" />');	
		if (!advanced_debug) {
			dType = "json";
		} else {
			dType = "text";
		}

		var actionPostPage = $(form).attr('action');
		ajxPostPage = actionPostPage.replace(/.php/, '.ajx.php');
		
		var $editors = $("textarea.ckeditor"); 
		if ($editors.length) { 
			for (instance in CKEDITOR.instances) 
    	        CKEDITOR.instances[instance].updateElement(); 
		}
		
		$.ajax({
			type: "POST",
			url: ajxPostPage,
			data: $(form).serialize(),
			dataType:dType,
			success: function(rtrMsg){

				if (rtrMsg){
					
					if (debug && advanced_debug) {
						alert(rtrMsg);
						return false;
					}
				
					rtr = rtrMsg.res;
					msg = rtrMsg.msg;	
					cmd = rtrMsg.cmd;
					adc = rtrMsg.adc;
					msg = unescape(msg.replace(/\+/g," "));

					if (rtr == 'err'){
						if (cmd == 'alerta'){
							alerta(msg, 0);	
						} else {
							alert(msg);	
						}
					} else if (rtr == 'ok'){
						
						if (cmd != ''){
							cmd = cmd.split(',');
							for (i=0;i<cmd.length;i++){
								comando = cmd[i];
								if (comando == 'atualiza'){
									atualiza('frame_principal', 'frmRlt');
								} else if (comando == 'relista'){
									relista('frame_principal');									
								} else if (comando == 'alerta'){ 
									alerta(msg, 1);	
								} else if (comando == 'alert'){ 
									alert(msg);		
								} else if (comando == 'limpa'){ 
									$(form).clearForm();									
								} else if (comando == 'principal'){ 
									voltar('principal');
								} else if (comando == 'repost'){
									document.location.reload();
								} else if (comando == 'post'){
									//adc = alert(adc)					
									adc = "{"+adc+"}"
									var jSonStr = eval('(' + adc + ')');
									jsPost(actionPostPage, '', jSonStr);
								} else if (comando == 'reload'){
									var vLoc = document.location.href;
									document.location.href = vLoc.replace(/#/, '');
								} else if (comando == 'function'){
									eval(adc);									
								}
							}
						} else {
							alert(msg);
						}
					}
				}
				subButton.attr('class', btClass);
				$('label.loader').html('');
				return false;
			},
			error: function (xhr, ajaxOptions, thrownError){
				//$('span#loader').html('');
				if (debug){
					//alert(xhr.statusText); 
					alert(thrownError);
				} else {
					alert('Problemas no processamento.');					
				}
				subButton.attr('class', btClass);
				$('label.loader').html('');
			}
		});	
	}	
}

function ajx_consume(subButton){

	form = $(subButton).closest('form');
	if(validaForm($(form))){

		var actionPostPage = $(form).attr('action');
		var actionResultContainer = $(form).attr('result');
		actionPostPage = actionPostPage.replace(/.php/, '.ajx.php');
		
		$('#'+actionResultContainer).html('<div class="big_loader"></div>');
		$.ajax({
			type: "POST",
			url: actionPostPage,
			data: $(form).serialize(),
			dataType:'text',
			success: function(rtrMsg){

				if (debug && advanced_debug) {
					alert(rtrMsg);
					return false;
				}

				$('#'+actionResultContainer).html(rtrMsg);
				if ($("table.lista")){
					processaLista();	
				}

				return false;
			},
			error: function (xhr, ajaxOptions, thrownError){
				if (debug){
					//alert(xhr.statusText); 
					alert(thrownError);
				} else {
					alert('Problemas no processamento.');					
				}
				$('#'+actionResultContainer).html('');
		
			}
		});	
	}	
}

function validaForm(oForm){
	validaStr = oForm.attr('valida');
	if (!!validaStr){
		question = confirm(validaStr);
		if (question == 0){
			return false;	
		}
	}

	subForm = true;

	$('[valida]', oForm).each(function() {	
		var campo	= this;										   
		var type 	= this.type;
		var tag 	= this.tagName.toLowerCase();
		var valida  = $(this).attr('valida');
		var formato	= $(this).attr('formato');
		var dummy	= $(this).attr('dummy');
		//TEXT

		if (type == 'text' || type == 'password' || tag == 'textarea' || tag == 'hidden'){
			var valor = $(this).val();
			if (valor == dummy) valor = '';
			
			if (valor == ''){
				alert(valida);
				campo.focus();					
				subForm = false;
				return (false);
			}

			if (!!formato){
				var rule = rules[formato];
				reg = rule.formato;					

				//CEP
				if (formato == 'cep'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo CEP. Utilize xxxxx-xxx.');
						campo.focus();
						subForm = false;
						return (false);								
					}	
				}

				//EMAIL
				else if (formato == 'email'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo email.');
						campo.focus();
						subForm = false;
						return (false);								
					}		
				}

				//CPF
				else if (formato == 'cpf'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo CPF. Utilize xxx.xxx.xxx-xx.');
						campo.focus();
						subForm = false;
						return (false);								
					} else {
						vldAdc = validaCPF(valor);
						if (vldAdc != ''){
							alert(vldAdc);
							campo.focus();
							subForm = false;
							return (false);								
						}								
					}
				}
				
				//CNPJ
				else if (formato == 'cnpj'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo CNPJ. Utilize xx.xxx.xxx/xxxx-xx.');
						campo.focus();
						subForm = false;
						return (false);								
					} else {
						vldAdc = validaCNPJ(valor);
						if (vldAdc != ''){
							alert(vldAdc);
							campo.focus();
							subForm = false;
							return (false);								
						}								
					}
				}
				
				//DATA
				else if (formato == 'data'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo data.');
						campo.focus();
						subForm = false;
						return (false);								
					}		
				}
				
				//HORA
				else if (formato == 'hora' || formato == 'hora2'){
					if (!reg.test(valor)){
						alert('Formato inválido no campo hora.');
						campo.focus();
						subForm = false;
						return (false);								
					}		
				}
			}
		//RADIOBUTTON				
		} else if (type == 'radio'){
			theName = $(this).attr('name');
			if( $("input[name="+theName+"]:checked").length == 0 ){
				alert(valida);
				this.focus();
				subForm = false;
				return (false);					
			}
		//CHECKBOX 	
		} else if (type == 'checkbox'){
			theName = $(this).attr('name');
			if( $("input[name="+theName+"]:checked").length == 0 ){
				alert(valida);
				this.focus();
				subForm = false;
				return (false);					
			}
		//SELECT 
		} else if (tag == 'select'){
			
			if ($(this).val() == ''){
				alert(valida);
				this.focus();
				subForm = false;
				return (false);				
			};
		}
	});
	
	//Validação customizada:
	if(typeof validaFormCustom == 'function') { 
		subForm = validaFormCustom(oForm); 
	} 		
	
	//não validou, não envia.
	if (!subForm){
		return false;	
	} else {
		return true;	
	}
}


///////////////////////////////////////////
// validar CPF
///////////////////////////////////////////

function validaCPF(CPF){
	erro = new String;
	if (CPF.length < 14) erro = "É necessario preencher corretamente o número do CPF! (xxx.xxx.xxx-xx)"; 
	if ((CPF.charAt(3) != ".") || (CPF.charAt(7) != ".") || (CPF.charAt(11) != "-")){
		if (erro.length == 0) erro = "É necessário preencher corretamente o número do CPF! (xxx.xxx.xxx-xx)";
	}
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CPF.substring(0,2);
		x += CPF.substring (4,6);
		x += CPF.substring (8,10);
		x += CPF.substring (12,13);
		CPF = x; 
	} else {
		CPF = CPF.replace ('.','');
		CPF = CPF.replace ('.','');
		CPF = CPF.replace ('-','');
	}	
	if (CPF.length > 0){
		if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
			CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
			CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
			CPF == "88888888888" || CPF == "99999999999"){
			erro = "CPF Inválido!";
		}
	
		soma = 0;
		for (cpx=0; cpx < 9; cpx ++)
			soma += parseInt(CPF.charAt(cpx)) * (10 - cpx);
		resto = 11 - (soma % 11);
		if (resto == 10 || resto == 11)
			resto = 0;
		if (resto != parseInt(CPF.charAt(9))){
			erro = "CPF Inválido!";
		}
	
		soma = 0;
		for (cpx = 0; cpx < 10; cpx ++)
			soma += parseInt(CPF.charAt(cpx)) * (11 - cpx);
		resto = 11 - (soma % 11);
	
		if (resto == 10 || resto == 11)
			resto = 0;
	
		if (resto != parseInt(CPF.charAt(10))){
			erro = "CPF Inválido!";
		}
		if (erro.length > 0){
			return (erro);
		}
		return '';		
	}	
}

///////////////////////////////////////////
// validar CNPJ
///////////////////////////////////////////

function validaCNPJ(CNPJ) {
	erro = new String;
	if (CNPJ.length < 18) erro = "É necessario preencher corretamente o número do CNPJ! (xx.xxx.xxx/xxxx-xx)"; 
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
		if (erro.length == 0) erro = "É necessário preencher corretamente o número do CNPJ! (xx.xxx.xxx/xxxx-xx)";
	}
	if(document.layers && parseInt(navigator.appVersion) == 4){
		x = CNPJ.substring(0,2);
		x += CNPJ. substring (3,6);
		x += CNPJ. substring (7,10);
		x += CNPJ. substring (11,15);
		x += CNPJ. substring (16,18);
		CNPJ = x; 
	} else {
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace (".","");
		CNPJ = CNPJ. replace ("-","");
		CNPJ = CNPJ. replace ("/","");
	}
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro = "A verificação de CNPJ suporta apenas números!"; 
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (cpj=0; cpj<12; cpj++){
		a[cpj] = CNPJ.charAt(cpj);
		b += a[cpj] * c[cpj+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])){
		erro ="CNPJ Inválido!";
	}
	if (erro.length > 0){
		return (erro)
	}
	return '';
}

function checkDate(dtaDate){
	if (dtaDate.value == "" ){
		return false;
	}
	var err=0;
	dtaValue=dtaDate.value;
	if (dtaValue.length != 8 && dtaValue.length != 10 ) err=1
	mm = dtaValue.substring(3, 5);
	dd = dtaValue.substring(0, 2);
	yy = dtaValue.substring(6, 10);
	if (mm<1 || mm>12) err = 1
	if (dd<1 || dd>31) err = 1
	if (yy.length == 4){
		if (yy<1900) err = 1
	} else {
		//se ano for inferior a 30 se entende 20??
		//se for maior que 29 se entende 19??
		yy=parseInt(yy,10)
		yy += yy<30?2000:1900
	}
	if (mm==4 || mm==6 || mm==9 || mm==11){
		if (dd==31) err=1
	}
	if (mm==2){
		var dtaYear=parseInt(yy/4);
		if (isNaN(dtaYear)) {
			err=1;
		}
		if (dd>29) err=1
		if (dd==29 && ((yy/4)!=parseInt(yy/4))) err=1
	}
	dtaDate.value = dd + '/' + mm + '/' + yy

	if (err==1) {
		if (dtaValue.length < 8){
			dtaDate.value = "";
		} else {
			alert(dtaDate.value + ' é uma data inválida !');
			dtaDate.value = "";
			dtaDate.focus();
			return false;
		}
	}
	return true;
}

function checkTime(cpoTime){
	strTime = cpoTime.value
	err = 0;
	if (strTime == ''){
		return false;
	}
	if (strTime.indexOf(':') < 0) err = 1;
	if (err==0){
		strTimeArr = strTime.split(':');
		if(strTimeArr.length < 2 && strTimeArr.length > 3) err = 1;
	}
	if (err==0){
		hora = parseInt(strTimeArr[0]);
		minuto = parseInt(strTimeArr[1]);
		segundo = 0;
		if (strTimeArr.length == 3) segundo = parseInt(strTimeArr[2]);
		if (hora < 0 || hora > 23) err = 1; 
	}	
	if (err==0){
		if (minuto < 0 || minuto > 59) err = 1; 
	}		
	if (err==0){
		if (segundo < 0 || segundo > 59) err = 1; 
	}
	if (err == 1){
		alert(strTime + ' é uma hora inválida !');
		cpoTime.value = '';
		cpoTime.focus();
		return false;		
	}
}

function checkBlur(cpo,formato){
	if (cpo.value != ''){
		var rule = rules[formato];
		reg = rule.formato;		
		if (!reg.test(cpo.value)){
			alert('Formato inválido no campo '+formato);
			cpo.focus();
			return (false);								
		}	
	}
}


function checkMemo(memTime){
	maxlen = $(memTime).attr('maxlength');
	curlen = $(memTime).val().length;
	if (!!maxlen){
		if (curlen > maxlen){
			alert('Texto muito longo. Máximo permitido: '+maxlen)
			memTime.value = memTime.value.substr(0,maxlen);
			curlen = $(memTime).val().length;			
			$('#'+$(memTime).attr('name')+'_len').html(curlen+'&nbsp;caracteres. (máx: '+maxlen+')');
		};	
	};
}


function dummyFocus(cpo){
	valor = $(cpo).val();
	dummy = $(cpo).attr('dummy');
	if (valor == dummy) $(cpo).val('');
}
function dummyBlur(cpo){
	dummy = $(cpo).attr('dummy');
	valor = $(cpo).val();
	if (valor == '') $(cpo).val(dummy);
}


$.fn.clearForm = function() {
	return this.each(function() {
	var type = this.type, tag = this.tagName.toLowerCase();
	if (tag == 'form')
		return $(':input',this).clearForm();
	if (type == 'text' || type == 'password' || tag == 'textarea')
		if ($(this).attr('dummy') != ''){
			this.value = $(this).attr('dummy');			
		} else {
			this.value = '';			
		}
	else if (type == 'checkbox' || type == 'radio')
		this.checked = false;
	else if (tag == 'select')
		this.selectedIndex = -1;
	});
};

var rules = {
	numero:	{mascara: '',	valida: '0123456789', 	 formato:''},	
	inteiro:{mascara: '',	valida: '-+0123456789',	 formato: /^[-+]?\d*/},		
	decimal:{mascara: '',	valida: '-0123456789,',  formato:''},			
	money:	{mascara: '',	valida: '-0123456789,.', formato:''},				
	texto: 	{mascara: '',	valida: 'aáàâãbcçdeéèêfghiíìjklmnoóòõôpqrstuúùüvwxyz0123456789_-()[]{}:/|\.,;+=@*%#!?&ºª ', formato:''},	
	memo: 	{mascara: '',	valida: '', formato:''},	
	login:	{mascara: '',	valida: 'abcdefghijklmnopqrstuvwxyz0123456789_', formato:''},
	loginExt:{mascara: '', valida: 'abcdefghijklmnopqrstuvwxyz0123456789_.@-',formato:''},
	cep:	{mascara: '     -   ',		valida: '0123456789', 	formato: /[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9]/},		  
	data:	{mascara: '  /  /    ',		valida: '0123456789', 	formato: /^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))/},
	cpf:	{mascara: '   .   .   -  ', valida: '0123456789', 	formato: /[0-9][0-9][0-9].[0-9][0-9][0-9].[0-9][0-9][0-9]-[0-9][0-9]/},	  
	cnpj:	{mascara: '  .   .   /    -  ',valida: '0123456789',formato: /[0-9][0-9].[0-9][0-9][0-9].[0-9][0-9][0-9]\/[0-9][0-9][0-9][0-9]-[0-9][0-9]/},
	hora:	{mascara: '  :  :  ',		valida: '0123456789',	formato:  /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?/},
	hora2:	{mascara: '  :  ',			valida: '0123456789' ,	formato:  /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])?$/},
	tel:	{mascara: '(   )    -    ', valida: '0123456789', 	formato:''},
	email:	{mascara: '', valida: 'abcdefghijklmnopqrstuvwxyz0123456789_.@-',formato: /^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\]?)|(?:[a-zA-Z0-9-]+\.)+(?:[a-zA-Z]){2,}\.?)/}
}



