var ajaxForm = new Class({
	Implements: [Options, Events],

	options: {

	},

	initialize: function(form,options) {
		this.setOptions(options);
		this.form = $(form);
		this.enabled = true;
		this.inputs = this.form.getElements('input');
		if (options != null && options.trigger != null) {
			this.trigger = $(this.options.trigger);
		} else {
			this.inputs.each(function(inp) {
				if (inp.get('type') == 'submit')
					this.trigger = inp;
			}.bind(this));
		}
		if (options != null && options.onSubmit != null)
			this.onSubmitCallback = options.onSubmit;
		this.alert = new ajaxAlert();
		this.textareas = this.form.getElements('textarea');
		this.all = $$(this.inputs,this.textareas);
		this.form.set('send', {
			onRequest: function(){
				this.enabled = false;
				this.form.getElements('.actionRequest').each(function(elem){
				elem.toggleClass('disabled');
				});
				this.all.each(function(elem){
				elem.set('disabled',true);
				});
			}.bind(this),
			
			onComplete: function(response){
				// Make a js alert component, right now I alert the damn response :D
				this.enabled = true;
				success = 0;
				if (response != null) {
					parsedMessage = JSON.decode(response);
					if (parsedMessage)
						success = ['result'];
				}
				if (success && options != null && options.onSuccess != null) {
					options.onSuccess();
				} else if (!success && options != null && options.onFailure != null) {
					options.onFailure();
				}
				if (response)
					this.alert.flash(response);
				this.all.each(function(elem){
					if (elem.get('type') != 'submit')
						elem.set('value', '');
						elem.set('disabled', false);
				});
				// Clean inputs and re-enable the button
				this.form.getElements('.actionRequest').each(function(elem){
					elem.removeClass('disabled');
				});
			}.bind(this)
		});
		this.trigger.addEvent('click', function(event){
			event.stop();
			if (this.enabled)
				this.send();
		}.bind(this));
	},

	send: function(){
		if (this.onSubmitCallback != null)
			this.onSubmitCallback();
		this.form.send();
	}
});

