var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

//Aggiunta main loading all\'unload del body
window.onbeforeunload = function() {
    $('#mini-loader').hide();
    $('#main_loading').show();
};

$(window).load(function() {
    $('#main_loading').fadeOut();
});

<?php
$skip_permissions = true;
include_once(__DIR__."/../core.php");
if(isUserAutenticated()) {
?>
$(document).ready(function() {
    //Orologio
    clock();

    //Calendario principale
    $('#daterange').daterangepicker({
            ranges: {
                '<?php echo _("Oggi") ?>': [moment(), moment()],
                '<?php echo _("Ieri") ?>': [moment().subtract('days', 1), moment().subtract('days', 1)],
                '<?php echo _("Ultimi 7 giorni") ?>': [moment().subtract('days', 6), moment()],
                '<?php echo _("Ultimi 30 giorni") ?>': [moment().subtract('days', 29), moment()],
                '<?php echo _("Questo mese") ?>': [moment().startOf('month'), moment().endOf('month')],
                '<?php echo _("Mese scorso") ?>': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')],
                "<?php echo _("Quest'anno") ?>": [moment().startOf('year'), moment().endOf('year')],
                '<?php echo _("Anno scorso") ?>': [moment().subtract('year', 1).startOf('year'), moment().subtract('year', 1).endOf('year')]
            },
            locale: {
                format: 'DD/MM/YYYY',
                separator: " - ",
                applyLabel: '<?php echo _("Applica") ?>',
                cancelLabel: '<?php echo _("Annulla") ?>',
                fromLabel: '<?php echo _("Da") ?>',
                toLabel: '<?php echo _("A") ?>',
                customRangeLabel: '<?php echo _("Personalizzato") ?>',
                monthNames: ['<?php echo _("Gennaio") ?>','<?php echo _("Febbraio") ?>','<?php echo _("Marzo") ?>','<?php echo _("Aprile") ?>','<?php echo _("Maggio") ?>','<?php echo _("Giugno") ?>','<?php echo _("Luglio") ?>','<?php echo _("Agosto") ?>','<?php echo _("Settembre") ?>','<?php echo _("Ottobre") ?>','<?php echo _("Novembre") ?>','<?php echo _("Dicembre") ?>'],
                daysOfWeek: ['<?php echo _("Do") ?>','<?php echo _("Lu") ?>','<?php echo _("Ma") ?>','<?php echo _("Me") ?>','<?php echo _("Gi") ?>','<?php echo _("Ve") ?>','<?php echo _("Sa") ?>'],
                "firstDay": 1
            },
            startDate: '<?php echo date("d/m/Y", strtotime($_SESSION['period_start'])) ?>',
            endDate: '<?php echo date("d/m/Y", strtotime($_SESSION['period_end'])) ?>',
            applyClass: 'btn btn-app btn-sm',
            cancelClass: 'btn btn-danger btn-sm'
        },
        function(start, end) {
            //Submit period and refresh page
            $.get('<?php echo $rootdir; ?>/core.php?period_start=' + start.format('YYYY-MM-DD') + '&period_end=' + end.format('YYYY-MM-DD'), function() {
                location.href = location.href;
            });
        }
    );

    $('.ask').on('click', function(){
        var msg = "<?php echo _("Eliminare questo elemento?"); ?>";
        if($(this).data("msg") != undefined) var msg = $(this).data("msg");

        if(confirm(msg)){
            var position= "";
            if($(this).data("position") != undefined) position = $(this).data("position");

            location.href = $(this).data("href") + "&op=" + $(this).data("op") + "&id=" + $(this).data("id");
        }
    });

   //Sidebar
    $('.sidebar-menu > li.treeview i.fa-angle-left').click(function(e) {
        e.preventDefault();
        $(this).find('ul').stop().slideDown();
    });

    $('.sidebar-menu > li.treeview i.fa-angle-down').click(function(e) {
        e.preventDefault();
        $(this).find('ul').stop().slideUp();
    });

    $menulist = $('.treeview-menu > li.active');
    for (i = 0; i < $menulist.length; i++) {
        $list = jQuery($menulist[i]);
        $list.parent().show().parent().addClass('active');
        $list.parent().parent().find('i.fa-angle-left').removeClass('fa-angle-left').addClass('fa-angle-down');
    }
<?php if( get_var("Nascondere la barra sinistra di default") == "1" ){ ?>

    $(".sidebar-offcanvas").addClass('collapse-left');
    $(".content-wrapper").addClass('strech');
<?php } ?>

    //Menu ordinabile
    $(".sidebar-menu").sortable({
        cursor: 'move',

        stop: function(event, ui) {
            var order = $(this).sortable('toArray').toString();

            $.post("<?php echo $rootdir; ?>/modules/aggiornamenti/actions.php?id_module=<?php echo $modules_info['Aggiornamenti']['id'] ?>", {
                op: 'sortmodules',
                ids: order
            });
        }
    });

    //Tabs
    $('#tabs').tabs();

    if ((location.hash).substr(0, 5) == '#tab_') {
        setTimeout(function() {
            window.scrollTo(0, 0);
        }, 1);
    }

    $('.nav-pills a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
    })

    //Entra nel tab indicato al caricamento della pagina
    var hash = window.location.hash;
    if (hash != '') $('ul.nav a[href="' + hash + '"]').tab('show');

    //Aggiunta nell'URL del nome tab su cui tornare dopo il submit
    $('form').on('submit', function() {
        id = $(this).closest('.tab-pane.active').attr('id');

        if (id != '' || id != undefined) {
            $(this).attr('action', $(this).attr('action') + '#' + id);
        }
    });

    //Messaggio di avviso salvataggio a comparsa sulla destra solo nella versione a desktop intero
    if ($(window).width() > 1023) {
        var i = 0;

        $('.alert-success').each(function() {
            i++;
            tops = 60 * i + 95;

            $(this).css({
                'position': 'fixed',
                'z-index': 3,
                'top': -100,
                'right': 10,
                'opacity': 1
            }).delay(1000).animate({
                'top': tops,
                'opacity': 1
            }).delay(3000).animate({
                'top': -100,
                'opacity': 0
            });
        });
    }

    //Nascondo la notifica se passo sopra col mouse
    $('.alert-success').on('mouseover', function(){
        $(this).stop().animate({
            'top': -100,
            'opacity': 0
        });
    });

    $('.widget').mouseover(function(e) {
        e.preventDefault();
        start_widgets($("#widget-controller_top, #widget-controller_right"));
    });

    backtotop_button();

    //Barra di ricerca
    //JQuery-UI Autocomplete wrapper
    $.widget("custom.catcomplete", $.ui.autocomplete, {
        _renderMenu: function(ul, items) {
            if (items[0].value == undefined) {
                $('#supersearch').removeClass('wait');
                ul.html('');
            } else {
                var that = this,
                    currentCategory = "";

                ul.addClass('ui-autocomplete-scrollable');

                $.each(items, function(index, item) {

                    if (item.category != currentCategory) {
                        ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
                        currentCategory = item.category;
                    }

                    that._renderItemData(ul, item);
                });
            }
        },

        _renderItem: function(ul, item) {
            return $("<li>")
                .append("<a href='" + item.link + "' title='Clicca per aprire'><b>" + item.value + "</b><br/>" + item.label + "</a>")
                .appendTo(ul);
        }
    });

    $('#supersearch').keyup(function() {
        $(document).ajaxStop();

        if ($(this).val() == '') {
            $(this).removeClass('wait');
        } else {
            $(this).addClass('wait');
        }
    });

    //Configurazione supersearch
    $('#supersearch').catcomplete({
        html: true,
        source: function(request, response) {
            $.ajax({
                url: '<?php echo $rootdir ?>/ajax_autocomplete.php?op=supersearch&module=*',
                async: false,
                dataType: "json",
                data: {
                    term: request.term
                },

                complete: function(jqXHR) {
                    $('#supersearch').removeClass('wait');
                },

                success: function(data) {
                    if (data == null) {
                        response($.map(['a'], function(item) {
                            return false;
                        }));
                    } else {
                        response($.map(data, function(item) {
                            labels = (item.labels).toString();
                            labels = labels.replace('<br/>,', '<br/>');

                            return {
                                label: labels,
                                category: item.category,
                                link: item.link,
                                value: item.title
                            }
                        }));
                    }
                },

                minLength: 2,

                select: function(event, ui) {
                    location.href = ui.link;
                }
            });
        }
    });
});

