/*--------------------------------------------------------------------------
 *  Extensions to the Prototype library (the idea is not to modify the Prototype library
 *    so I can replace it with a new version)
 *--------------------------------------------------------------------------*/

//========================================================================================
//                                    AJAX Timeouts
//========================================================================================

// Solving AJAX timeout problems
var AjaxTimeoutTime = 30000; //Set timeout to 30 seconds

function AjaxCallInProgress (xmlhttp) {
	switch (xmlhttp.readyState) {
		case 1: case 2: case 3:
			return true;
			break;
		// Case 4 and 0
		default:
			return false;
		break;
	}
}
function AjaxShowTimeoutMessage() {
	alert('The call to the server has timed out. You may have a connection problem. Please ensure you are still connected and try again.');
}
// Register global responders that will occur on all AJAX requests
Ajax.Responders.register({
	onCreate: function(request) {
		request['timeoutId'] = window.setTimeout(
			function() {
			// If we have hit the timeout and the AJAX request is active, abort it and let the user know
				if (AjaxCallInProgress(request.transport)) {
					request.transport.abort();
					AjaxShowTimeoutMessage();
					// Run the onFailure method if we set one up when creating the AJAX object
					if (request.options['onFailure']) {
						request.options['onFailure'](request.transport, request.json);
					}
				}
			},
			AjaxTimeoutTime
		);
	},
	onComplete: function(request) {
		// Clear the timeout, the request completed ok
		window.clearTimeout(request['timeoutId']);
	}
});
