/**********************************************************************************
/* 	settings.ar_tiposCampo, contiene los nombres de class html que se corresponderán 
	con tipos de validación para los campos de formulario que los contenga.
	
/* 	cada nombre da clase ha de tener dos funciones correspondientes.
	- una con el prefico r_ más el nombre de clase para los filtros de restricción.
	- otra con el prefijo v_ más el nombre clase para los filtros de validación.
	
/*  utilizaremos el atributo title de los campos para dar una referencia literal del 
	nombre del campo al usuario, en caso de error.

***********************************************************************************/
(function($){
	$.fn.formValidator = function( settings ) {
		
		settings = jQuery.extend({
			saltoLinea : 	"\n",
			idicadorLabel: 	"<small style='color:#FF0000;'>*</small>",
			colorValidable: "#CAE4FF",
			colorValido: 	"#D3FFCC",
			colorInvalido:	"#FFCCCD",
			
			// tipos de campo para validar			
			ar_tiposCampo: new Array(
				"jq_obligatorio",
				"jq_email",
				"jq_repiteCampo",
				"jq_numerico"
			),
			
			lang : $("html").attr("lang"),
			// textos del alert
			txtCampo_gl: "o campo ",
			txtObligatorio_gl: " non foi cuberto ",
			txtEmail_gl: " non é un e-mail ",
			txtRepieCampo_gl: " non coincide con ",
			txtNumerico_gl: " non é un número ",
			
			txtCampo_es: "el campo ",
			txtObligatorio_es: " no ha sido cubierto ",
			txtEmail_es: " no es un e-mail ",
			txtRepieCampo_es: " no coincide con ",
			txtNumerico_es: " no es un número ",
			
			txtCampo_en: "the ",
			txtObligatorio_en: " field hasn't been filled ",
			txtEmail_en: " field isn't an e-mail ",
			txtRepieCampo_en: " field doesn't match with ",
			txtNumerico_en: " field isn't a number ",
			
			/****************************** FILTROS DE RESTRICCIÓN ********************************
			/*	estas funciones añaden o quitan propiedades a los campos de dicho tipo.
			**************************************************************************************/
			r_jq_obligatorio : function( campo ){
				$(campo).css({ "background-color" : settings.colorValidable });
				return true;
			},
			// solo permite escribir números en este campo
			r_jq_numerico : function( campo ){
				$(campo).css({ "background-color" : settings.colorValidable });
				$(campo).bind( "keyup", function(e){
					if( /^[0-9||\s||\+||(||)]*$/.test( this.value ) ){
						this.antValue = this.value;
					}
					if( this.antValue ){
						this.value = this.antValue;
					}else{
						this.value = "";
					}
				});
				return true;
			},
			r_jq_email : function( campo ){
				$(campo).css({ "background-color" : settings.colorValidable });
				return true;
			},
			// vacía el campo si el valor fuese pegado
			r_jq_repiteCampo : function( campo ){
				$(campo).css({ "background-color" : settings.colorValidable });
				$(campo).bind( "keypress", function(e){
					if( !this.antValue && this.value.length > 1 ){
						this.value = "";
						this.antValue = "";
					}else if( this.antValue && this.value.length - this.antValue.length > 1 ){
						this.value = this.antValue;
					}else{
						this.antValue = this.value;
					}
				});
				$(campo).bind( "change", function(e){
					if( !this.antValue || this.antValue.length + 1 != this.value.length){
						this.value = "";
					}
				});
				return true;
			},
			
			/**************************** FILTROS DE VALIDACION ***********************************
			/*	estas funciones comprueban que el valor de los campos contengan un formato
				válido para su tipo.
			**************************************************************************************/
			// comprueba que el campo no esté vacio.
			v_jq_obligatorio : function( campo ){
				var value = $(campo).val();
				if( value !== "" ){
					return true;
				}else{
					settings.msgError += eval("settings.txtCampo_"+settings.lang) + $(campo).attr("title") + eval("settings.txtObligatorio_"+settings.lang) + settings.saltoLinea ;
					return false;
				}
			},
			// comprueba que el campo sea numerico
			v_jq_numerico : function( campo ){
				var value = $(campo).val();
				if( /^[0-9||\s||\+||(||)]*$/.test( value ) && value != "" ){
					return true;
				}else{
					settings.msgError += eval("settings.txtCampo_"+settings.lang)  + $(campo).attr("title") + eval("settings.txtNumerico_"+settings.lang) + settings.saltoLinea ;
					return false;
				}
			},
			// comprueba que el campo sea una dirección de correo electrónico.
			v_jq_email : function( campo ){
				var value = $(campo).val();
				if( /^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+\.[A-Za-z0-9_.]+[A-za-z]$/.test( value ) ){
					return true;
				}else{
					settings.msgError += eval("settings.txtCampo_"+settings.lang) + $(campo).attr("title") + eval("settings.txtEmail_"+settings.lang) + settings.saltoLinea ;
					return false;
				}
			},
			// comprueba que este campo tiene le mismo valor que el del campo con id especificado entre ##id del campo##
			v_jq_repiteCampo : function( campo ){
				var campoR = $("#" + $(campo).attr("class").replace(/(.*)(##)([^##]*)(##)(.*)/g ,"$3") );
				var rValue = campoR.val();
				var value = $(campo).val();
				if( value == rValue && value != "" ){
					return true;
				}else{
					settings.msgError += eval("settings.txtCampo_"+settings.lang) + $(campo).attr("title") + eval("settings.txtRepieCampo_"+settings.lang) + $(campoR).attr("title")+ settings.saltoLinea ;
					return false;
				}
			},
			
			formValido:		true,
			msgError:		""
			
		}, settings);
		
		
		
		function inicializar( forms ){
			$( forms ).each(function( Nf, form ){
									 
				// filtros de restricción
				for( var i = 0 ; i < settings.ar_tiposCampo.length ; i ++ ){
					$(form).find("."+settings.ar_tiposCampo[i]).each(function( Nc, campo ){
						var filtroRestricion = eval("settings.r_"+settings.ar_tiposCampo[i]);
						$(campo).bind( "focus", function(e){
							$(campo).css({ "background-color" : settings.colorValidable });
						});
						if( filtroRestricion ){
							filtroRestricion(campo);
							var id_campo = $(campo).attr("id");
							if( id_campo ){
								ponerAsterisco( id_campo );
							}
						}
					});
				}
				
				// al hacer submit del formulario
				$( form ).bind("submit", function( e, form ){
					settings.formValido = true;
					settings.msgError = "";
					
					for( var i = 0 ; i < settings.ar_tiposCampo.length ; i ++ ){
						$(form).find("."+settings.ar_tiposCampo[i]).each(function( Nc, campo ){
							campo.valido = true;
						});
					}
					// filtros de validación
					for( var i = 0 ; i < settings.ar_tiposCampo.length ; i ++ ){
						$(form).find("."+settings.ar_tiposCampo[i]).each(function( Nc, campo ){
							var filtroValidacion = eval("settings.v_"+settings.ar_tiposCampo[i]);
							if( filtroValidacion ){
								if( !filtroValidacion(campo) ){
									campo.valido = false;
									settings.formValido = false;
								}
								if( campo.valido ){
									$(campo).css({ "background-color" : settings.colorValido });
								}else{
									$(campo).css({ "background-color" : settings.colorInvalido });
								}
							}
						});
					}
					
					if( settings.formValido ){
						//alert("formulario OK.");
						return true;
					}else{
						alert(settings.msgError);
						return false;
					}
					if( settings.msgError != "" ){
						settings.msgError += settings.saltoLinea;
					}
					
				});
			});
		}
		
		// coloca un asterisco rojo a todos los label de canpos validables
		function ponerAsterisco( id_campo ){
			$("label").each(function( Nl, label ){
				if( $(label).attr("for") == id_campo ){
					if( !label.indicado ){
						
						var conLabel = "";
						if(/:$/g.test( $(label).html().split(" ").join("") )){
							conLabel = $(label).html().replace(/:/,"")+" "+settings.idicadorLabel+":";
						}else{
							conLabel = $(label).html()+" "+settings.idicadorLabel;
						}
						
						$(label).html( conLabel );
						label.indicado = true;
					}
				}
			});
		}
		
		inicializar(this);
		
	}
})(jQuery);

// validamos todos lo formularios
/*
$(document).ready(function() {
	$('form#myForm').formValidator({
		saltoLinea : 	"\n",
		idicadorLabel: 	"<small style='color:magenta;'>*</small>",
		colorValidable: "#FFF999",
		colorValido: 	"#D3FFCC",
		colorInvalido:	"#FFCCCD",
		ar_tiposCampo: new Array(
				"jq_obligatorio",
				"jq_email",
				"jq_repiteCampo",
				"jq_numerico"
		)
	});
})
*/

