;(function($){
	$.extend({
		jqValidacao: function(options) {
			return {
				init: function(options) {
					settings = jQuery.extend({
						lang: options.lang
					}, options);
					$.jqValidacao.loadMask();
					return this;
				},

				// Máscara nos campos
				// -----------------------------------------------------------------
				loadMask: function(p) {
					//$('input:text').setMask();
					//$('.updateArq').live('click',function(){



					$('.isnumeric').each(function(i){
						$("#"+ $(this).attr('id')).keypress(function(event) {
							// Backspace, tab, enter, end, home, left, right
							// We don't support the del key in Opera because del == . == 46.
							var controlKeys = [8, 9, 13, 35, 36, 37, 39];
							// IE doesn't support indexOf
							var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
							// Some browsers just don't raise events for control keys. Easy.
							// e.g. Safari backspace.
							if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
									(49 <= event.which && event.which <= 57) || // Always 1 through 9
									(48 == event.which && $(this).attr("value")) || // No 0 first digit
									isControlKey) { // Opera assigns values for control keys.
								return;
							} else {
								event.preventDefault();
							}
						});
					});

					$('.isdate').each(function(i){
						//$(".isdate").keypress(function (e) {
						
						//$("#"+ $(this).attr('id')).live('keypress',function(){
						$("#"+ $(this).attr('id')).keypress(function(e) {
							if( $.jqValidacao.keyNumeric(e) ) return false;
							var mask	= '##/##/####';
							var campo =  $(this).val().length;
							var saida = mask.substring(0,1);
							var texto = mask.substring(campo);

							var lenCampo	= new Number(campo);
							var lenMask		= new Number(mask.length);

							if((lenCampo+1) > lenMask) {
								return $.jqValidacao.key_check(e);		
							} else {
								var code = (e.keyCode ? e.keyCode : e.which);

								if( !$.jqValidacao.key_check(e) ){// permite apagar o que foi digitado 
									if(texto.substring(0,1) != saida) {
										$(this).val( $(this).val() + texto.substring(0,1) ); 
									}
								}
							}
						});						

						$("#"+ $(this).attr('id')).blur(function() {
							var valida = $.jqValidacao.isDate({ date:$(this).val() });
							if(!valida) {
								$(this).val("");
								$(this).removeClass("bgbd");
								$(this).addClass("campo_focus");
								//## alert('Informe uma data válida');
								return false;
							}
						});
					});

					$('.iscep').each(function(i)		{ $("#"+ $(this).attr('id')).mask("99999-999"); });
					$('.isphone').each(function(i)  { $("#"+ $(this).attr('id')).mask("(99) 9999-9999"); });
					$('.iscpf').each(function(i)		{ $("#"+ $(this).attr('id')).mask("999.999.999-99"); });
					$('.iscnpj').each(function(i)		{ $("#"+ $(this).attr('id')).mask("99.999.999/9999-99"); });
					$('.ispercent').each(function(i){ $("#"+ $(this).attr('id')).mask("999.99"); });					
					$('.ismaskdate').each(function(i)	{ $("#"+ $(this).attr('id')).mask("99/99/9999"); });
					$('.ismaskhora').each(function(i)	{ $("#"+ $(this).attr('id')).mask("99:99"); });
					$('.ismesano').each(function(i)	{ $("#"+ $(this).attr('id')).mask("99/99"); });
					$('.ismoney').each(function(i)	{ 
						$("#"+ $(this).attr('id')).priceFormat({
							prefix: '',
							centsSeparator: ',',
							thousandsSeparator: '.'
						});
					});
				},// end : loadMask

				// Máscara nos campos
				// -----------------------------------------------------------------
				loadMaskPerson: function(p) {
					//$('input:text').setMask();
					//$('.updateArq').live('click',function(){
					$box = p.boxdiv;
					$($box +' .isdate').each(function(i){
						//$(".isdate").keypress(function (e) {						
						//$("#"+ $(this).attr('id')).live('keypress',function(){
						$("#"+ $(this).attr('id')).keypress(function(e) {
							if( $.jqValidacao.keyNumeric(e) ) return false;
							var mask	= '##/##/####';
							var campo =  $(this).val().length;
							var saida = mask.substring(0,1);
							var texto = mask.substring(campo);

							var lenCampo	= new Number(campo);
							var lenMask		= new Number(mask.length);

							if((lenCampo+1) > lenMask) {
								return $.jqValidacao.key_check(e);		
							} else {
								var code = (e.keyCode ? e.keyCode : e.which);

								if( !$.jqValidacao.key_check(e) ){// permite apagar o que foi digitado 
									if(texto.substring(0,1) != saida) {
										$(this).val( $(this).val() + texto.substring(0,1) ); 
									}
								}
							}
						});

						$("#"+ $(this).attr('id')).blur(function() {
							var valida = $.jqValidacao.isDate({ date:$(this).val() });
							if(!valida) {
								$(this).val("");
								$(this).removeClass("bgbd");
								$(this).addClass("campo_focus");
								//## alert('Informe uma data válida');
								return false;
							}
						});
					});

					$($box +' .iscep').each(function(i)				{ $("#"+ $(this).attr('id')).mask("99999-999"); });
					$($box +' .isphone').each(function(i)			{ $("#"+ $(this).attr('id')).mask("(99) 9999-9999");});
					$($box +' .iscpf').each(function(i)				{ $("#"+ $(this).attr('id')).mask("999.999.999-99"); });
					$($box +' .iscnpj').each(function(i)			{ $("#"+ $(this).attr('id')).mask("99.999.999/9999-99"); });
					$($box +' .ispercent').each(function(i)		{ $("#"+ $(this).attr('id')).mask("999.99"); });					
					$($box +' .ismaskdate').each(function(i)	{ $("#"+ $(this).attr('id')).mask("99/99/9999"); });
					$($box +' .ismaskhora').each(function(i)	{ $("#"+ $(this).attr('id')).mask("99:99"); });
					$($box +' .ismesano').each(function(i)		{ $("#"+ $(this).attr('id')).mask("99/99"); });
				},// end : loadMaskPerson

				isDate: function(p) {
					value = p.date;
					if(value.length >= 1){ // verificando data  
						var data        = value;  
						var dia         = data.substr(0,2);  
						var barra1      = data.substr(2,1);  
						var mes         = data.substr(3,2);  
						var barra2      = data.substr(5,1);  
						var ano         = data.substr(6,4);  
						if(data.length!=10||barra1!="/"||barra2!="/"||isNaN(dia)||isNaN(mes)||isNaN(ano)||dia>31||mes>12)return false;  
						if((mes==4||mes==6||mes==9||mes==11) && dia==31)return false;  
						if(mes==2 && (dia>29||(dia==29 && ano%4!=0)))return false;  
						if(ano < 1900)return false;
					}
					return true;  
				},// end : isDate

				isCPF: function(p) {
					var cpf = p.cpf;
					var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
					if(!filtro.test(cpf)){
						window.alert("CPF inválido. Tente novamente 01. ("+ cpf +")");
						return false;
					}				
					cpf = cpf.replace(/\./g,"");
					cpf = cpf.replace(/\-/g,"");

					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 inválido. Tente novamente 02. ("+ cpf +" / "+ p.cpf +")");
						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 inválido. Tente novamente 03. ("+ cpf +")");
						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 inválido. Tente novamente 04. ("+ cpf +")");
						return false;
					}
					return true;
				},// end : isCPF

				isCNPJ: function(p) {
					var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais
					var cnpj = p.cnpj;
					var filtro = /^\d{2}.\d{3}.\d{3}\/\d{4}-\d{2}$/i;
					if(!filtro.test(cnpj)){
						window.alert("CPNJ inválido. Tente novamente 01. ("+ cnpj +")");
						return false;
					}
					cnpj = cnpj.replace(/\D+/g,'');
					//cnpj = c.value.replace(/\D+/g, '');
					digitos_iguais = 1;
					if (cnpj.length != 14){
						//alert('CNPJ inválido 02');
						return false;
					}
					for (i = 0; i < cnpj.length - 1; i++)
					if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
						digitos_iguais = 0;
						break;
					}
					if (!digitos_iguais){
						tamanho = cnpj.length - 2
						numeros = cnpj.substring(0,tamanho);
						digitos = cnpj.substring(tamanho);
						soma = 0;
						pos = tamanho - 7;
						for (i = tamanho; i >= 1; i--){
							soma += numeros.charAt(tamanho - i) * pos--;
							if (pos < 2)
							pos = 9;
						}
						resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
						if (resultado != digitos.charAt(0)){
							//alert('CNPJ inválido 03');
							return false;
						}
						tamanho = tamanho + 1;
						numeros = cnpj.substring(0,tamanho);
						soma = 0;
						pos = tamanho - 7;
						for (i = tamanho; i >= 1; i--){
							soma += numeros.charAt(tamanho - i) * pos--;
							if (pos < 2)
							pos = 9;
						}
						resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
						if (resultado != digitos.charAt(1)){
							//alert('CNPJ inválido 04');
							return false;
						}else {
							return true;
						}
					}else{
						//alert('CNPJ inválido 05');
						return false;
					}
				},// end : isCNPJ


				fcClear: function(p) {
					//alert( p.str +" / "+ p.sub );
					i = p.str.indexOf(p.sub);
					r = "";
					if (i == -1) return p.str;
					
					alert( p.str.substring(i + p.sub.length) );
					//var nString = $.jqValidacao.fcClear({str:p.str.substring(i + p.sub.length), sub:p.sub})
					
					
					//r += p.str.substring(0,i) + nString;
					r += p.str.substring(0,i) + remove(p.str.substring(i + p.sub.length), sub);
					return r;
				}, // end : fcClear


				// Validar Formulário de Cadastro
				// -----------------------------------------------------------------
				validarCadastro: function(p) {
					var error = 0;
					$('.required').each(function(i){
						// Verifica se o campo é requerido
						// ------------------------------------------------------
						var item = $(this).val();
						var idCampo = $(this).attr('id');
						if( item.length == 0) {
							error = 1;
						} else {
							$(this).removeClass("campo_focus");
							$(this).addClass("bgbd");
						}

						// Verifica se é uma Data válida
						// ------------------------------------------------------
						if($(this).hasClass("isdate")){
							var valida = $.jqValidacao.isDate({ date:$(this).val() });
							if(!valida) error = 2;				
						}// end : isdate

						// Verifica se o e-mail é válido
						// ------------------------------------------------------
						if($(this).hasClass("isemail")){
							if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(item)) error = 2;
						}// end : ismail

						// Verifica o mínimo de caracteres permitidos
						// ------------------------------------------------------
						if($(this).hasClass("minimo5")){
							if( item.length < 5) { error = 3; }
						}// end : ismail

						
						
						// Destaca o campo com erro
						// ------------------------------------------------------
						if( error != 0){
							$(this).focus();					
							$(this).removeClass("bgbd");
							$(this).addClass("campo_focus");
							//## jAlert('Preencha o campo em destaque corretamente.', 'Alerta de Erro');
							//alert( $(this).attr("rel") );
							$('#'+ idCampo).blur(function(){
								if( $(this).val().length > 0 ){ $(this).removeClass("campo_focus"); $(this).addClass("bgbd"); }
							});
							return false;
						}
					});// end : .required each

					if( error != 0)  return false;					
					return true;
				},// end : validarCadastro


				// teclas especiais (tab, backspace, delete, enter)
				key_check: function(e) {
					var code = (e.keyCode ? e.keyCode : e.which);
					var functional = false;
					if (code ==  8) functional = true;
					if (code ==  9) functional = true;
					if (code == 13) functional = true;
					if (code == 37) functional = true;
					if (code == 39) functional = true;
					if (code == 46) functional = true; // delete
					return functional;				
				},// end : key_check

				keyNumeric: function(e) {
					var code = (e.keyCode ? e.keyCode : e.which);
					var functional = false;
					if(code >= 96 && code <= 105) functional = true;
					return functional;
				},// end : keyNumeric

				/*
				function key_check_OLD (e) {
					var code = (e.keyCode ? e.keyCode : e.which);
					var functional = false;
					if (code ==  8) functional = true;
					if (code ==  9) functional = true;
					if (code == 13) functional = true;
					if (code == 37) functional = true;
					if (code == 39) functional = true;
					if (code == 46) functional = true; // delete
					return functional;
				},

				// filtra somente os números
				function keyNumeric_OLD (e) {
					var code = (e.keyCode ? e.keyCode : e.which);
					var functional = false;
					if(code >= 96 && code <= 105) functional = true;
					return functional;
				}
				*/

				um: function() { 
					//## alert('um ' + settings.name ) 
				}

			};
		}()
	});
})(jQuery);
