window.addEvent('domready', function(){

	$$('form').each( function(el){
		new FormValidator(el);
	});

});

var FormValidator = new Class({

	options: {
		hideClass: 'hideme',
		validateSelector: '.validate',
		presenceClass: 'presence',
		checkedClass: 'checked',
		phoneClass: 'phone',
		requiredClass: 'required',
		errorSelector: '.validate_errors'
	},
	
	initialize: function(el){
		this.form = el;
		this.form.addEvent('submit', this.checkValidation.bindWithEvent(this));
	},

	checkValidation: function(e){
		this.errors = false;
		this.errorMsgs = '';
		$$('.' + this.options.requiredClass).each(this.clearReds.bind(this));

		// find all labels in the form that need to have valid inputs
		this.form.getElements(this.options.validateSelector).each( this.runTests.bind(this));

		if (this.errors) {
			e.stop();
			alert('The following errors were found:' + this.errorMsgs);
		} else {
			return true;
		}

	},

	clearReds: function(el){
		el.removeClass(this.options.requiredClass);
	},

	runTests: function(el){
	
		// el is the label with the validate class

		var name = el.get('text').replace(/\*/, '').trim().capitalize();
		var input = $(el.get('for'));
		var value = input.get('value');

			if (el.hasClass(this.options.presenceClass)) {
				if (value == '' || value == null) {
					this.errors = true;
					this.errorMsgs += '\n\n' + name + ' must not be empty.';
					input.addClass(this.options.requiredClass);
				}
			}

			if (el.hasClass(this.options.checkedClass)) {
				if (value == '' || value == null) {
					this.errors = true;
					this.errorMsgs += '\n\n' + name + ' must be checked.';
					input.addClass('required');
				}
			}

			if (el.hasClass(this.options.phoneClass)) {
				if (value == '' || value == null) {
					this.errors = true;
					this.errorMsgs += '\n\n' + name + ' must be a valid phone number.';
					input.addClass('required');
				}
			}

	}

});
