'use strict';
/******************** PARAMETRI ******************************/
const BASE_URL_SITE = $('link[rel="canonical"]').attr('href');
var modal_id = '#modal';
var form_id = '#' + $(modal_id).attr('data-form');
var form = $(form_id);
var filter_modal_id = '#filterModal';
var filter_form_id = '#' + $(filter_modal_id).attr('data-form');
var filter_form = $(filter_form_id);
var modalLoader = $('#modal-loader');
/*********************************************************************************/
/**** FUNZIONI GLOBALI PERSONALIZZATE ***/
const defaultDatePickerOptions = {
language: 'it',
format: "dd/mm/yyyy",
autoclose: true
};
const defaultDateRangePickerOptions = {
autoApply: false,
autoUpdateInput: false,
linkedCalendars: false,
showCustomRangeLabel: false,
locale: {
"format": "DD/MM/YYYY",
"separator": " | ",
"applyLabel": "Ok",
"cancelLabel": "Reset",
"fromLabel": "Da",
"toLabel": "A",
"customRangeLabel": "Custom",
"weekLabel": "W",
"daysOfWeek": [
"Dom",
"Lun",
"Mar",
"Mer",
"Gio",
"Ven",
"Sab"
],
"monthNames": [
"Gennaio",
"Febbraio",
"Marzo",
"Aprile",
"Maggio",
"Giugno",
"Luglio",
"Agosto",
"Settembre",
"Ottobre",
"Novembre",
"Dicembre"
],
"firstDay": 1
},
alwaysShowCalendars: true,
ranges: {
'Oggi': [moment(), moment()],
'Ieri': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Ultimi 7 gg': [moment().subtract(6, 'days'), moment()],
'Ultimi 30 gg': [moment().subtract(29, 'days'), moment()],
'Questo Mese': [moment().startOf('month'), moment().endOf('month')],
'Mese Scorso': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
}
};
let $table;
String.prototype.capitalize = function () {
return this.charAt(0).toUpperCase() + this.slice(1)
}
$('a[href="#"]').click(function (event) {
event.preventDefault();
});
$('a[data-widget="pushmenu"]').click(function () {
let collapsed = ($('body').hasClass('sidebar-collapse')) ? 0 : 1;
$.cookie('ui_sidebar_collapsed', collapsed, {path: '/'});
if (collapsed) {
$table.trigger('reflow');
}
});
/****************************************
************* SEZIONE FORM *************
***************************************/
function populateForm(data, frm) {
$.each(data, function (key, value) {
var $ctrl = $('[name=' + key + ']', frm);
if ($ctrl.is('select')) {
$("option", $ctrl).each(function () {
if (this.value == value) {
this.selected = true;
}
});
} else {
switch ($ctrl.attr("type")) {
case "text":
case "hidden":
case "number":
$ctrl.val(value);
break;
case "textarea":
$ctrl.val(value);
break;
case "radio":
case "checkbox":
$ctrl.each(function () {
if ($(this).attr('id') == key && value == '1') {
$(this).iCheck('check');
}
});
break;
default:
$ctrl.val(value);
break;
}
}
});
$('input.datepicker').datepicker('update');
}
function resetForm(tipo, form_id) {
$(form_id + ' #ErrorDescription').html('').addClass('d-none');
$(form_id + ' div.form-group').removeClass('has-error');
$(form_id + ' div.multi-line-field-label-error').removeClass('has-error');
$(form_id + ' div.label-danger').addClass('d-none').html('');
if (tipo != 'errors') {
$(form_id).clearForm();
}
}
function getErrorHtml(formErrors, noBr) {
if ((typeof (formErrors) === 'undefined') || (formErrors.length < 1)) return;
noBr = (typeof (noBr) === 'undefined') ? false : noBr;
var out = '';
let brtxt = (noBr) ? '' : '
';
for (let errorKey in formErrors) {
out += (formErrors[errorKey] + brtxt);
}
return out;
}
function showErrors(form_id, resp) {
resetForm('errors', form_id);
//$(form_id + ' #ErrorDescription').html(resp.message).removeClass('d-none');
toastr.error(resp.message);
for (let key in resp.errors) {
let errBlock = $(form_id + ' div#' + key);
let labelBlock = $(form_id + ' div#' + key + ' .label-danger');
errBlock.addClass('has-error');
if (labelBlock.length === 0) {
labelBlock = errBlock.parent().children(' .label-danger');
labelBlock.html(labelBlock.html() + ' | ' + getErrorHtml(resp.errors[key], true));
labelBlock.removeClass('d-none');
} else {
labelBlock.html(getErrorHtml(resp.errors[key])).removeClass('d-none');
}
}
}
function initDatePicker() {
$('.datepicker').datepicker(defaultDatePickerOptions);
}
function initDateRangePicker(customRange) {
let dateRangePickerOptions = defaultDateRangePickerOptions;
if (customRange) {
dateRangePickerOptions.ranges = customRange;
}
$('input[daterangepicker]').daterangepicker(dateRangePickerOptions);
$('input[daterangepicker]').on('apply.daterangepicker', function (ev, picker) {
$(this).val(picker.startDate.format('DD/MM/YYYY') + ' | ' + picker.endDate.format('DD/MM/YYYY'));
});
$('input[daterangepicker]').on('cancel.daterangepicker', function (ev, picker) {
$(this).val('');
});
}
function initSwitchButton() {
//Abilita gli swithc button
$("input[data-bootstrap-switch]").each(function () {
$(this).bootstrapSwitch('state', $(this).prop('checked'));
});
}
function initICheck() {
var tableBody = $('#tablebody');
$('#select_all').click(function (link) {
link.preventDefault();
tableBody.find(':checkbox').iCheck('check');
});
$('#deselect_all').click(function (link) {
link.preventDefault();
tableBody.find(':checkbox').iCheck('uncheck');
});
$('#invert_all').click(function (link) {
link.preventDefault();
tableBody.find(':checkbox').iCheck('toggle');
});
}
function initTooltip() {
$('[data-toggle="tooltip"]').tooltip();
}
function initPopover() {
$('[data-toggle="popover"]').popover();
}
function initSummernote() {
$('.summernote').summernote({
dialogsInBody: true
});
}
function initSelect2(){
$('select[select2]').select2();
}
/*function initFontIconPicker(options){
$('[font-icon-picker]').fontIconPicker(options);
}*/
function refreshFormComponents() {
$("input[type='checkbox'], input[type='radio']").not(".no-icheck").iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue'
});
initTooltip();
initPopover();
}
function initFormComponents() {
refreshFormComponents();
initICheck();
initSwitchButton();
initDatePicker();
initDateRangePicker();
}
$(document).ready(() => {
setOrderThValue();
fixHeghtOfTableList();
}).delegate('a[href="#"]', 'click', function (link) {
link.preventDefault();
})
.delegate('#filterData', 'click', function (link) {
link.preventDefault();
$(filter_modal_id).modal('show');
})
.delegate('#filtra', 'click', function (link) {
link.preventDefault();
filter_form.submit();
})
.delegate('#resetFiltri', 'click', function (link) {
link.preventDefault();
filter_form.clearForm();
filter_form.find('select').val('');
})
.delegate('th[data-ord]', 'click', function (link) {
link.preventDefault();
const ordVal = $(this).attr('data-ord');
const tipoOrderEl = $('#tipoOrder');
const tipoOrder = (tipoOrderEl.val() === 'ASC') ? 'DESC' : 'ASC';
$('#order').val(ordVal);
tipoOrderEl.val(tipoOrder);
$('#searchForm').submit();
})
.delegate('select[data-refresh-search-form]', 'change', function (link) {
link.preventDefault();
$('#searchForm').submit();
})
/*******************************************
************* SEZIONE TABELLA *************
******************************************/
function setOrderThValue() {
const ordVal = $('#order').val();
const tipoOrd = $('#tipoOrder').val();
$('th[data-ord]').find('i').remove();
const thOrd = $('th[data-ord="' + ordVal + '"]');
const icon = (tipoOrd === 'ASC') ? 'fa-chevron-up' : 'fa-chevron-down';
const iconText = ``;
thOrd.find('i').remove();
const thText = thOrd.html() + ' ' + iconText;
thOrd.html(thText);
}
function initTableFlotHeader() {
//Abilito l'header fisso
$table = $('.table.flot-header');
$table.floatThead({
autoReflow: true,
scrollContainer: function ($table) {
return $table.closest('.table-wrapper');
},
responsiveContainer: function ($table) {
return $table.closest('.table-responsive');
}
});
//Imposta l'altezza del table-wrapper
fixHeghtOfTableList();
}
function refreshTable() {
if ($table) {
fixHeghtOfTableList();
}
}
function fixHeghtOfTableList() {
let windowHeight = $(window).height();
let navbarHeight = $(".navbar").outerHeight() || 0;
let footerHeight = $(".main-footer").outerHeight() || 0;
let contentHeaderHeight = $(".content-header").outerHeight() || 0;
let boxHeaderHeight = $(".box-header").outerHeight() || 0;
let boxFooterHeight = $(".box-footer").outerHeight() || 0;
let tableWrapperHeight = windowHeight - (navbarHeight + footerHeight + contentHeaderHeight + boxHeaderHeight + boxFooterHeight + 15);
$('.table-wrapper').css("height", tableWrapperHeight + "px");
let theadHeight = $('.table-wrapper thead').outerHeight() + 1;
const totHeight = tableWrapperHeight - theadHeight;
$('td.no-rows').css("height", (totHeight) + "px");
}
$(window).resize(function () {
fixHeghtOfTableList();
$table.trigger('reflow');
});
/**************************************************
************* FUNZIONI SPECIALIZZATE *************
*************************************************/
function password_generator(len) {
let length = (len) ? (len) : (10);
let string = "abcdefghijklmnopqrstuvwxyz"; //to upper
let numeric = '0123456789';
let punctuation = '!@#$%^&*()_+~`|}{[]\:;?><,./-=';
let password = "";
let character = "";
let crunch = true;
while (password.length < length) {
let entity1 = Math.ceil(string.length * Math.random() * Math.random());
let entity2 = Math.ceil(numeric.length * Math.random() * Math.random());
let entity3 = Math.ceil(punctuation.length * Math.random() * Math.random());
let hold = string.charAt(entity1);
hold = (entity1 % 2 == 0) ? (hold.toUpperCase()) : (hold);
character += hold;
character += numeric.charAt(entity2);
character += punctuation.charAt(entity3);
password = character;
}
return password;
}
function copyToClipboard(elem) {
// create hidden text element, if it doesn't already exist
var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
// can just use the original source element for the selection and copy
target = elem;
origSelectionStart = elem.selectionStart;
origSelectionEnd = elem.selectionEnd;
} else {
// must use a temporary form element for the selection and copy
target = document.getElementById(targetId);
if (!target) {
var target = document.createElement("textarea");
target.style.position = "absolute";
target.style.left = "-9999px";
target.style.top = "0";
target.id = targetId;
document.body.appendChild(target);
}
target.textContent = elem.textContent;
}
// select the content
var currentFocus = document.activeElement;
target.focus();
target.setSelectionRange(0, target.value.length);
// copy the selection
var succeed;
try {
succeed = document.execCommand("copy");
} catch (e) {
succeed = false;
}
// restore original focus
if (currentFocus && typeof currentFocus.focus === "function") {
currentFocus.focus();
}
if (isInput) {
// restore prior selection
elem.setSelectionRange(origSelectionStart, origSelectionEnd);
} else {
// clear temporary content
target.textContent = "";
}
return succeed;
}
/**
* Questa funzione passato un template html ne sostituisce i parametri
* @param template
* @param params
*/
function prepareHTMLWithParams(template, params) {
if (params instanceof Array) {
params.forEach(function (val, key) {
template = template.replace(new RegExp('%' + key + '%', 'g'), val);
});
} else if (params instanceof Object) {
Object.keys(params).forEach(function (key) {
template = template.replace(new RegExp('%' + key + '%', 'g'), params[key]);
});
}
return template;
}
/************************************************************************************
************* SEZIONE FUNZIONI GENRICHE PER LA GESTIONE DELLE IMMAGINI *************
************************************************************************************/
/**
* Questa funzione carica l'immagine nel box anteprima
* @param basePathImage
* @param nomeVaribileFile
* @param valFile
*/
function popolaImmagine(basePathImage, nomeVaribileFile, valFile, custom_class) {
if (custom_class === undefined) {
custom_class = 'img-fluid img-thumbnail';
}
if (valFile) {
$('#preview_block_' + nomeVaribileFile).addClass(custom_class).attr('src', basePathImage + valFile);
$('#image-preview-filename-' + nomeVaribileFile).val(valFile);
$("#image-preview-input-title-" + nomeVaribileFile).text("Cambia");
$("#image-preview-clear-" + nomeVaribileFile).show();
}
}
/**
* Questa funzione resetta il blocco immagine in base al parametro nome File che riceve
* @param nomeVariabileFile
* @param baseImagePath
*/
function resetImageInput(nomeVariabileFile, baseImagePath) {
// $('#preview_block_' + nomeVariabileFile).attr('src', baseImagePath + 'noimage.jpg');
$('#preview_block_' + nomeVariabileFile).attr('src', baseImagePath + 'no_img.png');
$('#image-preview-filename-' + nomeVariabileFile).val('');
$('#image-preview-clear-' + nomeVariabileFile).hide();
$('#image-preview-input-title-' + nomeVariabileFile).html('Carica ...');
var input_file = $('input#image_' + nomeVariabileFile);
input_file.replaceWith(input_file.val('').clone(true));
}
/**
* Questa funzione definisce gli event handler per il nome immagine che riceve in entrata
*
* @param nome_immagine
* @param base_image_path
* @param custom_class [default value: img-fluid img-thumbnail']
* @param custom_style [default value: '']
*
* '?' sta a indicare la Varibile NomeFile che si passa, dovrebbe corrispondere al nome del campo immagine
* image-preview-clear-? = Identificativo del pulsante "Cancella"
* image-preview-input-title-? = Identifica il testo del pusante "Scegli..." o "Cambia"
* image-preview-input-? = Identificativo del input di tipo FILE dove andra dell'immagine
* image-preview-filename-? = Identificativo dell'input che contiene il nome del file immagine caricato
* image_preview_block_? = Identificativo del blocco che contiene l'html con il tag
* preview_block_? = Identificatico dell'elemento immagine per visualizzare l'anteprima
*/
function defineEventHandlerForImageBlock(nome_immagine, base_image_path, custom_class, custom_style) {
if (custom_class === undefined) {
custom_class = 'img-fluid img-thumbnail';
}
if (custom_style === undefined) {
custom_style = '';
}
//Evento click pulsante cancella
$('#image-preview-clear-' + nome_immagine).click(function () {
resetImageInput(nome_immagine, base_image_path);
});
//Evento che al caricamento dell'immgaine ne crea il blocco anteprima
$("#image-preview-input-" + nome_immagine + " input:file").change(function () {
let img = $('
', {
id: 'preview_block_' + nome_immagine,
class: custom_class,
style: custom_style
});
let nome_file_1 = this.files[0];
let reader_file_1 = new FileReader();
// Set preview image into the popover data-content
reader_file_1.onload = function (e) {
$("#image-preview-input-title-" + nome_immagine).text("Cambia");
$("#image-preview-clear-" + nome_immagine).show();
$("#image-preview-filename-" + nome_immagine).val(nome_file_1.name);
img.attr('src', e.target.result);
$("#image_preview_block_" + nome_immagine).html($(img)[0].outerHTML);
};
reader_file_1.readAsDataURL(nome_file_1);
});
}