/**
* jQuery Form Validator Plugin
* Author: Justin Kimbrell (SaucePan Creative)
* Build: 0.1.4 - October 18, 2010
* Copyright 2010 - All rights reserved
*
* Update History
* v0.1.2 - 08/12/10
* Added the current object (this) to the call back functions success and fail.
* The new phone number (phone) regex expression was also add.
*/

jQuery.fn.extend({
	
	regex: function(type) {
		
		if(typeof type != "object" && typeof type != "function")
			var regex = $.getRegex(type);
		else
			var regex = type;
			
		regex = regex.test($(this).val());
		
		return regex;
	},
	
	check: function(obj) {
		
		var elem = $(this);
		var value = elem.val();
		var toPass = true;
		var regex;
		
		if(obj.type)
			var regex = obj.type;
		
		if(obj.regex)
			var regex = obj.regex;
				
		this.each(function() {
	
			if(obj.type && !elem.regex(regex) || obj.regex && !elem.regex(regex))
				toPass = false;
								
			if(obj.length && !elem.isLength(obj.length))
				toPass = false;
			
			if(obj.require && obj.require == true && !$.isNotEmpty(elem))
				toPass = false;
						
			if(obj.match && !elem.match(obj.match))
				toPass = false;
								
			if(obj.doNotMatch && elem.match(obj.doNotMatch))
				toPass = false;
							
			if(obj.fail && typeof obj.fail == "function" && toPass == false)
				obj.fail($(this))			
			
			if(obj.success && typeof obj.success == "function" && toPass == true)
				obj.success($(this));
		});
		
		return toPass;
	},	
	
	isLength: function(length) {
		
		if($(this).val().length == length)
			return true;
		
		return false;
		
	},
	
	match: function(obj2) {
		if($(this).val() != $(obj2).val())
			return false;
			
		return true;
	},
	
	validate: function(obj, callback) {
		var toSubmit = true;
		
		$.each(obj, function(index, value) {
			var check = $(index).check(value);
			
			if(toSubmit != false)
				toSubmit = check;
		});
		
		if(toSubmit == true && typeof callback == "function") {
			callback();
		}
		
		return toSubmit;
	}
	
});

jQuery.extend({	
	
	getRegex: function(type) {
		
		var regex = new Array();
		
		regex["alpha"] = /^[a-zA-Z]*$/;
		regex["abc"] = regex["alpha"];
		regex["numeric"] = /^[0-9]*$/;
		regex["123"] = regex["numeric"];
		regex["alphaNumeric"] = /[0-9][a-zA-Z]*$/;
		regex["abc123"] = regex["alphaNumeric"];
		regex["address"] = /[^0-9][a-zA-Z]$/;
		regex["123abc"] = regex["address"];
		regex["email"] = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		regex["phone"] = /^([0-9]{3})+[-]+([0-9]{3})+[-]+([0-9]{4})$/;
				
		return regex[type];
	},

	isNotEmpty: function(obj) {
	    var filter = /^\s*$/;
	    
		if(filter.test(obj.val()))
			return false;
		
		return true;
	},

	isValidDate: function(obj, filter) {
		
		if(!filter)
			var filter = /([0-9]{2})+\/+([0-9]{2})+\/+([0-9]{4})/;
		
		if(!filter.test(obj.val()))
			return false;
		
		return true;
	}
});

