/*=============================================================================

			 	 TITLE:		NetMediaOne - Simple Form Validation
		  MODIFIED:		2008.03.21
		 AUTHOR(S): 	Graham Wheeler - NetMediaOne - www.netmediaone.com
		  REQUIRES:		NetMediaOne Core 1.2
									jQuery 1.2

=============================================================================*/

NMO.Validator = function(el) {
	
	var sp = this;
	
	this.container = el;
	this.$c = $(el);

	// 
	//	Set to "alert" to have errors displayed in a javascript alert window, or
	//	"inline" to have them appear next to the referenced form fields
	//
	this.notificationMethod = ( this.$c.attr("notificationmethod") != undefined ) ? this.$c.attr("notificationmethod") : "inline";
	
	// 
	//	Set to "before" or "after" to set the position of inline error messages
	//	relative to the referenced form field
	//
	this.notificationPosition = ( this.$c.attr("notificationposition") != undefined ) ? this.$c.attr("notificationposition") : "after";
	
	this.$c.submit( function() { return sp.isValid(); } );
	
};

NMO.Validator.prototype = {
	
	validationPatterns: [
		
		{ name: "Email", pattern: /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/, error: "Email address not in valid format" },
		{ name: "IPAddress", pattern: /^((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){3}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})$/, error: "IP address not in valid format" },
		{ name: "StrictPhoneFax", pattern: /^(([0-9]{1})*[- .(]*([0-9a-zA-Z]{3})*[- .)]*[0-9a-zA-Z]{3}[- .]*[0-9a-zA-Z]{4})+$/, error: "Number not in valid format" },
		{ name: "PhoneFax", pattern: /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/, error: "Number not in valid format" }
	],
	
	getLabel: function(el) {

		if ( el.title != "" ) {
			return "'"+el.title+"'";
		} else {
			return "'"+el.name+"'";
		}				
		
	},
	
	isValid: function() {

		var sp = this;
		var errors = [];

		//
		//	Verify that the input is not empty
		//
		$("input.Required, textarea.Required", sp.container).each( function() {
			if ( this.value == "" && !$(this).hasClass("MatchPattern") ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Must be provided"
				} );
			}
		} );

		
		//
		//	Verify that the input value conforms to certain patterns
		//
		$("input.MatchPattern", sp.container).each( function() {
			if ( ( $(this).hasClass("Required") && this.value == "" ) || this.value != "" ) {

				for ( var i = 0; i < sp.validationPatterns.length; i++ ) {
					
					var p = sp.validationPatterns[i];
					if ( $(this).hasClass( p.name ) && !p.pattern.test(this.value) ) {
						var el = this;
						errors.push( { 
							field: el,
							message: p.error
						} );
					}	
				}

			}
		} );


		//
		//	Verify that the input value is a positive number
		//
		$("input.IsPositiveNumber", sp.container).each( function() {
			var num = parseInt( this.value, 10 );
			if ( isNaN(num) || num < 1 ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Must be a number greater than zero"
				} );
			}
		} );
		
		
		//
		//	Verify that the selected value of a select box is NOT an invalid option
		//
		$("select.CheckForValidSelection", sp.container).each( function() {
			var opt = this.options[this.selectedIndex];
			if ( $(opt).hasClass("InvalidSelection") ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Invalid option"
				} );
			}
		} );
		
		//
		//	Verify that at least one member in a set of checkboxes or radio buttons is selected
		//
		$(".MustSelectOne", this.container).each( function() {
																														 
			if ( $("input:checked", this).length == 0 ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Must select at least one value"
				} );
			}
		} );

		if ( errors.length > 0 ) {
			
			if ( sp.notificationMethod == "alert" ) {
				
				var eList = new StringBuffer("Please correct the following errors:\n\n");
				
				for ( var i = 0; i < errors.length; i++ ) {
					eList.append( sp.getLabel(errors[i].field) ).append(": ").append(errors[i].message).append("\n");
				}

				alert( eList.toString() );

			} else if ( sp.notificationMethod == "inline" ) {

				// remove previous error messages if any exist
				$(".ValidationErrorMessage, .ErrorSummary", sp.container).remove();
				$(".FailedValidation", sp.container).removeClass("FailedValidation");
				
				$("#formControls").append('<div class="ErrorSummary">This form contains errors that must be fixed before the form can be submitted. Please review the information you provided to ensure that all required fields are filled out and that the information is correct.</div>');
				
				for ( var i = 0; i < errors.length; i++ ) {
					
					var field = $( errors[i].field );
					$(field).addClass("FailedValidation");

					var message = '<span class="ValidationErrorMessage">'+errors[i].message+'</span>';
					if ( sp.notificationPosition == "before" ) { field.before(message); }
					else if ( sp.notificationPosition == "after" ) { field.after(message); }

				}
				
			}
			
			return false;
			
		} else {
		
			return true;
			
		}

	}
	
};



jQuery( function() { 
					
	$("form.Validated").each( function() {
		
		new NMO.Validator(this);
																		 
	} );

} );