//Widgets ordinabili
function start_widgets($widgets) {
    cls = new Array();

    for (i = 0; i < $widgets.length; i++) {
        $widget = jQuery($widgets[i]);

        list_name = ($widget.attr('id')).replace('widget-', '');

        //Salvo le classi del primo elemento di ogni lista
        cls[list_name] = $widget.find('li:first').attr('class');

        $widget.sortable({
            items: 'li',
            cursor: 'move',
            dropOnEmpty: true,
            connectWith: '.widget',
            scroll: true,
            helper : 'clone',
            start: function(event, ui) {
                //Salvo la lista da cui proviene il drag
                src_list = ($(this).attr('id')).replace('widget-', '');

                //Evidenzio le aree dei widget
                $('.widget').addClass('bordered').sortable('refreshPositions');
            },
            stop: function(event, ui) {
                //Rimuovo l'evidenziazione dell'area widget
                $('.widget').removeClass('bordered');

                //Salvo la lista su cui ho eseguito il drop
                dst_list = (ui.item.parent().attr('id')).replace('widget-', '');
                var new_class = "";

                var order = $(this).sortable('toArray').toString();
                $.post("<?php echo $rootdir; ?>/modules/aggiornamenti/actions.php?id_module=<?php echo $modules_info['Aggiornamenti']['id'] ?>", {
                    op: 'updatewidget',
                    location: dst_list,
                    id_module: globals.id_module,
                    class: new_class,
                    id: ui.item.attr('id')
                });

                $.post("<?php echo $rootdir; ?>/modules/aggiornamenti/actions.php?id_module=<?php echo $modules_info['Aggiornamenti']['id'] ?>", {
                    op: 'sortwidget',
                    location: dst_list,
                    ids: order,
                    id_module: globals.id_module,
                    class: new_class
                });
            }
        });
    }
}

