var AjaxFormValidator = Class.create();

AjaxFormValidator.prototype = {
	form: '',
	url: '',
	additionalParams: '',
	inlineElem: '',
	errorDisplay: 'alert',
	errors: '',
	callback: null,	
	submitid: '',
	refreshwindow: false,
	
	initialize: function(form,url,submitid,refreshwindow,additionalParams) {
		this.form = $(form);
		this.url = url;
		this.submitid = submitid;
		if(refreshwindow) this.refreshwindow = true;
	},

	validate: function(additionalparams) {		
		if(!additionalparams) additionalparams = '';
		document.getElementById(this.submitid).disabled = true;
		var params = Form.serialize(this.form) + additionalparams;
		var myAjax = new Ajax.Request(this.url,{method:'post', parameters: params, onSuccess: this.processForm.bind(this)});
		return false;	
	},

	processForm: function(req) {		
		var errors = eval( '(' + req.responseText + ')' );
		this.errors = errors;
		if(!errors) {	
			if(this.refreshwindow)
			{				
				window.parent.location.reload();
			}
			else
				window.location.href = this.form.action;			
		} else {
			document.getElementById(this.submitid).disabled = false;
			switch(this.errorDisplay) {
				case 'none':
					break
				case 'inline':
					this.showErrorsInline(errors);
					break
				default:
					this.showErrorsAlert(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();
	}
}