/*
	gr-jquery-validate.js v1.2

	Simple validation for Multiplier Forms

	Accepts the following (optional) parameters:
		options:
			required: Required field you want checked => Error value you want displayed
			checks: Fields you want checked (that aren't required) => Error value you want displayed 
			submit: Set to false to disable submit of form (if used in conjunction with ajax script, debug, etc.)
			preValidationFn: Executed before the validation of the form
			successHandler: Overrides default submit, so you can add extra processing/validation
			errorHandler: Overrides default error handling (alert value, then focus)
*/
(function($) {

	// Plugin definition
	$.fn.validate = function(options) {	
		
		// Set options
		var opts = $.extend({}, $.fn.validate.defaults, options);

		// And set success/failure functions
		// And make checks/required objects available
		var success = opts.successHandler || $.fn.validate.successHandler,
			failure = opts.errorHandler || $.fn.validate.errorHandler,
			required = opts.required,
			checks = opts.checks;

		// Function to do validation on a single field
		function checkField(f, req) {
			var t = f.length && !f.type ? 'radio' : f.type,
				msg = (required && required[f.name]) || (checks && checks[f.name]);
			switch (t) {
				case 'checkbox':
					if (req && !f.checked) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					}
					break;
				case 'file':
				case 'textarea':
				case 'password':
				case 'text': 
					if (f.name == 'emailAddress' && !$.fn.validate.validEmail(f.value)) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					} else if (f.name == 'postalCode' && !$.fn.validate.validPostalCode(f.value)) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					} else if (f.name == 'phoneNumber' && !$.fn.validate.validPhoneNumber(f.value)) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					}
					if (req && f.value === '') {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					}
					break;
				case 'select-one':
					if (f.selectedIndex === 0) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					}
					break;
				case 'radio':
				
					// Make all radio button cases an array
					var fs = f.length ? f : [f],
						good = false;
						
					// Loop through created array, if none are checked throw error
					for (var l = fs.length, e = 0; e < l;  e++) {
						if (fs[e].checked) {
							good = true;
						}
					}
					if (!good) {
						if (failure.call(this, f, msg) === false) return false;
						failed = true;
					}
					break;
			}
		}

		// Return jquery object for each input
		return this.each(function () {
			var $this = $(this);		
			$this.submit(function (evt) {
				evt.preventDefault();

				// Store 'validating' in form expando in case another
				// jquery plugin needs it in the chain
				$(this).data('validating', true);

				// Launch prevalidation code
				if (opts.preValidationFn) {
					if (opts.preValidationFn.call(this) === false) return false;
				}

				// Remember if we failed (in case we're not bailing immediately)
				var failed = false;

				// Check fields
				var r = required || false,
					c = checks || false,
					f;
				if (r) {
					for (f in r) {
						if (this[f]) {
							if (checkField.call(this, this[f], true) === false) return false;
						}
					}
				}
				if (c) {
					for (f in c) {
						if (this[f]) {
							if (checkField.call(this, this[f], false) === false) return false;
						}
					}
				}

				if (!failed) {
					
					// If we got this far, do submit
					if (success.call(this, opts) === false) {
						return false;
					} else {
						
						// Store 'validated' in form expando in case another
						// jquery plugin needs it in the chain
						$(this).data('validated', true);
					}
				}		
			});
		});
	};

	// Defaults
	$.fn.validate.defaults = {
		submit: true
	};
	
	// Handles failed validation of form element
	$.fn.validate.errorHandler = function(f, msg) {
		alert(msg);
		if (f.length) {
			f[0].focus();
		} else {
			f.focus();
			f.select();
		}
		return false;
	};

	// Handles successful validation of form
	$.fn.validate.successHandler = function(opts) {
		if (opts.submit) {
			this.submit();
		}
	};

	// Function to validate email address
	$.fn.validate.validEmail = function (email) {
		if (email === '') return true;
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return reg.test(email) ? true : false;
	};
	
	// Function to validate phone number
	$.fn.validate.validPhoneNumber = function (nmbr) {
		if (nmbr === '') return true;
		var stripped = nmbr.replace(/[\(\)\.\-\ ]/g, '');
		return (/[^\d]/).test(stripped) || stripped.length != 10 ? false : true;
	};
	
	// Function to validate postal code
	$.fn.validate.validPostalCode = function (postal) {
		if (postal === '') return true;
		return (/[^\d]/).test(postal) || postal.length != 5 ? false : true;
	};

})(jQuery);