// JavaScript Document
;(function($) {

	$.fn.validate = function(options)
	{
		$(this).bind('submit', function() {
			
			$('input:button, input:submit').attr('disabled', true);
			//comenzar la validación			
			for(var field in options.rules)
			{
				if(options.rules[field].required == true)
				{
					if($('#' + field).val() == '')
					{
						show_alert(field, options.messages.required);
						
						return false;
					}
					
					//validar el tipo
					if(options.rules[field].pattern != undefined)
					{
						if(!checkPattern($('#' + field).val(), options.rules[field].pattern))
						{
							var message = options.messages[options.rules[field].pattern];
							if(message == undefined) message = options.rules[field].message;
							
							show_alert(field, message);
							return false;
						}
					}
					
					//validar longitud
					if(options.rules[field].minlength != undefined)
					{
						var value = $('#' + field).val();
						if(value.length < options.rules[field].minlength)
						{
							var message = options.messages.minlength;
							message = message.replace("###", options.rules[field].minlength);
							
							show_alert(field, message);
							
							return false;
						}
					}
				}
				else if(options.rules[field].call_function != undefined) //custom function				
				{
					if(!options.rules[field].call_function())
						return false;
				}
			}
			
		});
		
		checkPattern = function(value, pattern)
		{
			var reg_pattern = '';
			
			if(pattern == 'alpha')
			{
				reg_pattern = /([aA-zZ ]+)$/;
			}
			else if(pattern == 'alphanum')
			{
				reg_pattern = /([aA-zZ0-9 ]+)$/;
			}
			else if(pattern == 'numeric')
			{
				reg_pattern = /([0-9]+)$/;
			}
			else if(pattern == 'double')
			{
				reg_pattern = /\d+$|^\d+\.\d{2}$/;
			}
			else if(pattern == 'email')
			{
				reg_pattern = /[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/;
			}
			else
			{
				reg_pattern = pattern;
			}
			
			return value.match(reg_pattern);
		};
		
		show_alert = function(field, message)
		{
			var ret;
			var textarea = document.createElement('textarea');
			message = str_replace(message, '<br />', '\r\n');
			textarea.innerHTML = message;
			ret = textarea.value;
			
			alert(ret);
			$('#' + field).focus();
			$('#' + field).select();
			
			$('input:button, input:submit').attr('disabled', false);
		};
		
		str_replace = function(haystack, needle, replacement)
		{
			var temp = haystack.split(needle);
			return temp.join(replacement);
		};
	}

})(jQuery);

