var xmlHttp, idCampo, idCampoDest, idBox, idBox1, recEscluso, idCampo, qrystrId, v_ty;

// **** TIPO 1 *************************************************************************

function cercaProvince(idCampo, idBox, idBox1) {
    var strElementById = idCampo
    var valorecampo = document.getElementById(strElementById).options[document.getElementById(strElementById).selectedIndex].value;
    // per l'oggetto nativo XMLHttpRequest
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function () { riceviProvince(idBox, idBox1) };
        xmlHttp.open("GET", "ajx/_ajax_all.asp?ty=1&regioneId=" + valorecampo + "&idCampo=" + idCampo, true);
        xmlHttp.send(null);
        // per IE
    } else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlHttp) {
            xmlHttp.onreadystatechange = function () { riceviProvince(idBox, idBox1) };
            xmlHttp.open("GET", "ajx/_ajax_all.asp?ty=1&regioneId=" + valorecampo + "&idCampo=" + idCampo, true);
            xmlHttp.send();
        }
    }
}

function riceviProvince(idBox, idBox1) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        document.getElementById(idBox).innerHTML = xmlHttp.responseText
        document.getElementById(idBox1).innerHTML = '<select name="noSelect" id="noSelect" disabled="disabled"><option value="">Tutte le Città</option>';
    }
}


// **** TIPO 2 *************************************************************************

function cercaComuni(idCampo, idCampoDest, idBox) {
    var strElementById = idCampo
    var valorecampo = document.getElementById(strElementById).options[document.getElementById(strElementById).selectedIndex].value;
    // per l'oggetto nativo XMLHttpRequest
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function () { riceviComuni(idBox); $("#selectComuni").uniform(); };
        xmlHttp.open("GET", "ajx/_ajax_all.asp?ty=2&provinciaId=" + valorecampo + "&idCampo=" + idCampo + "&idCampoDest=" + idCampoDest, true);
        xmlHttp.send(null);
        // per IE
    } else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlHttp) {
            xmlHttp.onreadystatechange = function () { riceviComuni(idBox); $("#selectComuni").uniform(); };
            xmlHttp.open("GET", "ajx/_ajax_all.asp?ty=2&provinciaId=" + valorecampo + "&idCampo=" + idCampo + "&idCampoDest=" + idCampoDest, true);
            xmlHttp.send();
        }
    }
}

function riceviComuni(idBox) {
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
        document.getElementById(idBox).innerHTML = xmlHttp.responseText
    }
}

// **** TIPO 3 *************************************************************************

function controllaEmail(recEscluso, idCampo, idBox) {
    var valorecampo = document.getElementById(idCampo).value;
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.onreadystatechange = function () { riceviEmail(idBox) };
    xmlHttp.open("POST", "ajx/_ajax_all.asp", true);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.send("ty=3&utnId=" + recEscluso + "&utnEmail=" + valorecampo + "&idCampo=" + idCampo);
}


function riceviEmail(idBox) {
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
        document.getElementById(idBox).innerHTML = xmlHttp.responseText
    }
}


// **** FUNZIONE PER INVIO DATI DA UN FORM *************************************************************************
// rdrPageUrl: nessun valore per ricaricare la pagina visualizzata. Per caricare altra pagina specificarne il nome. (risposta 'response.write Ajax')

function InviaDati(frmName, frmBox, padTop, imgLoad) {
    var xmlHttpReq = false;
    var self = this;
    var frmAction = document.forms[frmName].action;
    // Xhr per Mozilla/Safari/Ie7
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // per tutte le altre versioni di IE
    else if (window.ActiveXObject) {

        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', frmAction, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    self.xmlHttpReq.onreadystatechange = function () {

        if (self.xmlHttpReq.readyState == 4) {
            if (self.xmlHttpReq.status == 200) {
                var msg = self.xmlHttpReq.responseText;
                var ArrMsg = msg.split("<-->");     // Creo un' array dal messaggio
                var msgSendForm = ArrMsg[0];        // L'indice 0 dovrebbe contenere 'sendFormOk' se l'invio è andato a buon fine, altrimenti contiene i messaggi di errore
                switch (msgSendForm) {
                    case 'sendFormOk': // Form inviato
                        document.getElementById(frmBox).innerHTML = "<div align='center'><img border='0' src='/ajx/ajax_loader-" + imgLoad + ".gif' align='center' style='padding-top:" + padTop + "px;'></div>";
                        setTimeout("document.getElementById('" + frmBox + "').innerHTML = '" + ArrMsg[1] + "'", 500);
                        break;
                    case 'sendFormOkRdr': // Form inviato e redirect
                        document.getElementById(frmBox).innerHTML = "<div align='center'><img border='0' src='/ajx/ajax_loader-" + imgLoad + ".gif' align='center' style='padding-top:" + padTop + "px;'></div>";
                        var rdrPageUrl = ArrMsg[1];
                        if (rdrPageUrl == '') {
                            setTimeout("window.location.reload(true);", 500);
                        }
                        else {
                            setTimeout("window.location.href = '" + rdrPageUrl + "';", 500);
                        }                         
                        break;
                    default:           // Errori
                        jAlert(msg, 'ERRORE');
                        return true;
                }
            } else {
                jAlert("C'&egrave; stato un errore. Contattare il supporto", 'ERRORE');
            }
        }
    }
    self.xmlHttpReq.send(getquerystring(frmName));
}