//Modal
function launch_modal(title, href, init_modal=1, id='#bs-popup') {
    $('html').addClass('modal-open');

    $(id).on('hidden.bs.modal', function() {
        $('html').removeClass('modal-open');
        $(this).data('modal', null);
    });

    //Lettura contenuto div
    if (href.substr(0, 1) == '#') {
        data = $(href).html();

        $(id).html(
            '<div class="modal-dialog modal-lg">' +
            '	<div class="modal-content">' +
            '		<div class="modal-header bg-light-blue">' +
            '			<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only"><?php echo _("Chiudi") ?></span></button>' +
            '			<h4 class="modal-title"><i class="fa fa-pencil"></i> ' + title + '</h4>' +
            '		</div>' +
            '		<div class="modal-body">' + data + '</div>'
        );
        if (init_modal == 1) {
            $(id).modal('show');
        }
    } else {
        $.get(href, function(data, response) {
            if (response == 'success') {

                $(id).html(
                    '<div class="modal-dialog modal-lg">' +
                    '	<div class="modal-content">' +
                    '		<div class="modal-header bg-light-blue">' +
                    '			<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only"><?php echo _("Chiudi") ?></span></button>' +
                    '			<h4 class="modal-title"><i class="fa fa-pencil"></i> ' + title + '</h4>' +
                    '		</div>' +
                    '		<div class="modal-body">' + data + '</div>'
                );
                if (init_modal == 1) {
                    $(id).modal('show');
                }
            }
        });
    }
}


