//only works with jQ.ajax
//ajaxQueue stores an array of queued ajax request data for jQ.ajax
//and the number of active requests.
var ajaxQueue = function(options) {
	this.queue = [];
	this.pending = 0;
	this.max_requests = 2;
	jQ.extend(true, this, options);
}
//add method adds a request to the queue
ajaxQueue.prototype.add = function(req) {
	cb.console('ajaxQueue.add: '+req.type+' to '+req.url);
	var data = {};
	var callback = {error: null, success: null}; //scope callback variables for below
	for (var i in req) { //loop through request data
		if (i == 'success' || i == 'error') { //store callbacks
			callback[i] = req[i];
		} else if (i == 'jsonp') { //jsonp never completely implemented
			data.jsonp = req[i];
		} else {
			data[i] = req[i];
		}
	}
	
	var aQ = this;
	
	data.success = function(data) { //overwrite success callback with needed functionality for ajaxQueue
		aQ.pending--;
		cb.console('ajaxQueue: success - '+aQ.queue.length+' Queued Requests and '+aQ.pending+' Pending');
		if (aQ.queue.length > 0) {
			jQ.ajax(aQ.queue[0]); //start next request in queue if there is one
			cb.console('Start Queued Request L1 in success callback');
			aQ.queue.shift();
			aQ.pending++;
			if (aQ.queue.length > 0 && aQ.pending == aQ.max_requests - 1) {
				cb.console('Start Queued Request L2 in success callback');
				jQ.ajax(queue[0]);
				aQ.queue.shift();
				aQ.pending++;
			}
		}
		if (callback.success) callback.success(data); //call request's success callback if there is one
	}
	data.error = function(XMLHttpRequest, textStatus, errorThrown) { //overwrite error callback with needed functionality for ajaxQueue
		cb.console('ajaxQueue: error '+textStatus);
		aQ.pending--;
		if (aQ.queue.length > 0) {
			jQ.ajax(aQ.queue[0]); //start next request in queue if there is one
			cb.console('Start Queued Request L1 in error callback');
			aQ.queue.shift();
			aQ.pending++;
			if (aQ.queue.length > 0 && aQ.pending == aQ.max_requests - 1) {
				cb.console('Start Queued Request L2 in error callback');
				jQ.ajax(queue[0]);
				aQ.queue.shift();
				aQ.pending++;
			}
		}
		if (callback.error) callback.error(XMLHttpRequest, textStatus, errorThrown); //call request's error callback if there is one
	}
	
	this.queue.push(data); //add new request to queue

	if (this.pending <= this.max_requests) { //start request if there are less than 2 active
		jQ.ajax(data);
		this.queue.shift();
		this.pending++;
	}
}
