if (typeof Driebit == 'undefined') Driebit = {}

Driebit.ajaxForm = new Class({
	_class_success: 'ajax_success',
	_class_loading: 'ajax_loading',
	
	initialize: function(container, options) {
		if (typeof options == 'undefined') {
			options = {};
		}
		this._options = options;
		
		if (!$chk(container)) {
			return false;
		}
		
		this._container = container;
		if (this._container.get('tag') == 'form') {
			this._form = this._container;
		}
		else {
			forms = this._container.getChildren('form');
			if ($chk(forms) && forms.length) {
				this._form = forms[0];
			}
		}
		this._form.addEvent('submit', this.submitForm.bind(this));
		
		if (this._options.method != 'HTML' && this._options.method != 'JSON') {
			throw new Error('The method option needs to be "HTML" or "JSON"');
		}
		
		this._request_options = {
			url: this._form.get('action'),
			method: this._form.get('method')
		};

		if (this._options.method == 'JSON') {
			this._request_options.onSuccess = (this._options.callback == undefined ? this.onSuccessJSON.bind(this) : this._options.callback);
		}
		else if (this._options.method == 'HTML') {
			this._request_options.onSuccess = (this._options.callback == undefined ? this.onSuccessHTML.bind(this) : this._options.callback);
		}
	},
	
	submitForm: function(e) {
		if (typeof e != 'undefined') {
			e.stop();
		}
		this.setStatus(this._class_loading);
		if (this._options.method == 'JSON') {
			this._request = new Request.JSON(this._request_options);
			
		}
		else if (this._options.method == 'HTML') {
			this._request = new Request.HTML(this._request_options);
		}
		this._request.send({ data: this._form.toQueryString() });
	},
	
	setStatus: function(status_class) {
		var submit_buttons = this._form.getElements('input[type=submit], button[type=submit]');
		$$(submit_buttons).set('disabled', false);
		this._container.removeClass(this._class_success);
		this._container.removeClass(this._class_loading);
		this._container.addClass(status_class);
		if (status_class == this._class_loading) {
			$$(submit_buttons).set('disabled', true);
		}
	},
	
	onSuccessJSON: function(responseJSON, responseText) {
		this.setStatus(this._class_success);
		if (!responseJSON.ok && responseJSON.message.length) {
			throw new Error(responseJSON.message);
		}
	},
	
	onSuccessHTML: function(responseTree, responseElements, responseHTML, responseJavaScript) {
		this.setStatus(this._class_success);
		if (responseElements.length) {
			var new_container = responseElements[0];
			new_container.replaces(this._container);
			//heeft dit zin?
			//document.fireEvent('ajaxdomready');
		}
	}
});

document.addEvent('domready', function() {
	$$('.ajax_json').each(function(element) {
		new Driebit.ajaxForm(element, { method: 'JSON' });
	});
	$$('.ajax_html').each(function(element) {
		new Driebit.ajaxForm(element, { method: 'HTML' });
	});
});

