﻿//Funzione per richiamare le pagine usando AJAX
function AJAX(page, formmethod, theform, spanname) {
    var spanmsg = document.getElementById(spanname);
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
            {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("Il tuo browser non supporta AJAX!");
                return false;
            }
        }
    }
    
    xmlHttp.onreadystatechange=function() {
        if(xmlHttp.readyState==4) {
            if (spanmsg) {
                spanmsg.innerHTML = xmlHttp.responseText;
            }    
        }
   }
        
    //Se passo un form creo una stringa con tutte le coppie nomecampo-valore di tutti i campi presenti
    var strValues = "";
    var pass = false;
    if (theform) {
        for (i=0; i<theform.elements.length; i++){
            pass = false;
            strValue = theform.elements[i].value;
            //Se ho un checkbox o un radio passo solo i valori selezionati            
            if (theform.elements[i].type == "checkbox" || theform.elements[i].type == "radio") {
                if (theform.elements[i].checked) {                    
                    pass = true;
                } else {
                    pass = false;
                }
            } else {
                pass = true;
            }
            
            if (pass) {
                if (i > 0) strValues += "&";
                strValues += theform.elements[i].name + '=' + encodeURI(strValue);
            }
        }
    }

    //Aggiungo uno parametro finto alla pagina per ovviare al problema di caching
    if (page.indexOf("?") == -1) {
        page += "?pseudoParam=" + new Date().getTime();
    } else {
        page += "&pseudoParam=" + new Date().getTime();
    }

    xmlHttp.open(formmethod,page,false);
    if (formmethod == "POST") {       
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    } else if (formmethod == "GET") {
        strValues = null;
    }
    xmlHttp.send(strValues);
}