/*=============================================================================

			 	 TITLE:		NetMediaOne - Simple Form Validation
		  MODIFIED:		2009.11.29
		 AUTHOR(S): 	Graham Wheeler - NetMediaOne - www.netmediaone.com
		  REQUIRES:		NetMediaOne Core 1.2
									jQuery 1.3

=============================================================================*/

NMO.I18N.EN.TEST = "TEST_XXX_000_XXX";
NMO.I18N.EN.STR_EMAIL_INVALID_FORMAT = "Email address not in valid format";
NMO.I18N.EN.STR_NUMBER_INVALID_FORMAT = "Number not in valid format";
NMO.I18N.EN.STR_NUMBER_MUST_BE_POSITIVE = "Must be a number greater than zero";
NMO.I18N.EN.STR_MUST_SELECT_A_VALUE = "Must select at least one value";
NMO.I18N.EN.STR_MUST_MATCH = "Values do not match";
NMO.I18N.EN.STR_MUST_BE_PROVIDED = "Must be provided";
NMO.I18N.EN.STR_INVALID_SELECTION = "Invalid selection";
NMO.I18N.EN.STR_PLEASE_CORRECT_FOLLOWING_ERRORS = "Please correct the following errors:\n\n";

NMO.I18N.ES.TEST = "TEST_XXX_000_XXX";
NMO.I18N.ES.STR_EMAIL_INVALID_FORMAT = "Dirección de correo electrónico no válida en el formato de";
NMO.I18N.ES.STR_NUMBER_INVALID_FORMAT = "Número no válido en el formato";
NMO.I18N.ES.STR_NUMBER_MUST_BE_POSITIVE = "Debe ser un número mayor que cero";
NMO.I18N.ES.STR_MUST_SELECT_A_VALUE = "Debe seleccionar al menos un valor";
NMO.I18N.ES.STR_MUST_MATCH = "Los valores no coinciden";
NMO.I18N.ES.STR_MUST_BE_PROVIDED = "Deben ser proporcionados";
NMO.I18N.ES.STR_INVALID_SELECTION = "Selección no válida";
NMO.I18N.ES.STR_PLEASE_CORRECT_FOLLOWING_ERRORS = "Por favor, corrija los errores de los siguientes:\n\n";

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: "STR_EMAIL_INVALID_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: "STR_EMAIL_INVALID_FORMAT" },
		{ name: "PhoneFax", pattern: /^(([0-9]{1})*[- .(]*([0-9a-zA-Z]{3})*[- .)]*[0-9a-zA-Z]{3}[- .]*[0-9a-zA-Z]{4})+$/, error: "STR_NUMBER_INVALID_FORMAT" },
		{ name: "PositiveNumber", pattern: /^[1-9]+([0-9])*$/, error: "STR_NUMBER_MUST_BE_POSITIVE" }
		
	],
	
	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: "STR_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: "STR_MUST_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: "STR_INVALID_SELECTION"
				} );
			}
		} );
		

		//
		//	Verify that at least one member in a set of checkboxes or radio buttons is selected
		//
		$("input.MustSelectOne", this.container).each( function() {
			if ( $("input[name="+this.name+"]:checked").length == 0 ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "STR_MUST_SELECT_A_VALUE"
				} );
			}
		} );
		

		//
		//	Verify that at least one member in a set of checkboxes or radio buttons is selected
		//
		$(".MustSelectOne", this.container).each( function() {
			if ( $(this).find("input:checked").length == 0 ) {
				var el = this;
				errors.push( { 
					field: el,
					message: "STR_MUST_SELECT_A_VALUE"
				} );
			}
		} );
		

		if ( errors.length > 0 ) {
			
			if ( this.notificationMethod == "alert" ) {
				
				var eList = new StringBuffer(NMO.I18N[NMO.I18n.lang].STR_PLEASE_CORRECT_FOLLOWING_ERROR);
				
				for ( var i = 0; i < errors.length; i++ ) {
					eList.append( this.getLabel(errors[i].field) ).append(": ").append(NMO.I18N[NMO.I18N.lang][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");
				$(".ValidationErrorCue", this.container).show();
				
				for ( var i = 0; i < errors.length; i++ ) {
					
					var field = $( errors[i].field );
					$(field).addClass("FailedValidation");

					var msg = '<span class="ValidationErrorMessage">'+NMO.I18N[NMO.I18N.lang][errors[i].message]+'</span>';
					if ( this.notificationPosition == "before" ) { field.before(msg); }
					else if ( this.notificationPosition == "after" ) { field.after(msg); }

				}
				
			}
			
			return false;
			
		} else {
		
			$(".ValidationErrorCue", this.container).hide();
			return true;
			
		}

	}
	
};


jQuery( function() {

	$(document).bind("click", function(e) {
		var type = $(e.target).attr("type");
		if ( type == "submit" || type == "image" ) {
			if ( NMO.Validator.isValid( $(e.target).closest("form.Validated") ) ) {
				return true;
			} else {
				e.preventDefault();
				return false;
			}
		} else {
			return;
		}
	});

} );