// **** Modifiche in pagina MyAccount Richiede Jquery *************************************************************************
function ajxEditAccount(idBox, pageName, qrystrPar, mTy, padV) {
    $("#" + idBox).html('<div align="center"><img src="/ajx/ajax_loader.gif" align="center"  vspace="' + padV + '"></div>');
    $.ajax({
        type: "POST",
        url: pageName,
        data: qrystrPar + "&ty=" + mTy,
        success: function (msg) {
            $("#" + idBox).html(msg);
            $("#" + idBox + " input, select, textarea").uniform();     
            if (mTy == 'form') {
                $("div.boxModifica,div.boxModificaFatt").css("display", "none");       
            }
            else if (mTy == 'dati') {
                $("div.boxModificaLog,div.boxModificaFatt").css("display", "block");
            }

            $("#upgradeDatiUtn input#Citta").autocomplete("my-account.asp", {
                minChars: 2,
                delay: 50,
                max: 250,
                width: 240,
                mustMatch: true,
                extraParams: { reqC: 'ON' },

                formatItem: function (data, i, n, value) {
                    var comuneCap = value.split("<-->")[1];
                    var comuneNome = value.split("<-->")[2];
                    return comuneCap + " - " + comuneNome;
                },
                formatResult: function (data, value) {
                    var comuneCap = value.split("<-->")[1];
                    var comuneNome = value.split("<-->")[2];
                    //return comuneNome;  --> solo comune (prov)
                    return comuneCap + " - " + comuneNome;
                }
            })
            $('input#Citta').result(function (event, item) {
                if (item) {
                    $("#upgradeDatiUtn #comuneId").remove();
                    var hiddenVal = item[0].split('<-->')[0];
                    $("<input type='hidden' id='comuneId' name='comuneId' value='" + hiddenVal + "' />").appendTo("#upgradeDatiUtn");
                }
            });

        }
    });
}

function getquerystring(frmName) {
    var form = document.forms[frmName];
    var qstr = "";
    function GetElemValue(name, value) {
        qstr += (qstr.length > 0 ? "&" : "")
            + escape(name).replace(/\+/g, "%2B") + "="
            + escape(value ? value : "").replace(/\+/g, "%2B");
        //+ escape(value ? value : "").replace(/\n/g, "%0D");
    }
    var elemArray = form.elements;
    for (var i = 0; i < elemArray.length; i++) {
        var element = elemArray[i];
        var elemType = element.type.toUpperCase();
        var elemName = element.name;
        if (elemName) {
            if (elemType == "TEXT"
                    || elemType == "TEXTAREA"
                    || elemType == "PASSWORD"
					|| elemType == "BUTTON"
					|| elemType == "RESET"
					|| elemType == "SUBMIT"
					|| elemType == "FILE"
					|| elemType == "IMAGE"
                    || elemType == "HIDDEN")
                GetElemValue(elemName, element.value);
            else if (elemType == "CHECKBOX" && element.checked)
                GetElemValue(elemName, element.value ? element.value : "On");
            else if (elemType == "RADIO" && element.checked)
                GetElemValue(elemName, element.value);
            else if (elemType.indexOf("SELECT") != -1)
                for (var j = 0; j < element.options.length; j++) {
                    var option = element.options[j];
                    if (option.selected)
                        GetElemValue(elemName,
                            option.value ? option.value : '');
                }
        }
    }
    return qstr;
}

// **** Richiede Jquery *************************************************************************
function ajxShowContent(idBox, pageName, qrystrPar, padV) {
    $("#" + idBox).html('<div align="center"><img src="/ajx/ajax_loader.gif" align="center"  vspace="' + padV + '"></div>');
    $.ajax({
        type: "POST",
        url: pageName,
        data: qrystrPar,
        success: function (msg) {
            // $("#" + div_id).hide().fadeIn(600).html(msg); // con Fader
            $("#" + idBox).html(msg);
        }
    });
}


function ajxRContent(idBox, rdrPageUrl, padV) {
    $('#' + idBox).html('<div align="center"><img border="0" src="/ajx/ajax_loader.gif" align="center" vspace="' + padV + '" />');
    setTimeout("window.location.href = '" + rdrPageUrl + "';", 500);
    //$('#' + idBox).load("xxxxx.asp"); // --> caricamento pagina esterna co ajax 
}

function ajxCheckCookie(pageName, qrystrPar) {
    $.ajax({
        type: "POST",
        url: pageName,
        data: qrystrPar
    });
}
