/* Minification failed. Returning unminified contents.
(397,18-19): run-time error JS1195: Expected expression: >
(397,30-31): run-time error JS1004: Expected ';': )
(401,6-7): run-time error JS1195: Expected expression: )
(404,6-7): run-time error JS1195: Expected expression: )
(421,18-19): run-time error JS1195: Expected expression: >
(421,30-31): run-time error JS1004: Expected ';': )
(424,6-7): run-time error JS1195: Expected expression: )
(427,6-7): run-time error JS1195: Expected expression: )
(1299,40-41): run-time error JS1195: Expected expression: .
(1299,56-66): run-time error JS1197: Too many errors. The file might not be a JavaScript file: filterType
(1283,19-30): run-time error JS1301: End of file encountered before function is properly closed: function ()
(1299,66-67): run-time error JS1004: Expected ';': ]
(1299,67-68): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ]
(532,26-37): run-time error JS1301: End of file encountered before function is properly closed: function ()
(1300,17-18): run-time error JS1002: Syntax error: }
(1301,13-14): run-time error JS1197: Too many errors. The file might not be a JavaScript file: }
 */
var AltalexWKI = {};
AltalexWKI.Routes = {

	archivioNumeriConcorsi: '/aggregatori/ArchivioNumeriConcorsi/',
	archivioNumeri: '/aggregatori/ArchivioNumeri/',
	archivioNumeriPraticamente: '/aggregatori/ArchivioNumeriPraticamente/',
	archivioNumeriNewsletter: '/aggregatori/ArchivioNumeriNewsletter/',
	canalepreferito: '/aggregatori/canalepreferito/',
	canalepreferitoNew: '/aggregatori/CanalePreferitoNew/',
	profiloLogin: '/profilo/Login',
	profilosociallogin: '/profilo/sociallogin',
	sessionCheck: '/session/check',
	strumenti: "/strumenti/",
	sondaggiVote: "/sondaggi/vote/",
	apiComuni: "/api/comuni/",
	apiProvince: "/api/province/",
    formsAltalexRegistration: '/forms/altalex-registration',
    formsAltalexInserisciStudioRegistration: '/forms/altalex-inserisci-studio-registration',
	formsAltalexSend: '/forms/altalex-send',
	formsAltalexContactLawyerWithCaptcha: '/forms/altalex-contact-lawyer-with-captcha',
	modificapassword: '/profilo/modificapassword/',
	apiComuniescape: "/api/comuniescape/",
	apiProvinceescape: "/api/provinceescape/",
	TrackPageview: "/api/TrackPageview",
	TrackTagPageview: "/api/TrackTagPageview",
	GetBoxAvvocati: "/avvocati/getboxavvocati/"
	, getJoinedSocialNetworks: '/Account/GetJoinedSocialNetworks/'
	, linkedinAccessToken: '/Account/GetLinkedinAccessToken/'
	, linkedinAccessTokenCallback: '/Account/GetLinkedinAccessTokenCallback/',
	BoxAcquisti: '/Utenti/BoxAcquisti',
	BoxCorsi: '/Utenti/BoxCorsi',
	CheckMailAvvocato: '/Avvocati/CheckUtente',
    CheckMailUtente: '/Account/CheckUserEmail',
    ResendEmail: '/Account/ResendEmailToVerify',
    ResendEmailNew: '/Account/ResendEmailToVerifyNew',
	LoginAvvocato: '/Avvocati/LoginAvvocato',
	DownloadArticolo: '/strumenti/downloadpdfarticolo',
	CollaboraConNoi: '/AltalexForms/CollaboraConNoi',
	UploadFileCollaboratoreCV: '/AltalexForms/UploadFileCollaboratoreCV',
    UploadFileContributo: '/AltalexForms/UploadFileContributo',
    giuridicoaltalexCheckSearch:'/consolidati/search'
};


//var AltalexWKI = {};
//AltalexWKI.Routes = {

//    archivioNumeriConcorsi: '/aggregatori/ArchivioNumeriConcorsi',
//    archivioNumeri: '/aggregatori/ArchivioNumeri',
//    archivioNumeriPraticamente: '/aggregatori/ArchivioNumeriPraticamente',
//    archivioNumeriNewsletter: '/aggregatori/ArchivioNumeriNewsletter',
//    canalepreferito: '/aggregatori/canalepreferito',
//    profiloLogin: '/profilo/Login',
//    profilosociallogin: '/profilo/sociallogin',
//    sessionCheck: '/session/check',
//    strumenti: "/strumenti",
//    sondaggiVote: "/sondaggi/vote",
//    apiComuni: "/api/comuni",
//    apiProvince: "/api/province",
//    formsAltalexRegistration: '/forms/altalex-registration',
//    formsAltalexSend: '/forms/altalex-send',
//    formsAltalexContactLawyerWithCaptcha: '/forms/altalex-contact-lawyer-with-captcha',
//    modificamail: '/profilo/modificamail',
//    modificapassword: '/profilo/modificapassword',
//    apiComuniescape: "/api/comuniescape",
//    apiProvinceescape: "/api/provinceescape",
//    forumCommento: "/Forum/Discussione",
//    TrackPageview: "/api/TrackPageview",
//    TrackTagPageview: "/api/TrackTagPageview",
//    GetBoxAvvocati: "/avvocati/getboxavvocati"
//    , getJoinedSocialNetworks: '/Account/GetJoinedSocialNetworks'
//    , linkedinAccessToken: '/Account/GetLinkedinAccessToken'
//    , linkedinAccessTokenCallback: '/Account/GetLinkedinAccessTokenCallback',
//    BoxAcquisti: '/Utenti/BoxAcquisti',
//    BoxCorsi: '/Utenti/BoxCorsi',
//    BoxForum: '/AltalexForum/BoxForum',
//    NewDiscussionForum: '/AltalexForum/NuovaDiscussioneAjax',
//    DiscussionForum: '/AltalexForum/DiscussioneAjax',
//    CheckMailAvvocato: '/Avvocati/CheckUtente',
//    LoginAvvocato: '/Avvocati/LoginAvvocato',
//    DownloadArticolo: '/strumenti/downloadpdfarticolo'
//};

var Giuridico = {};
Giuridico.Routes = {

    giuridico: '/giuridico/',
    profiloLogin: '/profilo/Login',
    bookmarkutente: '/giuridico/bookmarkutente',
    bookmarkclearall: '/giuridico/clearallbookmark',
    bookmarknote: '/giuridico/bookmarknote/',
    consolidatoutente: '/giuridico/consolidatoutente',
    documenticonsolidatoutente: '/giuridico/docsconsolidatoutente',
    consolidatoadd: '/giuridico/addtoconsolidato',
    consolidatoclearall: '/giuridico/clearallconsolidati',
    consolidatoclear: '/giuridico/clearconsolidato/',
    checkDownload: '/giuridico/checkDownload/',
    consolidatiSearch: '/giuridico/giuridicoconsolidatisearch',
    votaDibattito: '/giuridico/vote/',
    abbonamentiutente: '/profilo/abbonamentiutente/',
    newslettersutente: '/profilo/newslettersutente/',
    agenziautente: '/profilo/agenziautente/',
    setNewsletter: '/profilo/SetNewsletter',
    modificapassword: '/profilo/modificapassword/',
    aggiungiAiPreferiti: '/profilo/bookmark/abbonamento/',
    roleGroupBookmark: '/profilo/RoleGroupBookmark',
    modificamail: '/profilo/modificamail/',
    recuperapassword: '/profilo/RemindPasswordHPpersonale/',
    profiloUtente: '/profilo/BoxProfiloUtente/',
    gazzettaNavigatoreYear: '/gazzettanavigatore/year',
    getForm: '/giuridico/getform/',
    sendForm: '/giuridico/send',
    newslettersutenteanteprima: '/profilo/AnteprimaNewsletter/',
    loadAgenzie: "/account/LoadAgenzia",
    elencoAgenzie: '/agenzie/ElencoAgenzie',
    registrazione: '/giuridico/registration',
    creaPdf: '/giuridico/print/',
    consolidatoCreaPdf: '/giuridico/printconsolidato/',
    consolidatoutentenewelement: '/giuridico/consolidatoutentenewelement',
};
;