//Datatable
function start_datatables() {
    var scroll = $(window).height() - $('.main-footer').height() - $('.nav-tabs-custom').height() - parseInt($('.nav-tabs-custom').css('margin-bottom'))*10 - $("#widget-controller_top").height();
    if(scroll < 300) scroll = 300;

    //Controlla che la tabella non sia giĆ  inizializzata
    if(!$.fn.DataTable.isDataTable('#main-records')){
        //Parametri di ricerca da url o sessione
        var search = getUrlVars();
<?php
$array = array();
if(isset($_SESSION['id_module'])){
    foreach($_SESSION as $idx1 => $arr2){
        if( $idx1 == "module_".$_SESSION['id_module'] ){
            foreach( $arr2 as $field => $value ){
                if( $value != '' ){
                    $field_name = str_replace( "search_", "", $field );
                    echo '
            if(search["search_'.str_replace("__", "_", $field_name).'"] == undefined) {
                search.push("search_'.str_replace("__", "_", $field_name).'");
                search["search_'.str_replace("__", "_", $field_name).'"] = "'.$value.'";
            }';
                }
            }
        }
    }
}
?>
        var res = [];
        $("#main-records th").each(function(){
            var id = $(this).attr('id').replace("th_", "");
            var done = false;
            search.forEach(function(item, index, array){
                if(item == "search_"+id.replace("__", "_")) {
                    res.push({ "sSearch" : array[item] });
                    done = true;
                }
            });
            if(!done) res.push({ "sSearch" : "" });
        });
 var sum;
        var id_module = $('#main-records').data('idmodule');
        var table = $("#main-records").DataTable({
            language: {
                url: "<?php echo $js ?>/i18n/datatables/jquery.datatables.lang-<?php echo $lang ?>.min.js"
            },
            autoWidth: true,
            dom: "ti",
            serverSide: true,
            ordering: true,
            searching: true,
            aaSorting: [],
            aoSearchCols: res,
            scrollY: scroll,
            scrollX: '100%',
            scroller: {
                loadingIndicator: true
            },
            ajax: {
                url: "ajax_dataload.php?id_module="+id_module,
                type: 'GET',
                dataSrc: function(data){
                    sum = data;
                    return data.data;
                }
            },
            initComplete: function() {
                this.api().columns('.search').every( function () {
                    var column = this;
                    $("<br><input type='text' class='form-control' placeholder='<?php echo _("Filtra") ?>...'><i class='deleteicon fa fa-times fa-2x hide'></i>")
                        .appendTo(column.header())
                        .on( 'keyup change', function (e) {
                            if (e.which != 9) {
                                if ($(this).val() == '') {
                                    if($(this).parent().data("slow") != undefined) $("#slow").remove();
                                    $(this).removeClass('input-searching');
                                    $(this).next('.deleteicon').addClass('hide');
                                }
                                else {
                                    if($(this).parent().data("slow") != undefined && $("#slow").length == 0){
                                        $("#main-records_info").parent().append('<span class="text-danger" id="slow"><i class="fa fa-refresh fa-spin"></i> <?php echo _("La ricerca potrebbe richiedere del tempo."); ?></span>');
                                    }
                                    $(this).addClass('input-searching');
                                    $(this).next('.deleteicon').removeClass('hide');
                                }
                            }

                            idx1 = 'module_'+( $('#main-records').data('idmodule') );
                            idx2 = 'search_'+( $(this).parent().attr('id') ).replace('th_', '');

                            //Imposto delle sessioni per le ricerche del modulo e del campo specificatsi
                            session_set( idx1+','+idx2, $(this).val(), 0 );

                            column
                                .search(this.value)
                                .draw();
                    });
                });

                //Disabilito l'ordinamento al click sull'<input>
                $("thead input, .deleteicon").click(function(e) {
                    stopTableSorting(e);
                });

                $('.deleteicon').on("click", function(e) {
                    reset($(this).parent().attr("id").replace("th_", ""));
                });

                //Se ho impostato una ricerca da URL filtro quei campi, altrimenti uso i campi della sessione
                getUrlVars().forEach(function(item, index, arr) {
                    $('#th_'+item.replace("search_", "").replace("_", "__")+' input').val(arr[item]).trigger('keyup');
                });

<?php
if(isset($_SESSION['id_module'])){
    foreach( $_SESSION as $idx1 => $arr2 ){
        if( $idx1 == "module_".$_SESSION['id_module'] ){
            foreach( $arr2 as $field => $value ){
                if( $value != '' ){
                    $field_name = str_replace( "search_", "", $field );
                    echo "
                    if($('#th_".$field_name." input').val() == '') $('#th_".$field_name." input').val( \"".$value."\" ).trigger('keyup');\n";
                }
            }
        }
    }
}
?>
            },
            drawCallback: function(){
                $(".dataTables_sizing .deleteicon").addClass('hide');

                $("[data-background]").each(function(){
                    $(this).parent().css("background", $(this).data("background"));
                });

                $("[data-link]").each(function(){
                    $(this).parent().not('.bound').addClass('bound').click(function(event) {
                        if (event.ctrlKey) {
                            window.open($(this).find("[data-link]").data('link'));
                        } else {
                            location.href = $(this).find("[data-link]").data('link');
                        }
                    });
                    $(this).parent().addClass("clickable");
                });

                $("[data-color]").each(function(){
                    $(this).parent().css("color", $(this).data("color"));
                });
            },
            footerCallback: function ( row, data, start, end, display ) {
                var i =0;
                this.api().columns().every( function () {
                    if(sum.summable[i] != undefined){
                        $(this.footer()).addClass("text-right");
                        $(this.footer()).html(sum.summable[i]);
                    }
                    else $(this.footer()).html("&nbsp;");
                    i++;
                });
            }
        });
    }
}

//Select
function start_superselect(){
    //Statico
	$('.superselect').each( function(){
		$this = $(this);
		$(this).select2({
            theme: "bootstrap",
			language: "it",
   			width: '100%',
   			allowClear: true,
   			escapeMarkup: function (text) { return text; }
		});
	});

    //Dinamico (AJAX, per tabelle con molti record)
	$('.superselectajax').each( function(){
		$this = $(this);
		$(this).select2({
            theme: "bootstrap",
			language: "it",
			allowClear: true,
			escapeMarkup: function (text) { return text; },
			ajax: {
		        url: "<?php echo $rootdir ?>/ajax_select2.php?op=" + $this.data('source'),
		        dataType: 'json',
		        delay: 250,
		        data: function (params) {
		            return {
		                q: params.term // search term
		            }
		        },
		        processResults: function (data) {
		            // parse the results into the format expected by Select2.
		            // since we are using custom formatting functions we do not need to
		            // alter the remote JSON data
					if($this.val() == "" || $this.val() == null){
						data.forEach(function (item, index){
							if(item.selected != undefined && item.selected != ""){
								$this.append('<option value="' + item.id + '">' + item.text + '</option>').val(item.id).trigger('change');
							}
						});
					}
					return {
		                results: data
		            }
		        },
		        cache: false
		    },
   			width: '100%'
		});
	});

    $(".select2-selection__rendered").attr("title", "");
}


/**
  * Aggiorna un <select> creato con select2 impostando un valore di default
  */
function set_default_select( dst_obj, option_value, option_label ){
	$(dst_obj).find('option').remove();
	$(dst_obj).append('<option>');
	$option = $(dst_obj).find('option');
	$option.val( option_value );
	$option.html( option_label );
	$option.prop('selected', true);
}

/**
  * Ottengo l'object corretto per leggere gli attributi di una <option> generata da select2 (viene generata in 2 modi diversi!)
  */
function select2_get_data( obj, item ){
	$select_obj = obj.select2('data');

	if( $select_obj[0] == undefined ){
		return undefined;
	} else {
		if( $select_obj[0].selected == false ){
			return $select_obj[0];
		} else {
			return $select_obj[0].element.dataset;
		}
	}
}


//Inputmask
function start_inputmask() {
    //Inizializzazione cifre decimali a X decimali
    $inputmasks = $('.inputmask-decimal');

    var decimali = <?php echo get_var("Cifre decimali"); ?>;

    for (i = 0; i < $inputmasks.length; i++) {
        $inputmask = jQuery($inputmasks[i]);

        new_value = $inputmask.val().replace(',', '.');
        new_value = parseFloat(new_value);
        new_value = new_value.toFixed(decimali);
        new_value = new_value.replace('.', ',');
        $inputmask.val(new_value);
    }

    //Input mask
    if (isMobile.any()) {
        $('.inputmask-decimal, .inputmask-integer').each(function() {
            val = $(this).val();
            val = val.replace(',', '.');
            $(this).attr('type', 'tel').val(val);
        });
    } else {
        $(".date-mask").inputmask("dd/mm/yyyy", {
            "placeholder": "dd/mm/yyyy"
        });
        $("[data-mask]").inputmask();
        $('.inputmask-decimal').inputmask("decimal", {
            "radixPoint": ",",
            "digits": decimali
        });
        $('.inputmask-integer').inputmask("decimal", {
            "radixPoint": ",",
            "digits": 0
        });
    }
}

function start_timepicker() {
    $(".time-mask").timepicker({
        minuteStep: 5,
        showInputs: false,
        disableFocus: true,
        showMeridian: false,
        defaultTime: false
    }).on('show.timepicker', function(e) {
        $(".glyphicon-chevron-up").removeClass("glyphicon glyphicon-chevron-up").addClass("fa fa-chevron-up");
        $(".glyphicon-chevron-down").removeClass("glyphicon glyphicon-chevron-down").addClass("fa fa-chevron-down");
    });
}
/*
	Funzione per far scrollare la pagina fino a un id + focus e offset
	es: ScrollToAndFocus ('id',0,'','Attenzione');
*/
function ScrollToAndFocus(id, offset, focus, messaggio) {
    $('html,body').animate({
        scrollTop: $('#' + id).offset().top + offset
    }, 'slow', function() {
        if (messaggio != '') {
            alert(messaggio);
            messaggio = '';
        };
        if (focus != '') {
            $('#' + focus).focus();
        }
    });
}

function session_keep_alive() {
    $.get('<?php echo $rootdir; ?>/core.php');
};

function force_decimal(n) {
    n = n.replace( ":", "." );
    n = n.replace(",", ".");
    return parseFloat(n);
}

/**
 * Ritorna il numero n come decimale con la virgola al posto del punto
 */
function decimals_with_commas(n, n_decimals) {
    n = parseFloat(n);
    n = n.toFixed(n_decimals);
    n = n.toString();
    n = n.replace('.', ',');

    return n;
}

/**
 * Ritorna un array associativo con i parametri passati via GET
 */
function getUrlVars(url = '') {
    var vars = [],
        hash;
    if (url == '')
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    else
        var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }

    return vars;
}

