var AjaxFormValidator = Class.create();

AjaxFormValidator.prototype = {
	form: '',
	url: '',
	additionalParams: '',
	inlineElem: '',
	errorDisplay: 'alert',
	errors: '',
	callback: null,
	update: false,

	initialize: function(form,url,additionalParams) {
		this.form = $(form);
		this.url = url;
	},

	validate: function(additionalparams) {
		if(!additionalparams) additionalparams = '';
		var params = Form.serialize(this.form) + additionalparams;
		var myAjax = null;
		if(!this.update) {
			myAjax = new Ajax.Request(this.url,{method:'post', parameters: params, onSuccess: this.processForm.bind(this)});
		}
		else {
			myAjax = new Ajax.Updater(this.update,this.url,{method:'post', parameters: params, onSuccess: this.processForm.bind(this)});
		}
		return false;
	},

	processForm: function(req) {
		var response = eval("(" + req.responseText + ")");
		this.errors = response.errors;

		if(typeof response.callback == 'function') {
			response.callback();
		}

		if(!this.errors) {
			//this.form.submit();
		} else {
			switch(this.errorDisplay) {
				case 'none':
					break
				case 'inline':
					this.showErrorsInline(this.errors);
					break
				default:
					this.showErrorsAlert(this.errors);
			}
			if(this.callback) {
				this.callback();
			}
		}
	},

	showErrorsAlert: function(errors) {
		var errorString = '';
		errors.each(function(error){
			errorString += error + '\n';
		});
		alert(errorString);
	},

	showErrorsInline: function(errors) {
		var html = '<ul>';
		errors.each(function(error){
			html += '<li>' + error + '</li>';
		});
		html += '</ul>';
		$(this.inlineElem).innerHTML = html;
		$(this.inlineElem).show();
	}
}
