/*=============================================================================

			 	 TITLE:		NetMediaOne - Simple Form Validation
		  MODIFIED:		2009.01.24
		 AUTHOR(S): 	Graham Wheeler - NetMediaOne - www.netmediaone.com
		  REQUIRES:		NetMediaOne Core 1.2
									jQuery 1.3

=============================================================================*/

NMO.Validator = {
	
	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: "EmailWithSubstitutionTags", 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})+)|\[\w+\]$/, 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: "PhoneFax", 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: "PositiveNumber", pattern: /^[1-9]+([0-9])*$/, error: "Must be a number greater than zero" }
		
	],
	
	getLabel: function(el) {

		if ( el.title != "" ) {
			return "'"+el.title+"'";
		} else {
			return "'"+el.name+"'";
		}				
		
	},
	
	isValid: function(el) {

		var errors = [];
		
		var self = 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";


		//
		//	Verify that the input is not empty
		//
		$(".Required", this.container).each( function() {
			if ( $(this).val() == "" && !$(this).hasClass("MatchPattern") ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Must be provided"
				} );
			}
		} );
		
		
		//
		//	Compares two values to verify that they are the same
		//
		$("[crosscheck]", this.container).each( function() {
			if ( $(this).val() != $( $(this).attr("crosscheck") ).val() ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Values do not match"
				} );
			}
		} );

		
		//
		//	Verify that the input value conforms to certain patterns
		//
		$(".MatchPattern", this.container).each( function() {
			if ( ( $(this).hasClass("Required") && this.value == "" ) || this.value != "" ) {

				for ( var i = 0; i < self.validationPatterns.length; i++ ) {
					
					var p = self.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 selected value of a select box is NOT an invalid option
		//
		$("select.CheckForValidSelection", this.container).each( function() {
			var opt = this.options[this.selectedIndex];
			if ( $(opt).hasClass("InvalidSelection") ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "Invalid option"
				} );
			}
		} );
		

		if ( errors.length > 0 ) {
			
			if ( this.notificationMethod == "alert" ) {
				
				var eList = new StringBuffer("Please correct the following errors:\n\n");
				
				for ( var i = 0; i < errors.length; i++ ) {
					eList.append( getLabel(errors[i].field) ).append(": ").append(errors[i].message).append("\n");
				}

				alert( eList.toString() );

			} else if ( this.notificationMethod == "inline" ) {

				// remove previous error messages if any exist
				$(".ValidationErrorMessage", this.container).remove();
				$(".FailedValidation", this.container).removeClass("FailedValidation");
				
				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 ( this.notificationPosition == "before" ) { field.before(message); }
					else if ( this.notificationPosition == "after" ) { field.after(message); }

				}
				
			}
			
			return false;
			
		} else {
		
			return true;
			
		}

	}
	
};


jQuery( function() {
								 
	$(document).bind("submit", function(e) {
		if ( NMO.Validator.isValid( $(e.target).closest("form.Validated") || false ) ) {
			return true;
		} else {
			e.preventDefault();
			return false;
		}
	});

} );

