/*
	Ajaxqueue module
	Singleton module, not to be instantiated manually

	When several AJAX requests are submitted at the same time, an error may occur which causes the current session to be lost
	It is therefore a best practice to AjaxQueue.Push() instead of new Ajax.Request() when sending requests on page load.
	When the requests are user-submitted, however, such collisions are not likely to occur.

	AjaxQueue.Push is a wrapper for new Ajax.Request() - it accepts the same parameters, and is invoked in the same manner
	Its function is to stack incomming AJAX requests into a queue, where the second one isn't processed until the first is complete.

	Note that Push is a function, and not a class, and hence doesn't need the "new" keyword, that Ajax.Request does.

	viz.
	AjaxQueue.Push('/ajax/', { parameters: { Method: 'TestQueue', onSuccess: function(transport) { alert(transport.responseText); } } } );
*/

Ajaxqueue = Class.create();
Ajaxqueue.prototype =
{
	initialize: function()
	{
		this.Queue = [];
		this.Processing = false;

		Event.observe(window, 'load', this.Process.bind(this));
	},

	Push: function(url, opts)
	{
		this.Queue.push({ Url: url, Options: opts });

		if(!this.Processing)
			this.Process();
	},

	Process: function()
	{
		if(this.Queue.length > 0)
		{
			this.Processing = true;

			var item = this.Queue[0];
			this.Queue = this.Queue.without(this.Queue[0]);

			item.Options.Callback = item.Options.onSuccess;
			item.Options.onSuccess = function (transport) {
				this.Processing = false;
				this.Process();

				if(typeof item.Options.Callback == 'function')
					item.Options.Callback(transport);
			}.bind(this);

			new Ajax.Request(item.Url, item.Options);
		}
	}
}

var AjaxQueue = new Ajaxqueue();