//---------- DEFINIZIONE VARIABILI GLOBALI ----------
var MESSAGE_ERR_REQUEST_FAILED = 'Errore fatale! Impossibile completare la richiesta http.';
var MESSAGE_ERR_INVALID_RESPONSE = 'Errore nel caricamento della pagina!';
var MESSAGE_ERR_JS_NOT_SUPPORTED = 'Errore fatale! Il browser non supporta JavaScript.';
//---------- FINE DEFINIZIONE VARIABILI GLOBALI ----------

/**
 * Document::makerequest()
 *
 * ( Tenta di ottenere i dati Json dal backend php ed esegue le
 *   funzioni passate come parametri )
 * 
 * @param	string		url				l'indirizzo del backend con tutti i parametri richiesti
 * @param	string		loadingFunction	la funzione da richiamare durante il caricamento dei dati
 * @param	string		loadedFunction	la funzione da richiamare dopo il caricamento dei dati
 * @param	string		callbackFunction	la funzione da richiamare quando i dati sono disponibili
 */
function makeRequest(url, loadingFunction, loadedFunction, callbackFunction)
{
	/* La variabile che conterra' l'oggetto istanziato da ajax */
    var http_request = false;
    
    /* Se il browser non e' IE */
    if (window.XMLHttpRequest) 
    {
    	http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType)
        {
        	http_request.overrideMimeType('text/xml');
        }
	}
	/* Se invece e' IE */
	else if (window.ActiveXObject) 
	{ 
		try 
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
			try 
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {}
        }
    }
	
	/* Se non sono riuscito ad istanziare il nuovo oggetto allora termino con un alert d'errore */
	if (!http_request)
	{
		alert(MESSAGE_ERR_JS_NOT_SUPPORTED);
	}
	/* L'oggetto e' stato istanziato, passo la richiesta al backend */
	else
	{
		/* In base all'evento sollevato eseguo una determinata funzione */
	    http_request.onreadystatechange = function()
	    {
	    	
	       switch (http_request.readyState)
	       {
			   /* Caricamento dati */
			   case 1:
	           		eval(loadingFunction + '()');		
	           break;
				
			   /* Dati caricati */	
	           case 2:
	           		eval(loadedFunction + '()');
	           break;
	           
	           /* Dati pronti */
	           case 4:
	               /* Se la richiesta e' andata a buon fine eseguo la funzione di callBack */
		           if (http_request.status == 200)
		           {
		              eval(callbackFunction + '(http_request.responseText)');
		           }
		           /* Se non e' andata a buon fine mostro un messaggio d'errore */
		           else
		           {
		               alert(MESSAGE_ERR_INVALID_RESPONSE + ' ' + http_request.status);
		           }
	       		break;
			}
		}
		
		/* Invio la richiesta */ 
		http_request.open('GET', url, true);
		http_request.send(null);
	}
}
