var VostokTheme = {};

VostokTheme.validator = {
	errorMessages : {
		requiredField : "this field can not be left blank",
		emailField : "this is not a valid e-mail address"
	},
	emailFields : null,
	requiredFiedls : null,
	form : null,
	initialize : function(formId){
		this.form = $(formId);
		if(!this.form){
			return false;
		}
		this.populateFields();
		this.form.observe('submit', this.handleSubmit.bindAsEventListener(this));
	},
	populateFields : function(){
		this.requiredFields = this.form.select('input.required');
		this.requiredFields.push(this.form.select('textarea').first()); //only one area expected
		this.emailFields = this.form.select('input.email'); //same for email... but who knows
	},
	handleSubmit : function(e){
		e.stop();
		this._resetCurrentErrors();
		var that = this;
		var errors = [];
		this.requiredFields.each(function(node){
			if(node.getValue().blank()){
				that._showError(node, that.errorMessages.requiredField);
				errors.push(true);
			}
		});
		this.emailFields.each(function(node){
			if(node.getValue().blank()){
				return true;
			}else{
				if(!node.getValue().match("^([_a-zA-Z0-9-+]+)(\\.[_a-zA-Z0-9-+]+)*@([a-zA-Z0-9-]+)(\\.[a-zA-Z0-9-]+)*(\\.[a-zA-Z]{2,4})$")){
						that._showError(node, that.errorMessages.emailField);
						errors.push(true);
				}
			}
		});
				
		if(errors.length > 0){
			return false;
		}else{
			this.form.submit();
		}
		
	},
	_resetCurrentErrors : function(){
		var errors = $$('p.error');
		errors.invoke('remove');
	},
	_showError : function(field, msg){
		var pError = new Element('p',{className : "error"});
		pError.update(msg);
		field.insert({before:pError});
	}
};
document.observe('dom:loaded',function(){
	//class="required" for required fields
	//class="email" for e-mail address fields	
	VostokTheme.validator.initialize('comment-form');
});