// This file will send out requests to the server and pass the results to callback functions
// Calls can be synchronous or asynchronous.

var AJAX_SYNC = 0;
var AJAX_ASYNC = 1;

var ajaxCallCache = {};
var ajaxCallback = {};
var ajaxCallId = 0;						// Call id, unique for every request

var ajaxCurrentCallIndex = 0;			// Current call
var ajaxCallsInProgress = 0;
var ajaxInProgress = false;


// This will cache a request as asynchronous and attempt to make a server call
function postSynchronous(options, callback) {
	options['callType'] = AJAX_SYNC;
	ajaxCacheRequest(options, callback);
}

function postAsynchronous(options, callback) {
	options['callType'] = AJAX_ASYNC;
	ajaxCacheRequest(options, callback);
}

function ajaxCacheRequest(options, callback) {
	options.callId = ajaxCallId;
	ajaxCallCache[ajaxCallId] = options;
	ajaxCallback[ajaxCallId] = callback;
	ajaxCallId++;
	ajaxCallServer();
}

function ajaxCallServer() {
	if (ajaxInProgress) {
		// check if the call in progress is asynchronous, if yes, it's safe to make another call
		if (ajaxCallCache[ajaxCurrentCallIndex].callType == AJAX_SYNC) {
			return;
	 	}
	}

	// Make the call with the appropriate options
	ajaxInProgress = true;
	ajaxCallsInProgress++;
	$.post(ajaxFile, ajaxCallCache[ajaxCurrentCallIndex], function(data, ts, xmlhr) {
   	ajaxCallCleanup(data, ts, xmlhr);
   }, "json");
}

function ajaxCallCleanup(data, ts, xmlhr) {
	var callId = data.callId;
	var error = ajaxError(data);
	// Get the appropriate callback function and execute it
	callback = ajaxCallback[ callId ];

	if (error == true) data = false;
	callback(data, ts, xmlhr);
	ajaxCallsInProgress--;
	
	ajaxInProgress = false;
	// If there are more items in the cache, make calls
	var cleanCache = true;
	ajaxCurrentCallIndex++;
	do {
		if (typeof ajaxCallCache[ajaxCurrentCallIndex] != "undefined") {
			// There is another call waiting in the queue
			ajaxCallServer();
			cleanCache = false;
			if (ajaxCallCache[ajaxCurrentCallIndex].callType == AJAX_SYNC) return;
		} else break;
		ajaxCurrentCallIndex++;
	} while (true);
	
	// Otherwise clean up the cache
	if (ajaxCallsInProgress == 0) {
		ajaxCallCache = {};
		ajaxCallback = {};
		ajaxCallId = 0;
		ajaxCurrentCallIndex = 0;
	}
}

function ajaxError(data) {
	if (typeof data.errorId == "undefined") return false;
	// If error was detected display a message
	alert(data.errorMsg);
	// Any additional info about the call can be retreived from the cache using data.callId

	return true; 
}

