// Set up our RCMS namespace
if(typeof(RCMS)=="undefined"){RCMS={};}

/* Form Validator Behavior
-----------------------------------------------------*/
RCMS.Validator = Behavior.create({

	form : null,
	errors : "",
	highlightColor : '#cf0000',
	
	regEmail : new RegExp(/^\w(?:\w|-|\.(?!\.|@))*@\w(?:\w|-|\.(?!\.))*\.\w{2,3}/),
	regURL : new RegExp(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i),
	regNumber : new RegExp(!/^\s+$/),
	regAlpha : new RegExp(/^[a-zA-Z]+$/),
	regAlphaNumeric : new RegExp(!/\W/),
	regCurrency : new RegExp(/^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/),
	
	initialize: function(options) {
		
		this.form = this.element;
		
		// Initialize our options
		if(options != null && typeof(options) != 'undefined') {
			if(typeof(options.highlightColor) != "undefined") {
				this.highlightColor = options.highlightColor;
			}
		}
	},
	
	onsubmit: function(event) {
		this.validateForm();
		if(!this.isValid()) {
			Event.stop(event);
			to_alert = this.errors;
			this.errors = "";
			alert(to_alert);
		} else {
			return true;
		}
	},
	
	isValid: function() {
		if(this.errors != "") {
			return false;
		} else {
			return true;
		}
	},
	
	validateForm: function() {
		// Validate text fields
		var inputs = this.form.getInputs('text');
		if(inputs) {
			for (var i=0; i < inputs.length; i++) {
				var textField = inputs[i];
				if(textField.hasClassName("required")) {
					this.validateRequiredTextField(textField);
				}
				if(textField.hasClassName("validate_email")) {
					this.validateEmailAddress(textField);
				}
			}
		}
	},
	
	validateRequiredTextField: function(field) {
		if(field.value == "") {
			var label = this.getLabelText(field);
			this.addErrorMessage(label + ' is a required field.');
			this.highlightField(field);
		}
	},
	
	validateEmailAddress: function(field) {
		if(!this.regEmail.test(field.value)) {
			var label = this.getLabelText(field);
			this.addErrorMessage(label + ' is not a valid email address.');
			this.highlightField(field);
		}
	},
	
	getLabelText: function(field) {
		return field.previous('label').innerHTML.stripTags().strip();
	},
	
	addErrorMessage: function(msg) {
		this.errors += msg + '\n';
	},
	
	highlightField: function(field) {
		field.style.border = "3px solid " + this.highlightColor;
		return false;
	}
	
});
