/* *
 *	Plugin: hValidator
 *	Version: 0.0.2 
 *  Last Revision: 02-03-2011
 * */
(function ($) {
	
	var hValidatorGlobalSettings=false;
	
	//Llamada externa que se hace del plugin, y crea la interfaz para interactuar con el mismo 
	$.fn.hValidatorPlugin = function (options) {
		$.hValidatorPlugin.impl.init(options, $(this));
	};
	
	//Llamada que interpreta la llamada externa y inicializa el plugin con algunos parametros
	$.hValidatorPlugin = function (options) {
		$.hValidatorPlugin.impl.init(options);
	};
	
	$.triggerValidateFunction = function (event, noMessageJustColor) {
		$.hValidatorPlugin.impl.triggerValidateFunction(event, noMessageJustColor);
	};
	
	$.warningAlert = function (event, executeActionForm, aMessages, noMessageJustColor) {
		$.hValidatorPlugin.impl.warningAlert(event, executeActionForm, aMessages, noMessageJustColor);
	};
	
	$.colorerErrors = function (object, showDivError) {
		$.hValidatorPlugin.impl.colorerErrors(object, showDivError);
	};
	
	//Inicializacion de variables por default
	$.hValidatorPlugin.defaults = {
		//Variables por default
		errorClass:"inputRequired",						//Es el selector que debe recorrer para los errores, puede ser customizado sin problemas
		labelErrorCustomClass:false,					//Clase customizable del label { .classExample }
		inputErrorCustomClass:false,					//Clase customizable del input { .classExample }
		warningWith:"popup", 							//Tipo de alerta (en div, o con popup) { popup - div }
		labelOrInputClassError:"input",					//La colorizacion, si es de tipo input, coloriza esto sino los labels  { input - label - both (ambos) }
		triggerValidateOnEvent:"blur",					//Dispara la funcion de validar, segun el evento que se quiera  { blur - click - mouseout - etc }
			

		//Inicializacion de textos y alertas
		inputAlert:"- Hay campos sin rellenar.",
		inputEmailAlert:"- La direccion de correo electronico es incorrecta.",
		textareaAlert:"- Hay textos sin completar.",
		selectAlert:"- Hay opciones sin seleccionar."
	};
	
	$.hValidatorPlugin.impl = {
		
		
		init : function (options, obj) {
			hValidatorGlobalSettings = $.extend({}, $.hValidatorPlugin.defaults, options);
			
			//Instancia del objeto
			hValidatorGlobalSettings.objInstance = obj;
			
			//Evento que se dispara cuando hace submit del objeto instanciado
			hValidatorGlobalSettings.objInstance.submit(function(event){
				$.triggerValidateFunction(event);
			});
			
			//Evento que se dispara cuando se ejecuta un evento de un subobjeto del objeto instanciado
			$("#"+hValidatorGlobalSettings.objInstance.attr("id")+" ."+hValidatorGlobalSettings.errorClass).bind(hValidatorGlobalSettings.triggerValidateOnEvent, function(event){
				$.triggerValidateFunction(event, true);
			});
		},
		
		triggerValidateFunction : function (event, noMessageJustColor) {
			
				executeActionForm=true;
				aMessages=new Array();
				$("#"+hValidatorGlobalSettings.objInstance.attr("id")+" input,select,textarea").each(function() {
					//Bloque generico que trata todos los selectores que tengan la clase inputRequired
					if($(this).hasClass(hValidatorGlobalSettings.errorClass)) {
						switch($(this).get(0).tagName.toLowerCase()) {
							case "select":
								if($(this,":first").val()=="0" || $(this,":first").val()=="") {
									aMessages["select"]=hValidatorGlobalSettings.selectAlert;
									$.colorerErrors($(this), true);
									executeActionForm=false;
								} else {
									$.colorerErrors($(this));
								}
								break;
							case "input":
								if(!$(this).val()) {
									aMessages["input"]=hValidatorGlobalSettings.inputAlert;
									$.colorerErrors($(this), true);
									executeActionForm=false;
								} else if($(this).val()) {
									$.colorerErrors($(this));
								}
								break;
							case "textarea":
								if(!$(this).val()) {
									aMessages["textarea"]=hValidatorGlobalSettings.textareaAlert;
									$.colorerErrors($(this), true);
									executeActionForm=false;
								} else if($(this).val()) {
									$.colorerErrors($(this));
								}
								break;
						}

					}
					
					//Bloque personalizado para los selectores que son distintos
					if($(this).hasClass("inputRequiredEmail")) {
						if(!$(this).val()) {
							aMessages["inputEmail"]=hValidatorGlobalSettings.inputEmailAlert;
							$.colorerErrors($(this), true);
							executeActionForm=false;
						} else if($(this).val()) {
							if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(this).val())){
								$.colorerErrors($(this));
							} else {
								aMessages["inputEmail"]=hValidatorGlobalSettings.inputEmailAlert;
								$.colorerErrors($(this), true);
								executeActionForm=false;
							}
							
						}
					}
				});
				
				if(!executeActionForm) {
					$.warningAlert(event, executeActionForm, aMessages, noMessageJustColor);
				}
				
		},
		
		colorerErrors : function (object, showDivError) {
			var classLabelError = (hValidatorGlobalSettings.labelErrorCustomClass ? hValidatorGlobalSettings.labelErrorCustomClass : "errorLabelBlock");
			var classInputError = (hValidatorGlobalSettings.inputErrorCustomClass ? hValidatorGlobalSettings.inputErrorCustomClass : "errorInputBlock");

			if(showDivError) {
				switch(hValidatorGlobalSettings.labelOrInputClassError) {
					case "input":
						object.addClass(classInputError);
						break;
					
					case "label":
						object.prev("label").addClass(classLabelError);
						break;
						
					case "both":
						object.addClass(classInputError);
						object.prev("label").addClass(classLabelError);
						break;
				}
			} else {
				if(object.prev("label").hasClass(classLabelError)) {
					object.prev("label").removeClass(classLabelError);
				}
				if(object.hasClass(classInputError)) {
					object.removeClass(classInputError);
				}
			}
		},
		
		warningAlert : function (event, executeActionForm, aMessages, noMessageJustColor) {
			if(!executeActionForm) {
				event.preventDefault();
				if(!noMessageJustColor) {
					var message="";
					if(aMessages) {
						for(rMessages in aMessages) {
							message=message+aMessages[rMessages]+"\n";
						}
					} else {
						message=" - Hay campos sin completar";
					}
					
					if(hValidatorGlobalSettings.warningWith=="popup") {
						alert(message);
					} else if(hValidatorGlobalSettings.warningWith=="block") {
						alert(message);
					} else if(hValidatorGlobalSettings.warningWith=="justMessage") {
						$("#"+hValidatorGlobalSettings.objInstance.attr("id")).append(message);
					}
				}
				
			}
		}
	
	
	
	};
	
	
})(jQuery);
