/**
 * @param string targetSuccess URL of the success page
 * @param string targetFailure URL of the failure page
 * @param object fields List of field elements
 */
var mooForm = new Class({
	Implements: [Events, Options],
	options: {
		'targetSuccess': '',
		'targetFailure': '',
		'url': 'index.php',
		'data': {},
		'form': 'form',
		'msgbox': '',
		'indicator': 'formFooter',
		'wrapper': 'div',
		'method': 'post',
		'scrollTo': 0,
		'style': {
			'indicator': 'mooFormLoader',
			'error': 'mooFormError',
			'errMsg': 'mooFormMsgError'
		},
		'msg': {
			'de': {
				'validate': '<h2>Ooops<br />Scheinbar fehlen ein paar Informationen!</h2>',
				'errCode': '<h3>Es trat ein technisches Problem beim Absenden des Formulars auf.<br />Bitte versuchen Sie es später noch einmal!</h3> (Fehlercode: ',
				'success': '<h2>Formular erfolgreich übertragen!<br />Vielen Dank!</h2>'
			},
			'en': {
				'validate': '<h2>Ooops<br />Something is missing here!</h2>',
				'errCode': '<h3>A problem occured when sending your form.<br />Please come back to us.</h3> (Errorcode: ',
				'success': '<h2>Form successfuly transferred!<br />Thank you!</h2>'
			}
		},
		'lang': 'en'
	},
	_marker: [],
	initialize: function(options) {
		this.setOptions(options);
		if (this.options.msgbox == '' || this.options.msgbox == null) this.options.msgbox = this.options.form;
		this._fields = $(this.options.form).getElements('input[type=text], input[type=radio], input[type=checkbox], input[type=hidden], textarea, select');
	},
	send: function() {
		var root = this;
		var req = new Request({
			'url': root.options.url,
			'method': root.options.method,
			'data': $merge(root.getValues(), root.options.data),
			'onRequest': function() {
				$(root.options.indicator).addClass('mooFormLoader');
			},
			'onFailure': function() {
				root.showError(1);
				$(root.options.indicator).removeClass('mooFormLoader');
			},
			'onSuccess': function(res) {
				$(root.options.indicator).removeClass('mooFormLoader');
				// alert(res);
				res = JSON.decode(res);
				if (res == null)
					root.showError(2);
				else
					root.handleResult(res);
			}
		});
		try {
			req.send();
		} catch (e) {
			alert(e.message);
		}
	},
	getMessage: function(msg, lang) {
		lang = (lang == null) ? this.options.lang : lang;
		return this.options.msg[lang][msg];
	},
	getValues: function() {
		var values = new Object();
		this._fields.each(function(field, index) {
			if (field.get('name') && field.get('value')) {
				if ((field.get('type') == 'checkbox' || field.get('type') == 'radio')) {
					if (field.checked)
						values[field.get('name')] = (field.get('value') ? field.get('value') : true);
				} else
					values[field.get('name')] = field.get('value');
			}
		}, this);
		return values;
	},
	showError: function(errorcode) {
		this.showMessage(this.getMessage('errCode') + ((errorcode == null) ? '0' : errorcode) + ')');
	},
	initMessage: function(message, classname) {
		var root = this;
		this._msgbox = new Element('div', {
			'html': message,
			'class': ((classname == null) ? root.options.style.errMsg : classname) 
		});
		this._msgbox.inject($(this.options.msgbox), 'top');
	},
	showMessage: function(message, classname) {
		if (this._msgbox == null)
			this.initMessage(message, classname);
		else {
			this._msgbox.set('class', ((classname == null) ? this.options.style.errMsg : classname));
			this._msgbox.set('html', message);
		}
		var myFx = new Fx.Scroll($(document.body)).start(0, this.options.scrollTo);
	},
	highlightFields: function(fields) {
		this._fields.each(function(field, index) {
			id = field.get('name');
			wrapper = field.getParent(this.options.wrapper);
			if (wrapper != null) {
				if (fields.contains(id)) {
					if (!this._marker.contains(id)) {
						this._marker.push(id);
						wrapper.addClass(this.options.style.error);
					}
				} else {
					if (this._marker.contains(id)) {
						this._marker.erase(id);
						wrapper.removeClass(this.options.style.error);
					}
				}
			}
		}, this);
	},
	handleResult: function(res) {
		var root = this;
		// Result object: {valid: BOOL, transferred: BOOL, errors: ['field1', 'field2']}
		this.fireEvent('handle', res);
		if (res.errors != null) {
			this.highlightFields(res.errors);
		}
		
		if (res.valid) {
			if (res.transferred) {
				// Show the success page or a success message
				if (this.options.targetSuccess == null || this.options.targetSuccess == '')
					this.showMessage(this.getMessage('success'), 'mooFormMsgSuccess');
				else
					window.location=this.options.targetSuccess;
			} else {
				// Form data could not be transferred
				if (this.options.targetFailure == null || this.options.targetFailure == '')
					this.showError(3);
				else
					window.location=this.options.targetFailure;
			}
		} else {
			if (res.errors != null || res.error != null) {
				this.showMessage(this.getMessage('validate'));
			}
		}
	}
});
