var ajaxDefaultTimeout = 10000; //10 secondi
var ajaxRequests = new Array(); //Contenitore di request ajax
var ajaxRequestsCount = 0;

var windowTimeOuts = new Array(); //Contenitore di funzioni timeout


//ESTENSIONE PER PROTOTYPE (aggiunge abort)
Ajax.Request.prototype.abort = function() {
	if (this.transport) {
		// prevent and state change callbacks from being issued
		this.transport.onreadystatechange = Prototype.emptyFunction;
		// abort the XHR
		this.transport.abort();
		// update the request counter
		Ajax.activeRequestCount--;
	}
};

//Pulitore di tutte le funzioni temporizzate appese
function clearAllTimeouts(){
	for(i=0;i<windowTimeOuts.length;i++ ){
		if (windowTimeOuts[i]) {
			clearTimeout(windowTimeOuts[i]);
		}
	}
}

//Pulitore di tutte le request ajax
function clearAllAjaxRequest(){
	for(i=0;i<ajaxRequests.length;i++ ){
		if (typeof ajaxRequests[i] == 'object' && ajaxRequests[i] != null) {
			ajaxRequests[i].abort();
		}
	}
}


// Timeout per chiamte ajax che non rispondono
Ajax.Responders.register({
	onCreate: function(request) { 
		//Su creazione memorizzo un puntatore a tutte le request ajax create
		request["idRequest"] = ajaxRequestsCount;
		ajaxRequests[ajaxRequestsCount] = request;
		ajaxRequestsCount++;
		
		//Gestione del timeout
		var ajaxTimeout = ajaxDefaultTimeout;

		if(request.options['ajaxTimeout'])
			ajaxTimeout = request.options['ajaxTimeout'];
//console.log('create ' + request.url + ' timeout ' + ajaxTimeout)
			
		request['timeoutId'] = window.setTimeout(
			function() {
				// If we have hit the timeout and the AJAX request is active, abort it and let the user know
//console.log('running...')
				var	bRunning = (request.transport.readyState == 1 ||
								request.transport.readyState == 2 ||
								request.transport.readyState == 3);
//console.log('running' + request.transport.readyState)
				if(bRunning) {
//console.log('abort ' + request.url)
					request.transport.abort();

					// 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);
					}
					if (request.options['onFailed']) {
						request.options['onFailed'](request.transport, request.json);
					}
				}
			},
			ajaxTimeout
		);
//console.log('timeoutId ' + request['timeoutId'])		
	},
	
	onComplete: function(request) {
//console.log('complete ' + request.url)

		//Rimuovi dalla lista delle requests
		ajaxRequests[request["idRequest"]] = null;
		
		// Clear the timeout, the request completed ok
		window.clearTimeout(request['timeoutId']);
	}
});

