/**
 * MOOForm for Mootools 1.2.1
 * @param options
 * @return MOOForm
 */

var MOOForm = new Class({

	initialize : function(options) {
		/** Start: AjaxForm attributes * */
		this.options = options;
		this.form = $(options.form) || null;
		this.log = $(options.log) || null;
		this.button = $(options.button) || null;
		this.resetFields = options.resetFields || null;
		this.onComplete = options.onComplete || null;
		/** End: AjaxForm attributes * */
		/** Start: fixed Fx for log */
		if (this.log) {
			this.log.fade("hide");
		}
		/** End: fixed Fx for log */
		if (this.button) {
			this.button.disabled = false;
		}
		this.reset();
		if (this.form) {
			this.form.addEvent('submit', this.submitForm.bind(this));
		}
	},
	submitForm : function(e) {
		if(!$defined(this.form.flag) || !this.form.flag){
			e.stop();
		}
			e.stop();
			if (this.spinner) {
				this.spinner.addClass('ajax-small-loading');
			}
			if (this.log) {
				//this.log.stop();
				this.log.addClass('ajax-small-loading')
				//this.log.hide();
				
			}
			
			if (this.button) {
				this.button.disabled = true;
			}
			var self = this;
			this.form.set('send', {
				onSuccess :self.handleOnComplete.bind(self),
				onFailure :self.onAjaxFailure.bind(self)
			});
			this.form.send();
			return false;
	},
reset : function() {
	this.resetFields.each( function(field) {
		if($(field))
			$(field).value = "";
			
	});
},
handleOnComplete : function(response) {
	if (this.button) {
		this.button.disabled = false;
	}
	var r = JSON.decode(response);
	if (this.spinner) {
		this.spinner.removeClass('ajax-small-loading');
	}
	if (r.error == true) {
		this.onAjaxFailure(response);
	} else {
		this.reset();
		if (this.button) {
			this.button.disabled = false;
		}
		if (this.log) {
			this.log.empty();
			this.log.set('html', r.msj);
			this.log.removeClass('ajax-small-loading');
			this.log.removeClass('error');
			this.log.addClass('succes');
			this.log.fade("in");
			//.highlight("#00ff00");
			
			try {
				this.log.fade.delay(5000, this.log, "out");
			} catch (e) {
			}
		}
		if (this.onComplete) {
			this.onComplete(response);
		}
	}
},
onAjaxFailure : function(response) {
	this.button.disabled = false;
	if (this.spinner) {
		this.spinner.removeClass('ajax-small-loading');
	}
	var r = JSON.decode(response);
	if (this.log) {
		this.log.empty();
		this.log.setHTML(r.msj);
		this.log.removeClass('succes');
		this.log.addClass('error')
		this.log.toggle();
		this.log.highlight("#f00", "#E6E6E6");
		this.log.toggle.delay(3500, this.log);
	}
}
});