/*
	Data e ora aggiornate
*/
function clock() {
    var now = new Date();
    now.getHours() < 10 ? h = "0" + now.getHours() : h = now.getHours();
    now.getMinutes() < 10 ? m = "0" + now.getMinutes() : m = now.getMinutes();
    now.getSeconds() < 10 ? s = "0" + now.getSeconds() : s = now.getSeconds();
    now.getDate() < 10 ? dd = "0" + now.getDate() : dd = now.getDate();
    (now.getMonth() + 1) < 10 ? mm = "0" + (now.getMonth() + 1) : mm = (now.getMonth() + 1);
    yy = now.getFullYear();

    var outStr = dd + '/' + mm + '/' + yy + ' ' + h + ':' + m + ':' + s;
    $('#datetime').html(outStr);
    setTimeout('clock()', 1000);
}

function stopTableSorting(e) {
    if (!e) var e = window.event
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
}

/**
 * Funzione per impostare un valore ad un array in $_SESSION
 */
function session_set_array(session_array, value, inversed) {
    if (inversed == undefined) {
        inversed = 1;
    }

    $.get("<?php echo $rootdir ?>/ajax.php?op=session_set_array&session=" + session_array + "&value=" + value + "&inversed=" + inversed);
}

/**
 * Funzione per impostare un valore ad una sessione
 */
