/*
---
description: A class that extends Mootools Form.Request so that a json response can be handled.

authors:
- Felix Gilcher <felix.gilcher@asquera.de>

requires:
- Form.Request

provides: [Form.Request.JSON]

...
*/


/**
 * class Form.Request.JSON < Form.Request
 *
 * submits a form and retrieves a json response. See http://mootools.net/docs/more/Forms/Form.Request
**/

/**
 * new Form.Request.JSON(form, options)
 *     - form (`mixed`): A form Element or the string id of a Form Element to manage submissions
 *     - options (`Object`): _(Optional)_ options as a `key:value` pair
 * 
 *
 * ##### Options:
 * see http://mootools.net/docs/more/Forms/Form.Request
 * 
 * ##### Example:
 *     var rq = new Form.Request.JSON('myform', options);
 *     rq.send();
 * 
**/
(function(){
	
	Form.Request.JSON = new Class({
		
		Extends: Form.Request,
		
		options: {
			//onFailure: $empty,
			//onSuccess: #empty, //aliased to onComplete,
			//onSend: $empty
			requestOptions: {
				'useSpinner': true
			},
			extraData: {},
			resetForm: true
		},

		initialize: function(form, options) {
			this.element = document.id(form);
			if (this.occlude()) return this.occluded;
			
			this.setOptions(options);
			
			if(!this.options.requestOptions.spinnerTarget) {
				this.options.requestOptions.spinnerTarget = this.element;
			}
			
			this.makeRequest();
			if (this.options.resetForm) {
				this.request.addEvent('success', function(){
					$try(function(){ this.element.reset(); }.bind(this));
					if (window.OverText) OverText.update();
				}.bind(this));
			}
			this.attach();
		},
		
		makeRequest: function(){
			this.request = new Request.JSON($merge({
					emulation: false,
					method: this.element.get('method') || 'post'
			}, this.options.requestOptions)).addEvents({
				success: function(responseJSON, responseText){
					['complete', 'success'].each(function(evt){
						this.fireEvent(evt, [responseJSON, responseText]);
					}, this);
				}.bind(this),
				failure: function(xhr){
					this.fireEvent('complete').fireEvent('failure', xhr);
				}.bind(this),
				exception: function(){
					this.fireEvent('failure', xhr);
				}.bind(this)
			});
		}
	});
	
})();
