var FormRequest = new Class(
{
    /*
		options:
		--------
		* url [required]: the url of the request
		* buttonId [required]: the id of the button element
		* sendSetting: the way to send the request, values:
			- now: send the request right away
			- event: send the request with automatic generated button event (default)
			- manual: send the request manual with the send() function
		* onClick: callback function when button is clicked
		* onRequest: callback function called when request started
		* onSuccess: callback function called when request completes successfully
		* onFailure: callback function called when request failed
	*/
	
	initialize: function(formId, opts)
    {
		// validate and set data
		if(!$(formId) || !opts.url || !opts.buttonId) return false;
		var root = this;
		this.data = 
		{
			url: opts.url,
			formId: formId,
			buttonId: opts.buttonId,
			sendSetting: opts.sendSetting ? opts.sendSetting : 'event',
			onClick: opts.onClick ? opts.onClick : null,
			onRequest: opts.onRequest ? opts.onRequest : null,
			onSuccess: opts.onSuccess ? opts.onSuccess : null,
			onFailure: opts.onFailure ? opts.onFailure : null
		};
		
		// attach request
		$(formId).set('send', 
		{
			url: this.data.url,
			method: 'post',
			onRequest: function()
			{
				if(root.data.onRequest)
				{
					var func = root.data.onRequest;
					func();
				}
			},
			onSuccess: function(response)
			{
				if(root.data.onSuccess)
				{
					var func = root.data.onSuccess;
					func(response);
				}
				$(root.data.buttonId).disabled = false;
				return true;
			},
			onFailure: function()
			{
				if(root.data.onFailure)
				{
					var func = root.data.onFailure;
					func();
				}
				else
				{
					alert('Oops, could not complete your request!');	
				}
				$(root.data.buttonId).disabled = false;
				return false;
			}
		});
		
		// check send setting
		switch(this.data.sendSetting)
		{
			case "now" :
				// send request
				this.send();
				break;
			
			case "manual" :
				// do nothing, wait for user to call the send() function
				break;
			
			default:
				// add click event
				$(opts.buttonId).addEvent('click', function(e)
				{
					// stop submit event
					new Event(e).stop();
					
					// disable submit button
					this.disabled = true;
					
					if(root.data.onClick)
					{
						var func = root.data.onClick;
						func();
					}
					else
					{
						// send request
						$(formId).send();
					}
				});
				break;
		}
    },
	send: function()
	{
		$(this.data.formId).send();
	}
});