function session_set(session_array, value, clear) {
    if (clear == undefined) {
        clear = 1;
    }

    $.get("<?php echo $rootdir ?>/ajax.php?op=session_set&session=" + session_array + "&value=" + value + "&clear=" + clear);
}

/**
 * Funzione per gestire i contatori testuali nel formato x/total.
 * Viene dato un id del campo da verificare come input, viene letto il testo nella forma [0-9]/[0-9] e viene fatto
 * il replate del primo numero in base a quanti elementi sono stati trovati (valore passato per parametro)
 */
function update_counter(id, new_value) {
    new_text = $('#' + id).html();

    //Estraggo parte numerica (formato x/total)
    pattern = /([^0-9]+)([0-9]+)\/([0-9]+)([^0-9]+)/;
    new_text = new_text.replace(pattern, "$1" + new_value + "/$3$4");

    //Estraggo totale (parte numerica dopo lo slash /)
    matches = pattern.exec(new_text);
    total = matches[3];

    $('#' + id).html(new_text);

    if (new_value == total) {
        $('#' + id).removeClass('btn-warning').removeClass('btn-danger').addClass('btn-success');
    } else if (new_value == 0) {
        $('#' + id).removeClass('btn-warning').removeClass('btn-success').addClass('btn-danger');
    } else {
        $('#' + id).removeClass('btn-success').removeClass('btn-danger').addClass('btn-warning');
    }
}

