var cns_formHelper = Class.create({
	valid: true,
	
	initialize: function () {		
		$('contactForm').observe('submit', (function (e){ this.validateForm(e); }).bind(this));
	},
		
	validateForm: function (e) {
		this.valid = true;
		var inputs = $$('.textbox').each((function (input){
			if(!input.present()){
				input.addClassName('textboxErr');
				if(input.getAttribute('name') == 'email') input.observe('keyup', (function (e){ this.emailCheck(e); }).bind(this));
				else input.observe('keyup', this.validCheck);
				input.observe('focus', this.clearField);
				input.value = "This can't be blank";
				this.valid = false;
			} else if((input.getAttribute('name') == 'email') && !this.validEmail($F(input))) {
				input.addClassName('textboxErr');
				input.observe('keyup', (function (e){ this.emailCheck(e); }).bind(this));
				input.value += ' << This is not a valid email address';
				input.observe('focus', this.clearEmailField);
				this.valid = false;
			}
		}), this);
		
		if(!this.valid) e.stop();
	},
	
	validCheck: function (e) {
		var target = e.element();
		if((target.hasClassName('textboxErr')) && (target.present())) {
			target.removeClassName('textboxErr');
		} else if(!target.present()) {
			target.addClassName('textboxErr');
		}
	},
	
	emailCheck: function (e) {
		var target = e.element();
		if((target.hasClassName('textboxErr')) && this.validEmail($F(target))) {
			target.removeClassName('textboxErr');
		} else if(!this.validEmail($F(target))) {
			target.addClassName('textboxErr');
		}
	},
	
	validEmail: function(email) {
		return (email.match(/.+@.+\..+/));
	},
		
	clearField: function(e) {
		e.element().value = '';
		e.element().stopObserving('focus', this.clearField);
	},
	
	clearEmailField: function(e) {
		var elementText = $F(e.element());
		e.element().value = elementText.substr(0, elementText.length - 37);
		e.element().stopObserving('focus', this.clearEmailField);
	}
});

document.observe('dom:loaded', function() { new cns_formHelper(); });