function LoginAltalexUser(urlLogin, buttonId, usernameId, passwordId, errorId, url, checkboxId, failhandler) {
    $(buttonId).click(function (event) {
        event.preventDefault();

        var idButton = $(buttonId);
        var checkbox = $(checkboxId).is(":checked");
        if (checkbox) { param = '1'; }
        else { param = '0'; }

        if (window.location.search != "")
            url = url + window.location.search;

        var socialBind = $("#cbAssocia").is(":checked");

        $.ajax({
            type: 'POST',
            timeout: 35000,
            url: urlLogin,
            data: {
                UserName: $(usernameId).val().replace(',', '.'),
                PassWord: $(passwordId).val(),
                ReturnUrl: url,
                CheckboxValue: param,
                socialId: socialBind ? $("#socialId").val() : null,
                socialFarm: socialBind ? $("#socialFarm").val() : null
            },
            success: function (data) {
                if (data.Success) {
                    if (idButton.selector == "#mainHeadBtnLogin") {
                        window.dataLayer.push({ 'event': 'login-ok' });
                    }
                    else if (idButton.selector == "#mainHeadLoginPopUpBtnLogin") {
                        window.dataLayer.push({ 'event': 'login-popup-ok' });
                    }
                    if (data.DoRedirect) {
                        showLoading();
                        window.location.href = data.ReturnUrl;
                    }
                    else {
                        $(errorId).html(data.Message).show();
                        //if (failhandler && (typeof failhandler == "function"))
                        //    failhandler();
                    }
                }
                else {
                    window.dataLayer.push({ 'event': 'login-error' });
                    if (data.DoRedirect) {
                        showLoading();
                        window.location.href = data.ReturnUrl;
                    }
                    else {
                        $(errorId).html(data.Message).show();
                        //if (failhandler && (typeof failhandler == "function"))
                        //    failhandler();
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                $(errorId).html(textStatus).show();
                //if (failhandler && (typeof failhandler == "function"))
                //    failhandler();
            }
        });
    });
}

function ShowLoginAlertConsolidato() {
    $('#consolidatoHiddenButton').click();
}

function ShowLoginAlert() {
    documentoPopup(
        $("#loginPopUp"), true, 'modalPopup__close', function () {
            $("#loginPopUp .welcome p").html('Registrati od effettua la login per salvare il tuo canale preferito.');
        });
}

function JSONPost2(url, jsonData, functionSuccess, functionFail) {
    var json = JSON.stringify(jsonData);
    $.ajax(
        {
            url: url,
            type: 'POST',
            dataType: 'json',
            data: json,
            contentType: 'application/json; charset=utf-8',
            cache: false,
            headers: { "cache-control": "no-cache" }
        })
        .success(functionSuccess)
        .error(functionFail);
}

function JsonPost2LoadingBox(url, jsonData, boxid) {
    JSONPost2(url, jsonData,
        function (result) {
            appendLoadedContent(boxid, result);
        },
        function (xhr, status) {
            appendLoadedContent(boxid, xhr.responseText);
        });
}

function HTMLPost(url, jsonData, functionSuccess, functionFail) {
    $.ajax(
        {
            url: url,
            type: 'POST',
            //DO NOT SET FOR HTML RESULTS dataType: 'json',
            data: JSON.stringify(jsonData),
            contentType: 'application/json; charset=utf-8',
            cache: false,
            headers: { "cache-control": "no-cache" }
        })
        .success(functionSuccess)
        .error(functionFail);
}

function JSONPost(url, jsonData, functionName) {
    var json = JSON.stringify(jsonData);
    $.ajax(
        {
            url: url,
            type: 'POST',
            dataType: 'json',
            data: json,
            contentType: 'application/json; charset=utf-8',
            cache: false,
            headers: { "cache-control": "no-cache" }
        })
        .success(functionName)
        .error(function (xhr, status) {
            alert(xhr.responseText);
        });
}

function appendLoadedContent(container, html) {
    $(container).children('.loading-box').remove();
    if ((html == null) || (html == 'undefined'))
        $(container).hide();
    else
        $(container).append(html);
}

var loadingSpinnerEl;
function showLoading() {
    var loadingSpinnerEl = document.querySelector('.loadingSpinner');

    if (loadingSpinnerEl && !loadingSpinnerEl.classList.contains('loadingSpinner--visible')) {
        loadingSpinnerEl.classList.add('loadingSpinner--visible');
    }
}

function hideLoading() {
    var loadingSpinnerEl = document.querySelector('.loadingSpinner');
    if (loadingSpinnerEl && loadingSpinnerEl.classList.contains('loadingSpinner--visible')) {
        loadingSpinnerEl.classList.remove('loadingSpinner--visible');
    }
}

function SessionRemoteCheck() {
    $.ajax(
        {
            url: AltalexWKI.Routes.sessionCheck,
            type: 'GET',
            cache: false,
            headers: { "cache-control": "no-cache" },
            success: function (data) {
                if (data.HasToRefresh) {
                    window.location.href = window.location.pathname;//data.ReturnUrl;
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
            }
        });
}


function documentoPopupPraticamente(idPop) {
    var idCnt = 'pop-' + idPop;
    if ($('#' + idCnt).length < 1) {
        $('body').append('<div id="' + idCnt + '" class="popup_praticamente"><span class="b-close"><span> <i class="fa fa-times"></i> </span></span></div>');
        $('#' + idCnt).append('<div class="contenuto-popup"></div>');
        $('#' + idCnt + ' .contenuto-popup').html($('#' + idPop).clone());
    }
    var targetCnt = $('#' + idCnt);
    documentoPopup(targetCnt);
}

function addRequiredExpressionMethod() {
    var getOperandValue = function (op) {
        if (op.indexOf("$") == 0) {
            var id = op.substring(1);
            return $("#" + id).selectric().val();
        }
        else
            return op;
    };

    $.validator.addMethod("requiredExpression", function (value, element, params) {
        var tokens = params.split(' ');
        var a = getOperandValue(tokens[0]);
        var operator = tokens[1];
        var b = getOperandValue(tokens[2]);

        var passed = false;
        switch (operator) {
            case "EQ":
                passed = a == b;
        }

        if (passed)
            return value != '-';
        else
            return true;
    });
}

//------------------- LISTING AVVOCATO -------------------

function manageSelectElementListingAvvocato() {

    var $select = $('select');

    $select.each(function () {
        var selects = $(this);

        selects.on('change', function () {

            var id = $(this).attr("id");

            $("#" + id + "-error").css('display', 'none');

        });
    });
}

function updateSelectListingAvvocato(select, data, textFirst) {
    select.innerHTML = "";
    var opt = document.createElement('option');

    opt.value = "";
    opt.innerHTML = textFirst;
    select.appendChild(opt);

    for (var i = 0; i <= data.length - 1; i++) {
        var opt = document.createElement('option');
        opt.value = data[i].Cod;
        opt.innerHTML = data[i].Desc;
        select.appendChild(opt);
    }
}

function changeRegion(obj, sede) {

    var provinciaObj;
    var comuneObj;

    var numeroSede = 1;
    var currentId = obj.id;

    if (sede == 1) {
        provinciaObj = document.getElementById("Province");
        comuneObj = document.getElementById("City");
    }
    else {
        provinciaObj = document.getElementById("ProvinceAlt");
        comuneObj = document.getElementById("CityAlt");
    }

    fetch(AltalexWKI.Routes.apiProvince + obj.value, {
        method: 'POST',
        cache: 'no-cache'
    })
    .then((res) => res.json())
    .then((data) => {
        updateSelectListingAvvocato(provinciaObj, data, "Qualsiasi provincia");
        updateSelectListingAvvocato(comuneObj, data, "Qualsiasi comune");
    })
    .catch ((error) => {
        console.error('Error:', error);
    });
}

function changeProvince(obj, sede) {

    var numeroSede = 1;
    var currentId = obj.id;

    if (sede == 1)
        var cityObj = document.getElementById('City');
    else
        var cityObj = document.getElementById('CityAlt');

    fetch(AltalexWKI.Routes.apiComuni + obj.value, {
        method: 'POST',
        cache: 'no-cache'
    })
    .then((res) => res.json())
    .then((data) => {
        updateSelectListingAvvocato(cityObj, data, "Qualsiasi comune");
    })
    .catch((error) => {
        console.error('Error:', error);
    });
}

function addSedeAlternativaSection() {
    $('#fields-sede-alt').append($('#fields-hidden').html());
    $('#fields-hidden .field-sede-alt').remove();

    $('#HasSedeAlternativa').val(true);

    // Selectrizzo le 3 combo
    $('#fields-sede-alt').find('select').each(function () {
        var selects = $(this);

        selects.on('change', function () {

            var id = $(this).attr("id");

            $("#" + id + "-error").css('display', 'none');

        });
    }).selectric({
        disableOnMobile: false,
        maxHeight: 280,
        customClass: {
            camelCase: true
        }
    });

    $('#AddressAlt').rules("add", { required: true, messages: { required: "inserisci l\' indirizzo della sede alternativa" } });
    $('#CapAlt').rules("add", { required: true, messages: { required: "inserisci il CAP della sede alternativa" } });
    $('#CapAlt').rules("add", { number: true, messages: { number: "CAP non valido" } });
    $('#RegionAlt').rules("add", { valueNotEquals: "", messages: { valueNotEquals: "inserisci la regione della sede alternativa" } });
    $('#ProvinceAlt').rules("add", { valueNotEquals: "", messages: { valueNotEquals: "inserisci la provincia della sede alternativa" } });
    $('#CityAlt').rules("add", { valueNotEquals: "", messages: { valueNotEquals: "inserisci il comune della sede alternativa" } });
    $('#PhoneAlt').rules("add", { required: true, messages: { required: "inserisci il telefono della sede alternativa" } });
}

function removeSedeAlternativaSection() {

    $('#HasSedeAlternativa').val(false);

    $('#fields-sede-alt .field-sede-alt').each(function () {
        $('#fields-hidden').append($(this));
    });

    $('#fields-hidden').find('select').selectric('destroy');

    $('#fields-sede-alt .field-sede-alt').remove();
}

function browseFile(ph) {
    $("#" + ph).click();
}

function clearFile(ph, imgStudioDefault, imgProfiloDefault) {

    $("#" + ph).replaceWith($("#" + ph).clone());
    $("#" + ph).change(function () {
        readURL(this, ph);
    });

    if (ph == "FotoStudio") {
        $('#imgFotoStudio').css("background-image", "url('" + imgStudioDefault + "')");
        $('#FotoStudioModified').val(true);
    }
    else {
        $('#imgFoto').attr('src', imgProfiloDefault);
        $('#FotoProfiloModified').val(true);
    }
}

function readURL(input, ph) {

    var size = input.files[0].size;
    if (size > 1000000) {
        var label = $("#" + ph).parent().find('.labelTitle');
        $(label).after("<p class=\"field-validation-error\" style=\"color:red\">Dimensione massima immagini consentita 1 MB</p>");
        $("#" + ph).replaceWith($("#" + ph).clone());
        $("#" + ph).change(function () {
            readURL(this, ph);
        });
        return;
    }

    if (input.files && input.files[0] && FileReader != undefined) {
        var reader = new FileReader();
        if (ph == "FotoStudio") {
            var img = "#imgFotoStudio";
            reader.onload = function (e) {
                $(img).css('background', 'url(' + e.target.result + ') left top');
                $(img).css('background-size', '907px 400px');
            }
        }
        else {
            var img = "#imgFoto";
            reader.onload = function (e) {
                $('#imgFoto').attr('src', e.target.result);
            }
        }

        reader.readAsDataURL(input.files[0]);
    }
}

//------------------- LISTING AVVOCATO -------------------;
var ListingFilters = new function () {
    this.pager = 0;
    this.filters = {
        query: '', // Fulltextsearch
        tipo: new Set(),
        data: '',
        da: '',
        a: '',
        provvedimentoda: '',
        provvedimentoa: '',
        dataa: '',
        datada: '',
        lettera: '',
        argomento: new Set(),
        area: new Set(),
        Categoria: new Set(),
        argomentoMassimario: new Set(),
        //canale: new Set(),
        codicealtalex: new Set(),
        categoryaudio: new Set(),
        sort: '',
        cerca: '',
        autore: '',
        regione: '',
        provincia: '',
        comune: ''
    };

    this.baseUrl = document.location.pathname;

    this.init = function () {
        // Load json da aggregatore:
        var aggrBase = document.getElementById('aggrBase');
        var aggrData = document.getElementById('aggrData');

        if (!aggrData)
            return;

        var newAggrDataTxt = aggrData.value;
        if (newAggrDataTxt.length < 1) {
            return;
        }
        var newAggrData = JSON.parse(newAggrDataTxt);

        var aggrDataParamsEl = document.getElementById('aggrDataParams');
        var aggrDataParams = '';
        if (aggrDataParamsEl) {
            var aggrDataParamsTxt = aggrDataParamsEl.value;
            aggrDataParams = JSON.parse(aggrDataParamsTxt);
        }

        this.bindFilterObj();

        // Baseurl override for seo-friendly url management
        if (aggrBase && aggrBase.value) {
            this.baseUrl = aggrBase.value;
        }

        this.refreshPager();
        this.refreshLetters(newAggrData);

        this.initDates();
        this.refreshDates();

        this.initSearchList();
        this.refreshSearchList();

        this.initContentFilters("filterArguments", "argomento", "Args", newAggrData);
        this.initContentFilters("filterAree", "area", "AreaCategory", newAggrData, { disableShowMoreContentFilters: true });
        this.initContentFilters("filterRubricaCategory", "Categoria", "RubricaCategory", newAggrData);
        this.initContentFilters("filterArgumentsMax", "argomentoMassimario", "ArgsMax", newAggrData);

        //this.initContentFilters("filterChannels", "canale", "Channels", newAggrData);
        //this.refreshContentFilters("filterChannels", "canale", "Channels", newAggrDataFilter);

        this.initContentFilters("filterDocuments", "tipo", "TipoDocs", newAggrData);
        this.initContentFilters("filterCodici", "codicealtalex", "Codici", newAggrData);
        this.initContentFilters("filterAudioCategory", "categoryaudio", "CategoryAudio", newAggrData);
        this.searchShowResult();
    };

    this.bindFilterObj = function () {       
        // Init filters da url:
        var qs = document.location.search;
        if (qs.length > 1 && qs.indexOf('?') >= 0) {
            qs = qs.substring(1);
        }
        var params = qs.split('&');
        if (params.length > 0) {
            for (var i = 0; i < params.length; i++) {
                var parName = params[i].split('=');
                if (parName.length < 2) {
                    continue;
                }
                if (this.filters[parName[0]] != undefined) {
                    if (this.filters[parName[0]] instanceof Set) {
                        var parValues = parName[1].split(',');
                        for (var c = 0; c < parValues.length; c++) {
                            //this.filters[parName[0]].push(parValues[c]);
                            this.filters[parName[0]].add(parValues[c]);
                        }
                    } else {
                        this.filters[parName[0]] = parName[1];
                    }
                }
            }
        }
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // GESTIONE PAGINAZIONE
    ////////////////////////////////////////////////////////////////////////////////////////////////

    this.refreshLetters = function (newAggrData) {
        var enabledLetters = newAggrData.Letters;
        var letters = Array.from(document.querySelectorAll('.sidebarModule--letters .sidebarModule__filters a.sidebarModule__filters-btn'));
        const urlSearchParams = new URLSearchParams(window.location.search);
        const params = Object.fromEntries(urlSearchParams.entries());
        var _letter = params.lettera;
        var target = undefined;
        for (var i = 0; i < letters.length; i++) {
            var _dataItemLetter = letters[i].getAttribute('data-item');
            if (!enabledLetters.includes(i)) {
                letters[i].classList.add("sidebarModule__filters-btn--disabled");
            }
            else if (_letter && _dataItemLetter && _letter.toLowerCase() === _dataItemLetter.toLowerCase()) {
                target = i;
            }
        }

        if (target) {
            setTimeout(function () {
                var evt = new MouseEvent('click', {
                    bubbles: true,
                    cancelable: true,
                    view: window
                });

                !letters[target].dispatchEvent(evt);
            }, 1);
        }
    };

    this.refreshPager = function () {
        var buttonsUtils = Array.from(document.querySelectorAll('.pageNavigation__utils__btns a'));
        var pageLinksWrappers = Array.from(document.querySelectorAll('.pageLink a'));
        var buttons = buttonsUtils.concat(pageLinksWrappers);

        if (buttons.length) {
            for (var i = 0; i < buttons.length; i++) {
                var btnEl = buttons[i];

                btnEl.addEventListener('click', function (e) {
                    e.preventDefault();
                    var href = e.target.getAttribute('href');
                    if (href) {
                        href = href.split('?')[0];
                        var pagePos = href.search(/\/[0-9]*$/i);
                        if (pagePos > 0) {
                            ListingFilters.pager = parseInt(href.substring(pagePos + 1), 10);
                        } else {
                            ListingFilters.pager = 0;
                        }
                        ListingFilters.update();
                    }
                });
            }
        }
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // GESTIONE SEARCH
    ////////////////////////////////////////////////////////////////////////////////////////////////

    this.initSearchList = function () {

        //SEARCH NEW
        var listSearchForm = document.getElementById('listSearchForm');
        if (listSearchForm) {
            var listSearchFormButton = listSearchForm.getElementsByTagName("button")[0];
            if (listSearchFormButton) {
                listSearchFormButton.addEventListener('click', function (e) {
                    e.preventDefault();
                    var inputSearch = document.getElementById('listSearch');
                    ListingFilters.add("cerca", inputSearch.value);
                    ListingFilters.update();
                });
            }
        }

        var searchByAuthor = document.getElementById('listSearchByAuthorForm');
        if (searchByAuthor) {
            var searchByAuthorBtn = searchByAuthor.getElementsByTagName("button")[0];
            if (searchByAuthorBtn) {
                searchByAuthorBtn.addEventListener('click', function (e) {
                    e.preventDefault();
                    var inputAuthorSearch = document.getElementById('listSearchByAuthor');
                    ListingFilters.add("autore", inputAuthorSearch.value);
                    ListingFilters.update();
                });
            }
        }

        //LEGACY
        var inputStyling = document.querySelector('.inputStyling');
        if (inputStyling) {
            $("#listSearchForm .inputStyling .searchButton").click(function (e) {
                e.preventDefault();
                ListingFilters.add("cerca", $("#listSearch").val());
                ListingFilters.update();
            });
            $("#listSearchForm .inputStyling .searchButton.custom").click(function (e) {
                e.preventDefault();
                ListingFilters.add("cerca", $("#listSearch").val());
                ListingFilters.add("autore", $("#listSearchauthor").val());
                ListingFilters.update();
            });
        }
    };

    this.refreshSearchList = function () {
        var listSearch = document.getElementById('listSearch');
        if (listSearch) {
            listSearch.value = this.filters.cerca;
        }
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // GESTIONE DATE
    ////////////////////////////////////////////////////////////////////////////////////////////////

    // Restituisce il valore del filtro anno selezionato
    this.getYear = function () {
        var dataFilterYear = document.getElementById('dataFilterYear');
        if (dataFilterYear) {
            return dataFilterYear.value;
        }
    }

    // Restituisce il valore del filtro mese selezionato
    this.getMonth = function () {
        var dataFilterMonth = document.getElementById('dataFilterMonth');
        if (dataFilterMonth) {
            return dataFilterMonth.value;
        }
    }

    // Restituisce il valore del filtro giorno selezionato
    this.getDay = function () {
        var dataFilterDay = document.getElementById('dataFilterDay');
        if (dataFilterDay) {
            return dataFilterDay.value;
        }
    }

    // Recupero Giorni di un dato mese
    this.daysInMonth = function (month, year) {
        return new Date(year, month, 0).getDate();
    }

    // Recupero Data FROM dal calendario
    this.getDataRangeFrom = function () {
        var txtFromDate = document.getElementById('txtFromDate');
        if (txtFromDate) {
            return txtFromDate.value;
        }
    }

    // Recupero Data TO dal calendario
    this.getDataRangeTo = function () {
        var txtToDate = document.getElementById('txtToDate');
        if (txtToDate) {
            return txtToDate.value;
        }
    }

    // Recupero le date formattate e restituisco come da/a
    this.getDatesFormatted = function (_selector) {
        var rangeEl = document.querySelector(_selector);
        if (rangeEl !== null) {
            var range = rangeEl.value;
            if (range) {
                var dates = range.split(" ");
                return dates[0] + '/' + dates[2]
            }
        }
    }

    // Verifica se il giorno esiste in un dato mese. 
    // Altrimenti restituisce l' ultimo giorno del mese
    this.limitDaysInMonth = function (month, year, day) {
        daysInMonth = ListingFilters.daysInMonth(month, year);
        if (day > daysInMonth) day = daysInMonth;
        return day;
    }

    // Aggiunge i filtri dates alla querystring
    this.setDatesFilters = function (selectedYear, selectedMonth, selectedDay) {

        var da = "";
        var a = "";

        var minYear = "2000";
        var maxYear = new Date().getFullYear();
        var minMonth = "01";
        var maxMonth = "12";
        var minDay = "01";
        var maxDay = "31";
        var daysInMaxMonth = "";

        if (selectedYear != "") {
            minYear = selectedYear;
            maxYear = selectedYear;
        }
        if (selectedMonth != "") {
            minMonth = selectedMonth;
            maxMonth = selectedMonth;
        }
        if (selectedDay != "") {
            minDay = selectedDay;
            maxDay = selectedDay;
        }

        da = minYear + "" + "" + minMonth + "" + minDay;
        a = maxYear + "" + "" + maxMonth + "" + ListingFilters.limitDaysInMonth(maxMonth, maxYear, maxDay);

        var dataFilterType = "";

        var dataFilterTypeEl = document.getElementById('dataFilterType');
        if (dataFilterTypeEl) {
            dataFilterType = dataFilterTypeEl.value;
        }

        ListingFilters.add(dataFilterType + "da", da);
        ListingFilters.add(dataFilterType + "a", a);
        ListingFilters.update();
    }

    // Riceve le date come da/a in formato dd-MM-YYYY e li aggiunge ai filtri della querystring
    this.setDatesFiltersFormatted = function (datesRange) {
        const dates = datesRange.split('/');

        var da = dates[0].slice(6) + "" + dates[0].slice(3, 5) + "" + dates[0].slice(0, 2);

        var a = ""
        if (dates[1] != undefined) {
            a = dates[1].slice(6) + "" + dates[1].slice(3, 5) + "" + dates[1].slice(0, 2);
        }

        ListingFilters.add("datada", da);
        ListingFilters.add("dataa", a);
        ListingFilters.update();
    }

    // Mostra la tendina dei giorni
    this.showDataFilterDay = function () {
        var $dataFilterDay = document.getElementById('dataFilterDay');
        if ($dataFilterDay && $dataFilterDay.length) {
            $('#dataFilterDay').prop("disabled", false);
            $('#dataFilterDay').not(':input[type=hidden]').selectric('refresh');
        }
    }

    // Nascondi la tendina dei giorni
    this.hideDataFilterDay = function () {
        var $dataFilterDay = document.getElementById('dataFilterDay');
        if ($dataFilterDay && $dataFilterDay.length) {
            $dataFilterDay.val("");
            $('#dataFilterDay').prop("disabled", false);
            $('#dataFilterDay').not(':input[type=hidden]').selectric('refresh');
            $('#dataFilterDay').prop("disabled", true);
        }
    }

    // Nascondi la tendina dei mesi
    this.hideDataFilterMonth = function () {
        var $dataFilterMonth = document.getElementById('dataFilterMonth');
        if ($dataFilterMonth && $dataFilterMonth.length) {
            $dataFilterMonth.val("");
            $('#dataFilterMonth').not(':input[type=hidden]').selectric('refresh');
        }
    }

    // Popola la tendina dei giorni, in base a mese anno selezionati.
    this.setDataFilterDay = function (month, year) {

        if (month == "" || year == "") {
            ListingFilters.hideDataFilterMonth();
            ListingFilters.hideDataFilterDay();
            return;
        }

        var daysInMonth = ListingFilters.daysInMonth(month, year);

        var dataFilterDay = document.getElementById('dataFilterDay');

        if (dataFilterDay) {
            for (c = 1; c <= daysInMonth; c++) {
                $('#dataFilterDay').append('<option value="' + ListingFilters.leadingZero(c) + '">' + ListingFilters.leadingZero(c) + '</option>');
            }
        }

        ListingFilters.showDataFilterDay();
    }

    // Inizializza i filtri per data
    this.initDates = function () {
        var dataFilterYear = document.getElementById('dataFilterYear');

        if (dataFilterYear) {
            // Per popolare menu a tendina dei gg, in base a mese anno selezionati
            $('#dataFilterYear, #dataFilterMonth').change(function (e) {
                var year = ListingFilters.getYear();
                var month = ListingFilters.getMonth();
                ListingFilters.setDataFilterDay(month, year);
            });

            // Per creare filtro da a (combo anno/mese/giorno)
            $('#dataFilterYear, #dataFilterMonth, #dataFilterDay').change(function (e) {
                ListingFilters.setDatesFilters(ListingFilters.getYear(), ListingFilters.getMonth(), ListingFilters.getDay());
            });
        }
    }

    // Popola le combo in base ai filtri data ricevuti in querystring
    this.refreshDates = function () {

        var da = ListingFilters.filters.da;
        var a = ListingFilters.filters.a;

        var annoDaSelezionare = "";
        var meseDaSelezionare = "";
        var giornoDaSelezionare = "";

        var annoDa = da.substring(0, 4);
        var meseDa = da.substring(4, 6);
        var giornoDa = da.substring(6, 8);

        var annoA = a.substring(0, 4);
        var meseA = a.substring(4, 6);
        var giornoA = a.substring(6, 8);

        if (annoDa == annoA) annoDaSelezionare = annoDa;
        if (meseDa == meseA) meseDaSelezionare = meseDa;
        if (giornoDa == giornoA) giornoDaSelezionare = giornoDa;

        // Attivare e popolare i giorni solo in presenza di mese e anno...
        ListingFilters.setDataFilterDay(meseDaSelezionare, annoDaSelezionare);

        var dataFilterYear = document.getElementById('dataFilterYear');
        if (dataFilterYear) {
            $('#dataFilterYear').val(annoDaSelezionare);
            $('#dataFilterYear').selectric('refresh');
        }

        var dataFilterMonth = document.getElementById('dataFilterMonth');
        if (dataFilterMonth) {
            $('#dataFilterMonth').val(meseDaSelezionare);
            $('#dataFilterMonth').selectric('refresh');
        }

        var dataFilterDay = document.getElementById('dataFilterDay');
        if (dataFilterDay) {
            $('#dataFilterDay').val(giornoDaSelezionare);
            $('#dataFilterDay').not(':input[type=hidden]').selectric('refresh');
        }

        var txtFromDate = document.getElementById('txtFromDate');
        if (txtFromDate) {
            // Per creare filtro da a (calendari da/a)
            if (da != '' && da.length > 7) {
                $('#txtFromDate').datepicker("setDate", giornoDa + "/" + meseDa + "/" + annoDa);
            }
            if (a != '' && a.length > 7) {
                $('#txtToDate').datepicker("setDate", giornoA + "/" + meseA + "/" + annoA);
            }
        }
    }

    this.parseDate = function (input, format) {
        // Default format
        format = format || 'yyyy-mm-dd'; 
        var parts = input.match(/(\d+)/g),
            i = 0, fmt = {};

        // Extract date-part indexes from the format
        format.replace(/(yyyy|dd|mm)/g, function (part) { fmt[part] = i++; });
        return new Date(parts[fmt['yyyy']], parts[fmt['mm']] - 1, parts[fmt['dd']]);
    }

    this.leadingZero = function (value) {
        if (value < 10) {
            return "0" + value.toString();
        }
        return value.toString();
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////
    // GESTIONE CONTENT FILTERS
    ////////////////////////////////////////////////////////////////////////////////////////////////

    this.cleanUrl = function (url) {
        var cleanUrl = url.toString().replace(/ /gi, "-").toLowerCase();
        return cleanUrl;
    }

    this.initContentFilters = function (selector, filterType, arrKey, newAggrData, config) {
        config = config || {};

        // Invio parametri sull'onclick dei contentfilters
        var listElements = Array.from(document.querySelectorAll("#" + selector + " li"));

        for (let index = 0; index < listElements.length; index++) {
            const element = listElements[index];

            element.addEventListener('click', function (s) {
                s.preventDefault();

                var link = element.getElementsByTagName("a")[0];
                var isWebpak = link.classList.contains('Ricerca__sidebar-module-filters-btn');
                if (element.classList.contains('active') || (isWebpak && !link.classList.contains('Ricerca__sidebar-module-filters-btn--checked'))) {
                    var value = link.dataset.value;
                    if (value) {
                        ListingFilters.remove(filterType, value);
                    } else {
                        ListingFilters.remove(filterType, ListingFilters.cleanUrl(link.textContent));
                    }
                }
                else {
                    var value = link.dataset.value;
                    if (value) {
                        ListingFilters.add(filterType, value);
                    } else {
                        ListingFilters.add(filterType, ListingFilters.cleanUrl(link.textContent));
                    }
                }
                ListingFilters.update();
            })
        }

        // Inizializzo contentfilters leggendo il json newAggrData
        ListingFilters.loadElementsContentFilters(selector, arrKey, newAggrData);

        // Rimuovo le voci che non hanno risultati (nell'init posso rimuoverle)
        ListingFilters.removeElementsContentFilters(selector);

        if (!config.disableShowMoreContentFilters) {
            // Gestione tasti more
            ListingFilters.showMoreContentFilters(selector);
        }

        // Gestione links filtri selezionati
        ListingFilters.clickContentFilters(selector);

        // Gestione illuminazione filtri selezionati
        ListingFilters.highlightContentFilters(selector, filterType);
    };

    this.refreshContentFilters = function (selector, arrKey, newAggrData, config) {
        config = config || {};

        // Prima li nascondo tutti
        ListingFilters.hideElementsContentFilters(selector);

        // Poi valorizzo solo quelli presenti in newAggrData
        ListingFilters.loadElementsContentFilters(selector, arrKey, newAggrData);

        if (!config.disableShowMoreContentFilters) {
            // Gestione tasti more
            ListingFilters.showMoreContentFilters(selector);
        }

        // Rimuovo tutto il menu se non c'e' nemmeno una voce rimasta
        ListingFilters.removeContentFilters(selector);
    }

    this.showMoreContentFilters = function (selector) {
        var filtersUl = Array.from(document.querySelectorAll("#" + selector + ":not(.Ricerca__sidebar-module--rubrica)"));

        if (filtersUl.length > 0) {
            var $filtersUl = $("#" + selector + ":not(.Ricerca__sidebar-module--rubrica)");
            $filtersUl.each(function () {
                var max = 5
                if ($(this).find('li:visible').length > max) {
                    $(this).find('.moreButton').remove();
                    var allItems = $(this).find('li:visible');
                    var maxItems = $(this).find('li:visible').slice(0, max - 1);

                    $(this).find('li:visible:gt(' + (max - 1) + ')').hide().end().append('<li class="moreButton"><a href="#" class="show_more">...altri argomenti</a></li>');
                    $(this).find('.moreButton').click(function (e) {
                        e.preventDefault();
                        if ($(this).find('.show_more').length) {
                            maxItems.hide();
                            allItems.show();
                            $(this).html('<a href="#" class="show_less">...meno argomenti</a>');
                        } else {
                            allItems.hide();
                            maxItems.show();
                            $(this).html('<a href="#" class="show_more">...altri argomenti</a>');
                        };
                    });
                };
            });
        }
    }

    this.clickContentFilters = function (selector) {
        var filterButtonsList = Array.from(document.querySelectorAll('#' + selector + ' li.selectYes'));

        if (filterButtonsList.length > 0) {
            var $filterButtonsList = $('#' + selector + ' li.selectYes');

            // Binding onclick
            $filterButtonsList.click(function (e) { 
                e.preventDefault();
                $(this).toggleClass('active');
            })
        }
    }

    this.highlightContentFilters = function (selector, filterType) {
        var filterButtonsList = Array.from(document.querySelectorAll('#' + selector + ' li.selectYes a'));

        if (filterButtonsList.length > 0) {

            for (let i = 0; i < filterButtonsList.length; i++) {
                var el = filterButtonsList[i];
                ListingFilters.cleanUrl(el.text);
                el.parentNode.classList.add('active');
            }

        }
        var filterButtonsList = Array.from(document.querySelectorAll('#' + selector + ' li a'));

        if (filterButtonsList.length > 0) {

            for (let i = 0; i < filterButtonsList.length; i++) {
                var el = filterButtonsList[i];
                var filterVal = el.getAttribute('data-value');
                ListingFilters.cleanUrl(el.text);
                if (ListingFilters.exists(filterType, filterVal)) {
                    el.classList.add('Ricerca__sidebar-module-filters-btn--checked');
                }
            }

        }
    }

    this.removeContentFilters = function (selector) {
        var contentFilters = Array.from(document.querySelectorAll("#" + selector + " li"));

        if (contentFilters.length > 0) {
            for (let index = 0; index < contentFilters.length; index++) {

                var spanNR = contentFilters[index].parentNode.querySelector('span.nR');

                if (spanNR) {
                    contentFilters[index].parentNode.style.display = 'block';
                } else {
                    contentFilters[index].parentNode.style.display = 'none';
                }
            }
        }
    }

    this.loadElementsContentFilters = function (selector, arrKey, jsonArray) {

        var enabledItems = jsonArray[arrKey];

        for (var key in enabledItems) {
            var label = key;
            var nr = ListingFilters.cleanUrl(enabledItems[key]);

            var selectors = Array.from(document.querySelectorAll("#" + selector + " li a"));
            if (selectors.length > 0) {
                var selected = selectors.filter(function (selector) {
                    return selector.getAttribute("data-filter") == label;
                });
                if (selected && selected.length > 0 && nr > 0) {
                    var spanNR = selected[0].parentNode.querySelector('span.nR');
                    if (spanNR !== null) {
                        spanNR.innerHTML = nr;
                    }
                }
            }
        }
    };

    this.removeElementsContentFilters = function (selector) {
        var contentFilters = Array.from(document.querySelectorAll("#" + selector + " li:not(.active):not(.newFilterActive) span.nR"));
        if (contentFilters.length > 0) {
            for (let i = 0; i < contentFilters.length; i++) {
                if (contentFilters[i].innerText == "") {
                    contentFilters[i].parentNode.remove;
                }
            }
        }
    }

    this.hideElementsContentFilters = function (selector) {
        var element = document.querySelectorAll("#" + selector + " li.newFilterActive span.nR");
        var contentFilters = Array.from(element);
        if (contentFilters.length > 0) {
            for (let i = 0; i < contentFilters.length; i++) {
                if (contentFilters[i] !== null) {
                    contentFilters[i].innerHTML = "";
                }
            }
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    this.exists = function (filterType, filterVal) {
        var elementExists = false;
        if (this.filters[filterType] != undefined) {
            if (this.filters[filterType] instanceof Set) {
                if (this.filters[filterType].has(filterVal)) {
                    elementExists = true;
                }
            }
            else {
                if (this.filters[filterType] == filterVal) {
                    elementExists = true;
                }
            }
        }
        return elementExists;
    };

    this.add = function (filterType, filterVal) {
        if (this.filters[filterType] != undefined) {
            if (this.filters[filterType] instanceof Set)
                this.filters[filterType].add(filterVal);
            else
                this.filters[filterType] = filterVal;
            this.pager = 0;
        }
    };

    this.remove = function (filterType, filterVal) {
        if (this.filters[filterType] != undefined) {
            if (this.filters[filterType] instanceof Set) {
                this.filters[filterType].delete(filterVal);
            } else {
                this.filters[filterType] = '';
            }
            this.pager = 0;
        }
    };

    this.update = function () {
        var newUrl = "";

        for (var filterType in this.filters) {
            var newVal = '';

            if (this.filters[filterType] == undefined)
                continue;

            if (this.filters[filterType] instanceof Set) {
                if (this.filters[filterType].size < 1)
                    continue;
                newVal = filterType + "=";
                for (var i = 0; i < this.filters[filterType].size; i++) {
                    if (i != 0)
                        newVal = newVal + ",";
                    newVal = newVal + [...this.filters[filterType]][i];
                }
            } else {
                if (this.filters[filterType] == "") {
                    continue
                } else {
                    newVal = filterType + "=" + this.filters[filterType];
                }
            }
            if (newUrl.length < 1)
                newUrl = "?";
            else
                newUrl = newUrl + "&";

            newUrl = newUrl + newVal;
        }

        if (this.pager > 1) {
            newUrl = this.baseUrl + "/" + this.pager + newUrl;

            var canonical = document.querySelector('link[rel="canonical"]');
            if (canonical !== null) {
                canonical.href = document.location.origin + "/" + newUrl;
            }
        }
        else
            newUrl = this.baseUrl + newUrl;

        history.replaceState({ 'filterState': this.filters, 'pager': this.pager }, document.title, newUrl);

        var dataFilterYear = document.getElementById('dataFilterYear');
        if (dataFilterYear) {
            return dataFilterYear.value;
        }

        var aggrData = document.getElementById('aggrData');
        if (aggrData) {
            aggrData.value = '';
        }

        var aggrBase = document.getElementById('aggrBase');
        if (aggrBase) {
            aggrBase.value = '';
        }

        var aggrDataParams = document.getElementById('aggrDataParams');
        if (aggrDataParams) {
            aggrDataParams.value = '';
        }

        var aggrPage = document.getElementById('aggrPage');
        if (aggrPage) {
            aggrPage.value = this.pager;
        }

        var form = document.querySelector('#faggrData');

        if (form !== null) {
            var formData = new FormData(form);

            fetch(newUrl, {
                method: 'POST',
                body: formData,
            })
            .then((response) => {
                if (!response.ok) {
                    throw Error(response.statusText);
                }
                return response;
            })
            .then((response) => response.text())
            .then((data) => {
                ListingFilters.handleResult(data);

                var shopAltalexSearch = document.querySelector('#shopAltalexSearch');
                var searchEdicolaProf = document.querySelector('#searchEdicolaProf');

                if (shopAltalexSearch !== null && (shopAltalexSearch.innerHTML == undefined || shopAltalexSearch.innerHTML.trim() == '')) {
                    shopAltalexSearch.parentNode.removeChild(shopAltalexSearch);
                }
                if (searchEdicolaProf !== null && (searchEdicolaProf.innerHTML == undefined || searchEdicolaProf.innerHTML.trim() == '')) {
                    searchEdicolaProf.parentNode.removeChild(searchEdicolaProf);
                }

                var spinner = document.querySelector('.loadingSpinner.loadingSpinner--visible');
                if (spinner !== null) {
                    spinner.classList.remove('loadingSpinner--visible');
                }
            })
            .catch((error) => { console.error(error); });
        }
    };

    this.searchShowResult = function () {
        if (document.querySelector("#real_amount")) {
            var amount = document.querySelector("#real_amount").innerText;
            document.querySelector("#Ricerca__main-tools-result").innerText = amount;
        }
    };

    this.handleResult = function (html) {
        var aggrResult = document.querySelector('#aggrResult');
        if (aggrResult !== null) {
            aggrResult.innerHTML = html;
        }

        this.searchShowResult();
        var aggrData = document.querySelector('#aggrData');

        var newAggrDataTxt = aggrData.value;
        if (newAggrDataTxt.length < 1) {
            return;
        }

        var newAggrData = JSON.parse(newAggrDataTxt);

        this.refreshPager();
        this.refreshContentFilters("filterArguments", "Args", newAggrData);
        this.refreshContentFilters("filterAree", "AreaCategory", newAggrData, { disableShowMoreContentFilters: true });
        this.refreshContentFilters("filterRubricaCategory", "RubricaCategory", newAggrData);
        this.refreshContentFilters("filterArgumentsMax", "ArgsMax", newAggrData);
        //this.refreshContentFilters("filterChannels", "canale", "Channels", newAggrDataFilter);
        this.refreshContentFilters("filterDocuments", "TipoDocs", newAggrData);
        this.refreshContentFilters("filterCodici", "Codici", newAggrData);
        this.refreshContentFilters("filterAudioCategory", "CategoryAudio", newAggrData);

        window.scrollTo({
            top: 160,
            left: 0,
            behavior: 'smooth'
        });
    };
};

document.addEventListener('DOMContentLoaded', () => {
    history.replaceState({}, document.title, document.location.href);
    ListingFilters.init();
});;
///////////////////////////////////
// LOGIN
///////////////////////////////////
function LoginGiuridicoUser(urlLogin, buttonId, usernameId, passwordId, errorId, url, checkboxId) {
    $(buttonId).click(function (event) {
        event.preventDefault();
        GiuridicoLogin(urlLogin, usernameId, passwordId, errorId, url, checkboxId);
    });
}

function GiuridicoLogin(urlLogin, usernameId, passwordId, errorId, url, checkboxId) {
    if (checkboxId == '' || $(checkboxId) == null) { param = '0'; }
    else {
        var checkbox = $(checkboxId).is(":checked");
        if (checkbox) { param = '1'; }
        else { param = '0'; }
    }
    //blockUi();
    $.ajax({
        type: 'POST',
        timeout: 35000,
        url: urlLogin,
        data: { UserName: $(usernameId).val().replace(',', '.'), PassWord: $(passwordId).val(), ReturnUrl: url, CheckboxValue: param },
        success: function (data) {
            //unblockUi();
            if (data.Success) {
                if (data.DoRedirect) {
                    window.location.href = data.ReturnUrl;
                }
                else {
                    $(errorId).html(data.Message);
                }
            }
            else {
                if (data.DoRedirect) {
                    window.location.href = data.ReturnUrl;
                }
                else {
                    $(errorId).html(data.Message);
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            //unblockUi();
            $(errorId).html(textStatus);
        }
    });
}

///////////////////////////////////
// ARTICOLO
///////////////////////////////////
function documentBookmark(action, freemium, documentId, linkDocumentBookmark) {
    if (freemium.RequiresLogin) {
        alert("Errore");
    }
    else {

        $.ajax({
            url: Giuridico.Routes.giuridico + action + "/" + documentId,
            type: 'POST',
            data: documentId,
            cache: false,
            headers: { "cache-control": "no-cache" }
        })
        .success(function () {
            toggleBookmark(linkDocumentBookmark);
        })
        .error(function () { alert('errore'); });
    }
}

function toggleBookmark(linkDocumentBookmark) {
    $(linkDocumentBookmark).toggleClass("highlight");

    var on = "<a href=\"javascript:documentBookmark('clearbookmark');\"><i class='fa fa-bookmark' style='color:orange'></i>salvato</a>";
    var off = "<a href=\"javascript:documentBookmark('bookmark');\"><i class='fa fa-bookmark'></i>salva</a>";

    if ($(linkDocumentBookmark).hasClass("highlight"))
        var text = on;
    else
        var text = off;

    $(linkDocumentBookmark).hide();
    $(linkDocumentBookmark).html(text);
    $(linkDocumentBookmark).fadeIn();

}

///////////////////////////////////
// BOOKMARKS
///////////////////////////////////
function BookmarksAddNote(documentId, note) {
    $.ajax({
        url: Giuridico.Routes.bookmarknote,
        type: 'POST',
        data: { idDocumento: documentId, note: $(note).val() },
        cache: false,
        headers: { "cache-control": "no-cache" }
    })
    .success(function () {
        window.location.reload();
    })
    .error(function () { alert('errore'); });
}

///////////////////////////////////
// CONSOLIDATI
///////////////////////////////////
function ConsolidatoDownload(item) {
    $.ajax({
        url: Giuridico.Routes.checkDownload + item,
        type: 'POST',
        data: "",
        cache: false,
        headers: { "cache-control": "no-cache" }
    })
    .success(function (result) {
        if (result.RequiresLogin) {
            ShowLoginAlertConsolidato();
        }
        if (result.RequiresProductPurchase) {
            ShowLoginAlertConsolidato();
        }
        else {
            window.location.href = result.Url;
        }
    })
    .error(function () {
    });
}

function GiuridicoConsolidatoSearch() {
    let range = $('.date-pickr-range[data-id="range"]').val();
    const dates = range.split(" ");

    if ($("#fromPage").val() == "" && $("#toPage").val() == "") {
        $('.quotidiano-search-error').css("display", "block");
        return;
    }
    $('.quotidiano-search-error').css("display", "none");

    var params =
         {
             DataFrom: dates[0],
             DataTo: dates[2]
        };

    searchShowResult = function (data) {
        $('.featurePdfQG .featurePdfQG__entries').slideDown();
        $("#featurePdfQG__entries").html(data);
    };

    micromodalInit = function () {
        MicroModal.init({
            awaitCloseAnimation: true,
            openClass: 'Modal--is-open',
            disableFocus: true,
        });
    };

    $.ajax({
        url: AltalexWKI.Routes.giuridicoaltalexCheckSearch,
        type: 'POST',
        data: params,
        cache: false,
        headers: { "cache-control": "no-cache" }
    })
    .success(function (result) {
        searchShowResult(result);
        micromodalInit();
    })
    .error(function () { searchShowResult("<label>Nessun arretrato disponibile </label> "); });
}

///////////////////////////////////
// VOTA DIBATTITO
///////////////////////////////////
function GiuridicoVote(documentId, voto) {
    $.ajax({
        url: Giuridico.Routes.votaDibattito + documentId + '/' + voto,
        type: 'POST',
        data: "",
        cache: false,
        headers: { "cache-control": "no-cache" }
    })
    .success(function () {
        $('#votaProButton').prop('href', "javascript:void(0)");
        $('#votaControButton').prop('href', "javascript:void(0)");
        $('#votaProButton').remove();
        $('#votaControButton').remove(); 
    })
    .error(function () {
        alert('errore');
    });
}

///////////////////////////////////
// BASE
///////////////////////////////////
function JSONPost2(url, jsonData, functionSuccess, functionFail) {
    var json = JSON.stringify(jsonData);
    $.ajax(
        {
            url: url,
            type: 'POST',
            dataType: 'json',
            data: json,
            contentType: 'application/json; charset=utf-8',
            cache: false,
            headers: { "cache-control": "no-cache" }
        })
        .success(functionSuccess)
        .error(functionFail);
}

///////////////////////////////////
// AGENZIE
///////////////////////////////////
function loadAgenzia() {
    if ($('#CAP').val() == "") {
        alert("Per favore inserisci un cap");
        return;
    }

    var checkedCount = $("input:checked").length;
    var valid = checkedCount > 0;
    if (!valid) {
        alert("Per favore seleziona almeno una professione");
        return;
    }

    var capInput = $('#CAP').val();
    var prof = $("input:checked").select().val()

    $('.agenzie .show-results').html('<br />Ricerca in corso <br/>');

    var param = {
        cap: capInput,
        professioni: prof
    };

    JSONPost2(
        Giuridico.Routes.elencoAgenzie,
        param,
        function (result) {
            $('.agenzie .show-results').html(result);
            $('.agenzie .show-results').slideDown();
        },
        function (xhr, status) {
            $('.agenzie .show-results').html(xhr.responseText);
            $('.agenzie .show-results').slideDown();
        }
    );
}

///////////////////////////////////
// RICERCA
///////////////////////////////////
function ClearSearchFilters(isPage) {
    if (isPage == "Page") {
        $('#SEARCHTERMPage').val('');
        $('#SEARCHAUTHORPage').val('');
        $('#SEARCHSECTIONPage').prop('selectedIndex', 0);
        $("#fromPage").datepicker('setDate', null);
        $("#toPage").datepicker('setDate', null);
    } else {
        $('#SEARCHTERM').val('');
        $('#SEARCHAUTHOR').val('');
        $('#SEARCHSECTION').prop('selectedIndex', 0);
        $('#from').datepicker('setDate', null);
        $('#to').datepicker('setDate', null);
    }
}

function OrdinaRisultatiRicerca(param) {
    var path = window.location.origin + "/Cerca";
    if (param != null) {
        path = path + "?" + param + $('#SEARCHORDERPage').val();
    }
    window.location.href = path;
}

///////////////////////////////////
// STRUMENTI DOCUMENTO
///////////////////////////////////
//function sendEmailDocument(shareUrl) {
//    var title = $('#titoloArticolo').text
//    window.open("mailto:?subject=IlQuotidianoGiuridico: " + title.replace("+", "%20") + " &body=Leggi l’articolo tratto da Il Quotidiano Giuridico: " + shareUrl);
//}

function DownloadPDF(documentID) {
    var url = Giuridico.Routes.creaPdf + documentID;
    window.open(url);
}

function openLoginBoxRiviste() {
    $('.reservedaccess-download-panel').hide();
    var myopener = $(this);
    var effect = 'slide'; // effetto
    var options = { direction: 'right' }; // opzioni
    var duration = 300; // durata (default: 400 millisecondi)
    $('.reservedaccess-download-panel').show(effect, options, duration);
}

function buyBoxRiviste(link) {
    $('.overlay').fadeIn();
    var myopener = $(this);
    var effect = 'slide'; // effetto
    var options = { direction: 'right' }; // opzioni
    var duration = 300; // durata (default: 400 millisecondi)
    $('#buyNowLink').attr("href", link);
    $('.reservedaccess-buy-panel').show(effect, options, duration);
}

function ContentReservedDownload() {
    var myopener = $(this);
    var effect = 'slide'; // effetto
    var options = { direction: 'right' }; // opzioni
    var duration = 300; // durata (default: 400 millisecondi)
    $('.reservedaccess-download-panel').show(effect, options, duration);
    $('.overlay').css({
        "opacity": "0.35",
        "filter": "alpha(opacity=35)",
        "-moz-opacity": "0.35",
        "-khtml-opacity": "0.35",
    });
};