function backtotop_button() {
    // browser window scroll (in pixels) after which the "back to top" link is shown
    var offset = 10,

        //browser window scroll (in pixels) after which the "back to top" link opacity is reduced
        offset_opacity = 100,

        //duration of the top scrolling animation (in ms)
        scroll_top_duration = 700,

        //grab the "back to top" link
        $back_to_top = $('#back-to-top');

    //hide or show the "back to top" link
    $(window).scroll(function() {
        ($(this).scrollTop() > offset) ? $back_to_top.addClass('cd-is-visible'): $back_to_top.removeClass('cd-is-visible cd-fade-out');
        if ($(this).scrollTop() > offset_opacity) {
            $back_to_top.addClass('cd-fade-out');
        }
    });

    //smooth scroll to top
    $back_to_top.on('click', function(event) {
        event.preventDefault();
        $('body,html').animate({
            scrollTop: 0,
        }, scroll_top_duration);
    });
}

Number.prototype.formatMoney = function(c, d, t) {
    var n = this,
        c = isNaN(c = Math.abs(c)) ? 2 : c,
        d = d == undefined ? "." : d,
        t = t == undefined ? "," : t,
        s = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;

    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function reset(type = ''){
    if(type == '') $('[id^=th_] input').val('').trigger( 'keyup' );
    else $('[id^=th_'+type+'] input').val('').trigger( 'keyup' );
}

function equalHeight(selector){
    $(selector).css("min-height", 0);

    var maxHeight = 0;
    $(selector).each(function(){
        var thisH = $(this).outerHeight();
        if (thisH > maxHeight) { maxHeight = thisH; }
    });

    $(selector).css("min-height", maxHeight);

    $(window).on("resize", function(){
        equalHeight(selector);
    });
}
<?php
}
?>