/* 
**  
**  INAIL - Webkit 6.1.0
** 
*/


$(window).on('load', function () {
	//RIMUOVO UL AUTOCOMPLETE DI JQUERY UI - Causa errore W3C
	$('ul#ui-id-1, .ui-helper-hidden-accessible').remove();

	//RIMUOO ARIA-HIDDEN TRUE DALLE FRECCE DEL WIZARD
	$('.slick-prev, .slick-next').removeAttr('aria-hidden');
});

$(document).ready(function () {

	  $('.inail-skip-link').on('click', function(e) {
  e.preventDefault();
  const targetSelector = $(this).data('target');
  const $target = $(targetSelector);
  if ($target.length) {
    if (!$target.is(':focusable')) {
      $target.attr('tabindex', '-1');
    }
    $target.get(0).scrollIntoView({ behavior: 'smooth' });
    $target.focus();
  }
});

	// // Funzione per mettere il focus sul menu
	// function focusOnMenu() {
	// 	const target = $('#trigger-slider-menu-hamburger');
	// 	if (target.length) {
	// 		target.attr('tabindex', '-1'); // assicura che l'elemento sia focusable
	// 		target.focus();
	// 	}
	// }

	// // Collega il click e keyup ai link
	// $('#skip-link-1').on('click keyup', function (e) {
	// 	console.log('entro?')
	// 	if (e.type === 'click' || e.key === 'Enter') {
	// 		e.preventDefault();
	// 		focusOnMenu();
	// 	}
	// });




	//TOOLTIP ACCESSIBILI DA TASTIERA
	$(function () {
		$('[data-toggle="tooltip"]').tooltip();
	})

	$('a.iconaNotifica').on('keydown', function (event) {
		var modaleDaAprire = $(this).find('span.fa').attr('data-target');

		if (event.keyCode === 13) {

			$(modaleDaAprire).modal('show');
		}
	});

	//CAROUSEL - Sposta focus su elemento attivo quando si scorre con le frecce (uso da tastiera)
	$('.carousel-control').click(function () {

		var selettoreCarousel = $(this).parent().parent().attr('id');
		$('#' + selettoreCarousel).focus();


	});

	//CORREZIONE TAB - Lettura aperto/chiuso da screen reader
	$('a[data-toggle="pill"]').click(function () {
		$(this).parent().parent().find('a[data-toggle="pill"]').attr('aria-expanded', 'false');
		$(this).attr('aria-expanded', 'true');
	});


	//Chiudo popover alla perdita del focus
	$('a[data-toggle="popover"], button[data-toggle="popover"]').focusout(function () {
		$(this).click();
		$('.popover').popover('hide');
	});
	$('a[data-toggle="popover"], button[data-toggle="popover"]').on('inserted.bs.popover', function () {
		$(this).parent().find('.popover').attr('aria-live', 'assertive')
	})

	//----------GESTIONE TOOLTIP POPOVER----------//
	// Selettore per tutti gli elementi con popover
	const popoverSelector = '[data-toggle="popover"]';
	// Mappa per tracciare lo stato dei popover
	const popoverStates = new WeakMap();
	// Funzione per verificare se un popover è visibile
	function isPopoverVisible($element) {
		const describedBy = $element.attr('aria-describedby');
		if (!describedBy) return false;

		const $popover = $('.popover[id="' + describedBy + '"]');
		return $popover.length > 0 && $popover.is(':visible');
	}

	// Funzione per mostrare il popover
	function showPopover($element, source = 'unknown') {
		$element.popover('show');
		$element.attr('aria-expanded', 'true');

		// Aggiorna lo stato
		const state = popoverStates.get($element[0]) || {};
		state.isVisible = true;
		state.lastAction = 'show';
		state.lastSource = source;
		popoverStates.set($element[0], state);
	}

	// Funzione per nascondere il popover
	function hidePopover($element, source = 'unknown') {
		$element.popover('hide');
		$element.attr('aria-expanded', 'false');

		// Aggiorna lo stato
		const state = popoverStates.get($element[0]) || {};
		state.isVisible = false;
		state.lastAction = 'hide';
		state.lastSource = source;
		popoverStates.set($element[0], state);
	}

	// Funzione per applicare gli handler ai popover
	function initPopoverHandlers() {
		// Rimuovo eventuali handler esistenti per evitare duplicati
		$(popoverSelector).off('focus.popover focusout.popover keydown.popover click.popover mousedown.popover');

		// Inizializza lo stato per ogni elemento
		$(popoverSelector).each(function () {
			if (!popoverStates.has(this)) {
				popoverStates.set(this, {
					isVisible: false,
					lastAction: null,
					lastSource: null,
					focusTimestamp: null,
					clickTimestamp: null
				});
			}
		});

		// Gestione focus - mostra automaticamente
		$(popoverSelector).on('focus.popover', function (e) {
			const $element = $(this);
			const state = popoverStates.get(this);

			state.focusTimestamp = Date.now();
			state.hasFocus = true;
			// Mostra il popover solo se non è già visibile
			if (!isPopoverVisible($element)) {
				showPopover($element, 'focus');
			}
		});

		// Gestione perdita focus
		$(popoverSelector).on('focusout.popover', function (e) {
			const $element = $(this);
			const state = popoverStates.get(this);

			state.hasFocus = false;

			

			// Piccolo delay per permettere eventuali click
			setTimeout(() => {
				const currentState = popoverStates.get(this);
				// Nascondi solo se non ha più il focus e non è stato cliccato di recente
				if (!currentState.hasFocus &&
					(!currentState.clickTimestamp || Date.now() - currentState.clickTimestamp > 100)) {
					hidePopover($element, 'focusout');
				}
			}, 150);
		});

		// Gestione mousedown (prima del click) per tracciare l'intenzione
		$(popoverSelector).on('mousedown.popover', function (e) {
			const state = popoverStates.get(this);
			state.mouseDownTimestamp = Date.now();
		});

		// Gestione click
		$(popoverSelector).on('click.popover', function (e) {
			const $element = $(this);
			const state = popoverStates.get(this);

			state.clickTimestamp = Date.now();

			// Se il click avviene subito dopo il focus (entro 200ms), lo ignoriamo
			// per evitare il comportamento di chiudi/riapri
			if (state.focusTimestamp &&
				(state.clickTimestamp - state.focusTimestamp) < 200) {
				return;
			}

			// Toggle del popover
			if (isPopoverVisible($element)) {
				hidePopover($element, 'click');
			} else {
				showPopover($element, 'click');
			}
		});

		// Gestione tastiera per spazio ed enter
		$(popoverSelector).on('keydown.popover', function (e) {
			// Spazio (32) o Enter (13)
			if (e.which === 32 || e.which === 13) {
				e.preventDefault();

				const $element = $(this);


				// Toggle del popover
				if (isPopoverVisible($element)) {
					hidePopover($element, 'keyboard');
				} else {
					showPopover($element, 'keyboard');
				}
			}
		});
	}

	// Funzione per chiudere tutti i popover aperti (utile per ESC o click esterno)
	function closeAllPopovers() {
		$(popoverSelector).each(function () {
			const $element = $(this);
			if (isPopoverVisible($element)) {
				hidePopover($element, 'closeAll');
			}
		});
	}

	// Chiudi popover quando si preme ESC
	$(document).on('keydown', function (e) {
		if (e.which === 27) { // ESC
			closeAllPopovers();
		}
	});

	// Chiudi popover quando si clicca fuori (opzionale)
	$(document).on('click', function (e) {
		// Se il click non è su un elemento popover o sul popover stesso
		if (!$(e.target).closest(popoverSelector).length &&
			!$(e.target).closest('.popover').length) {
			closeAllPopovers();
		}
	});

	// Inizializza al caricamento della pagina
	$(document).ready(function () {
		initPopoverHandlers();
	});

	// Re-inizializza quando il DOM cambia (per i cambi di componente)
	let popoverObserver = new MutationObserver(function (mutations) {
		let shouldReinit = false;

		mutations.forEach(function (mutation) {
			if (mutation.type === 'childList') {
				// Controlla se sono stati aggiunti nuovi elementi con popover
				mutation.addedNodes.forEach(function (node) {
					if (node.nodeType === 1) { // Element node
						if ($(node).find(popoverSelector).length > 0 || $(node).is(popoverSelector)) {
							shouldReinit = true;
						}
					}
				});
			}
		});

		if (shouldReinit) {
			// Piccolo delay per assicurarsi che il DOM sia completamente aggiornato
			setTimeout(initPopoverHandlers, 50);
		}
	});

	// Osserva i cambiamenti nel DOM
	popoverObserver.observe(document.body, {
		childList: true,
		subtree: true
	});

	//----------FINE GESTIONE POPOVER----------//

	//Colore value di default per il campo data
	$('.datePicker label input').each(function () {
		var isDefault = $(this).val();
		if (isDefault == "GG/MM/AAAA") {
			$(this).css('color', '#999');
		}
	});

	$('body').on('click', function (e) {
		$('[data-toggle="popover"]').each(function () {
			//the 'is' for buttons that trigger popups
			//the 'has' for icons within a button that triggers a popup
			if (!$(this).is(e.target) && $(this).has(e.target).length === 0 &&
				$('.popover').has(e.target).length === 0) {
				$(this).popover('hide');
			}
		});
	});

	/* Accordion Gray toggle */
	$(function () {
		$('.accordion-gray .panel-body.collapse').on('hide.bs.collapse', function () {

			$(this).prev(".head-accordion-gray").find(".fa-minus-circle").toggleClass("fa-minus-circle").toggleClass("fa-plus-circle");
		})
		$('.accordion-gray .panel-body.collapse').on('show.bs.collapse', function () {

			$(this).prev(".head-accordion-gray").find(".fa-plus-circle").toggleClass("fa-minus-circle").toggleClass("fa-plus-circle");
		})
	})


	/* Popover form help icon */
	$('[data-toggle="popover"]').popover();

	/* Textbox count characters */
	var remainingCharList = $('div.remainingChar');
	$.each(remainingCharList, function (index, value) {
		$(value).html(function () {
			try {
				var textArea = $(value).parents('.form-group ').find('textarea');
				var max = $(textArea).attr("maxlength");
				var currentChars = $(textArea).val().length;
				var charsLeft = ((max - currentChars) > -1) ? (max - currentChars) : "sotto zro0";
				$(value).html(function () {
					return "<strong>" + charsLeft + "</strong> caratteri disponibili";
				});
			}
			catch (e) { }
		})
	})

	$('textarea[maxlength]').keyup(function () {
		var maxLength = $(this).attr("maxlength")
		var length = $(this).val().length;
		var length = maxLength - length;

		if (Modernizr.flexbox == false) { // <-- solo IE9
			var text = $(this).val();
			if (text.length > maxLength) {
				$(this).val(text.substr(0, maxLength));
			}
		}
		if (length >= 0) {
			$(this).siblings("div.remainingChar").html(function () {
				return "<strong>" + length + "</strong> caratteri disponibili";
			});
		}
	});

	$('button:reset, input:reset').click(function () {
		var remainingCharList = $(this).parents('form').find('div.remainingChar');
		$.each(remainingCharList, function (index, value) {
			$(value).html(function () {
				return "<strong>" + $(value).parents('.form-group ').find('textarea').attr('maxlength') + "</strong> caratteri disponibili";
			})
		})
	});


	/* Reset file upload fields */
	$("input .reset").click(function () {
		$(this).siblings("input").val("");
	});

	/*Attiva datepicker*/
	$(".datePicker .fa.fa-calendar").click(function () {
		$(this).prev().focus();
	});




	/* Freccia Accordion */
	/* Form */
	$(function () {
		$('.form-accordion .collapse').on('hide.bs.collapse', function () {
			$(this).parent().find(".formAccordionBtn").removeClass("fa-chevron-up").addClass("fa-chevron-down");
		})
		$('.form-accordion .collapse').on('show.bs.collapse', function () {
			$(this).parent().find(".formAccordionBtn").removeClass("fa-chevron-down").addClass("fa-chevron-up");
		})
	})



	/* Filtri */
	$(function () {
		$('.filter-accordion .collapse').on('hide.bs.collapse', function () {

			$(this).prev(".panel-heading").children(".fa-chevron-up").toggleClass("fa-chevron-up").toggleClass("fa-chevron-down");
		})
		$('.filter-accordion .collapse').on('show.bs.collapse', function () {

			$(this).prev(".panel-heading").children(".fa-chevron-down").toggleClass("fa-chevron-down").toggleClass("fa-chevron-up");
		})
	})



	/* FINE Freccia Accordion */

	/*START_FILE_UPLOADER*/
/* START_FILE_UPLOADER */
const uploaderState = new Map();
const file1 = { id: 'f1', label: 'nome-file-01.pdf', fileSizeString: '0.5 MB', fileSize: 0.5 };
const file2 = { id: 'f2', label: 'nome-file-02.pdf', fileSizeString: '0.3 MB', fileSize: 0.3 };
const file3 = { id: 'f3', label: 'nome-file-03.pdf', fileSizeString: '1.5 MB', fileSize: 1.5 };

function generateFileId() {
  return 'f-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
}

function buildFileMarkup(file, key, showProgress = true) {
  const isError = Number(file.fileSize) > 1;
  return `
    <li data-file-id="${file.id}">
      <div class="d-flex align-items-center justify-content-between">
        <div class="d-flex align-items-center">
          <div class="mr-2 ${isError ? 'inail-file-uploader-icon-error' : ''}">
            <i class="fa-regular fa-file-lines inail-file-icon-size" aria-hidden="true"></i>
          </div>
          <div class="inail-file-uploader-label ${isError ? 'inail-file-uploader-label-error' : ''} mr-2">
            ${file.label}
            
          </div>
          <div class="inail-file-uploader-size mr-3">${file.fileSizeString}</div>
        </div>
        <div class="inail-file-uploader-icon">
          <button class="inail-button-download"
                  aria-label="elimina allegato ${file.label}"
                  data-file-delete="${file.id}" data-uploader-key="${key}">
            <i class="fa fa-trash-alt inail-file-uploader-icon-reset" aria-hidden="true"></i>
          </button>
        </div>
      </div>

      ${isError ? `
        <div class="inail-file-uploader-error-hint ml-4">
          <i class="fas fa-exclamation-circle inail-file-uploader-icon-error mr-2" aria-hidden="true"></i>
          Errore durante il caricamento del file allegato.
        </div>` : ''}

      ${showProgress ? `
        <div class="inail-uploader-spinner">
          <span class="progress" data-progress-container="${file.id}">
            <span class="progress-bar"
                  role="progressbar"
                  aria-valuenow="0"
                  aria-valuemin="0"
                  aria-valuemax="100"
                  aria-valuetext="Stato avanzamento: 0%"
                  style="width:0%"
                  data-progress-bar="${file.id}">
            </span>
          </span>
        </div>` : ''}

      <div class="inail-divider" data-divider="${file.id}"><hr></div>
    </li>`;
}

function initUploader($widget) {
  if ($widget.data('uploader-initialized')) return;
  $widget.data('uploader-initialized', true);

  const key = $widget.data('uploader-key') || 'file_uploader';
  uploaderState.set(key, { list: [] });

  const $input   = $widget.find(`[data-file-input="${key}"]`);
  const $trigger = $widget.find(`[data-file-trigger="${key}"]`);
  const $status  = $widget.find('.inail-aria-status');

  $trigger.off('click').on('click', e => {
    e.preventDefault();
    const el = $input.get(0);
    if (el.showPicker) el.showPicker(); else el.click();
  });

  $input.off('change').on('change', function () {
    const files = Array.from(this.files || []);
    if (!files.length) return;

    const state = uploaderState.get(key);
    const added = files.map(f => {
      const sizeMB = +(f.size / (1024 * 1024)).toFixed(1);
      return {
        id: generateFileId(),
        label: f.name,
        fileSizeString: `${sizeMB} MB`,
        fileSize: sizeMB
      };
    });

    // Announce selection
    if (files.length === 1) {
      $status.text(`File ${files[0].name} selezionato.`);
    } else {
      $status.text(`${files.length} file selezionati.`);
    }

    state.list.push(...added);
    const $list = $widget.find('.inail-file-uploader-text-container');

    added.forEach(file => {
      $list.append(buildFileMarkup(file, key, true));
      const $item = $widget.find(`[data-file-id="${file.id}"]`);
      const $bar = $item.find(`[data-progress-bar="${file.id}"]`);
      const $spinner = $item.find('.inail-uploader-spinner');

      $spinner.show();
      $status.text(`Caricamento avviato per ${file.label}.`);

      let progress = 0;
      const interval = setInterval(() => {
        progress += 5;
        $bar.css('width', `${progress}%`).attr('aria-valuenow', progress);

        if (progress >= 100) {
          clearInterval(interval);
          setTimeout(() => {
            $spinner.fadeOut(600, () => { $spinner.remove(); });
            $item.addClass('upload-complete');
            $status.text(`Caricamento completato per ${file.label}.`);
          }, 500);
        }
      }, 40);
    });

    $list.css('visibility', 'visible');
    this.value = '';
    this.blur();
  });

  // Delete handler
  $widget.off('click', '[data-file-delete]')
    .on('click', '[data-file-delete]', function () {
      const fileId = $(this).data('file-delete');
      const state = uploaderState.get(key);
      const file = state.list.find(f => f.id === fileId);
      state.list = state.list.filter(f => f.id !== fileId);
      $widget.find(`[data-file-id="${fileId}"]`).remove();
      if (file) $status.text(`File ${file.label} eliminato.`);
    });
}


// Initialize all uploaders
$('[data-input-type="file_uploader"]').each(function () {
  initUploader($(this));
});

// Preload test files (no spinner)
function preloadTestFiles($widget, key) {
  const state = uploaderState.get(key);
  if (!state) return;

  state.list.push(file1, file2, file3);

  const $list = $widget.find('.inail-file-uploader-text-container');
  [file1, file2, file3].forEach(file => {
    $list.append(buildFileMarkup(file, key, false));
    const $item = $widget.find(`[data-file-id="${file.id}"]`);
    $item.addClass('upload-complete');
  });

  $list.css('visibility', 'visible');
}

// Hook into init for preload
$('[data-input-type="file_uploader"]').each(function () {
  const $widget = $(this);
  initUploader($widget);
  const key = $widget.data('uploader-key') || 'file_uploader';
  preloadTestFiles($widget, key);
});

/* END_FILE_UPLOADER */





// $trigger.on('click', () => $input.trigger('click'));
//
// If you need a standalone binding:
$(document).on('click', '[data-file-trigger]', function () {
  const key = $(this).data('file-trigger');
  const $widget = $(this).closest('[data-input-type="file_uploader"]');
  $widget.find(`[data-file-input="${key}"]`).trigger('click');
});

// Custom fileselect event (optional)
$(document).on('change', '.btn-file :file', function () {
  const input = $(this);
  const numFiles = input.get(0).files ? input.get(0).files.length : 1;
  const label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [numFiles, label]);
});

$(document).on('fileselect', '.btn-file :file', function (event, numFiles, label) {
  const $container = $(this).closest('[data-input-type="file_uploader"]');
  const $textInput = $container.find('.upload-file-button-container input:text');
  const log = numFiles > 1 ? `${numFiles} files selezionati` : label;
  if ($textInput.length) $textInput.val(log);
  else if (log) alert(log);
});

// Remove legacy direct-id usage
// if ($(".uploadBtn").length > 0) {
//   document.getElementById("uploadBtn").onchange = function () {
//     document.getElementById("addFile").value = this.value;
//   };
// }


// Trigger → input (standalone binding)
$(document).on('click', '[data-file-trigger]', function () {
  const key = $(this).data('file-trigger');
  const $widget = $(this).closest('[data-input-type="file_uploader"]');
  $widget.find(`[data-file-input="${key}"]`).trigger('click');
});

// Custom fileselect event (optional)
$(document).on('change', '.btn-file :file', function () {
  const input = $(this);
  const numFiles = input.get(0).files ? input.get(0).files.length : 1;
  const label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [numFiles, label]);
});

$(document).on('fileselect', '.btn-file :file', function (event, numFiles, label) {
  const $container = $(this).closest('[data-input-type="file_uploader"]');
  const $textInput = $container.find('.upload-file-button-container input:text');
  const log = numFiles > 1 ? `${numFiles} files selezionati` : label;
  if ($textInput.length) $textInput.val(log);
  else if (log) alert(log);
});

const newUploadWidgetSelector = '[data-input-type="file_uploader"]';

// --- Focus underline handler ---
function browseButtonFocusHandler($fileInput) {
  $fileInput.on('focus', function () {
    $(this).closest('.upload-container').find('span').css('text-decoration', 'underline');
  }).on('focusout', function () {
    $(this).closest('.upload-container').find('span').css('text-decoration', 'none');
  });
}

// --- Accessibility toggle when a file is selected ---
function selectedFileHandler($fileInput, isFileSelected) {
  const $widget = $fileInput.closest(newUploadWidgetSelector);
  const $btnGroup = $widget.find('.upload-file-button-container');

  if (isFileSelected) {
    $btnGroup.children('label, input, button').attr('aria-hidden', 'false');
    $btnGroup.find('.add-file').removeAttr('disabled').removeClass('disabled').attr('aria-hidden', 'false');
    $widget.find('.upload-container input').addClass('disabled').attr('aria-hidden', 'true');
    $widget.find('.upload-container').addClass('disabled');
    $btnGroup.children('button').attr('tabindex', '0').removeAttr('disabled').css('opacity', '1');
    $btnGroup.children('span').attr('aria-hidden', 'true');
    $fileInput.attr('disabled', 'disabled');
    $fileInput.closest('.upload-container').find('span').css('text-decoration', 'none');
    $widget.find('.fileUpload button.add-file').focus();
  } else {
    $btnGroup.children('label, input, button').attr('aria-hidden', 'true');
    $btnGroup.children('input').val('');
    $btnGroup.find('.add-file').addClass('disabled').attr('disabled', 'disabled').attr('aria-hidden', 'true');
    $widget.find('.upload-container input').removeClass('disabled').attr('aria-hidden', 'false');
    $widget.find('.upload-container').removeClass('disabled')
           .find('input').removeAttr('disabled');
    $btnGroup.children('button').attr('tabindex', '-1').attr('disabled', 'disabled').css('opacity', '0.5');
    $btnGroup.children('span').attr('aria-hidden', 'false');
    $fileInput.removeAttr('disabled');
  }
}

// --- File handler (uses data-file-id now) ---
function fileHandler($fileInput) {
  const hasValue = $fileInput.val() !== '';
  selectedFileHandler($fileInput, hasValue);

  const label = $fileInput.val().replace(/\\/g, '/').replace(/.*\//, '');
  const $widget = $fileInput.closest('[data-input-type="file_uploader"]');
  $widget.find('.upload-file-button-container input:text').val(label);

  // Reset (innerx) — recreate original input
  $widget.find('.innerx').off('click').on('click', function (e) {
    e.preventDefault();
    const $original = $fileInput.clone();
    $original.val('');
    $original.on('change', function () { fileHandler($(this)); });
    browseButtonFocusHandler($original);

    $widget.find('.upload-file-button-container input:text').val('');
    $widget.find('.upload-container input:file').remove();
    $widget.find('.upload-container').append($original);
    selectedFileHandler($original, false);

    $widget.find('.fileUpload input[data-file-input]').focus();
  });
}

// --- Traverse widgets and bind handlers ---
function traverseEl($widgets) {
  if ($widgets.length > 0) {
    $widgets.each(function () {
      const $widget = $(this);
      selectedFileHandler($widget.find('.upload-file-button-container input.form-control'), false);
      const $fileInput = $widget.find('.fileUpload :file');
      browseButtonFocusHandler($fileInput);
      $fileInput.on('change', function () { fileHandler($(this)); });
    });
  }
}

// Initial traversal
traverseEl($('[data-input-type="file_uploader"]'));

// “Nuovo file” button (add-file) — data-based
$(document).on('click', '.add-file', function () {
  const $widget = $(this).closest('[data-input-type="file_uploader"]');
  const key = $widget.data('uploader-key') || 'file_uploader';

  const nuovoScegli = $(`<input accept=".pdf" class="btn-primary upload" type="file"
                               aria-label="Scegli il file" aria-hidden="false"
                               data-file-input="${key}">`);

  $widget.find('.upload-container input:file').remove();
  $widget.find('.upload-container span').attr('aria-hidden', 'false');
  $widget.find('.upload-container').append(nuovoScegli);
  $widget.find('.fileUpload input[data-file-input]').focus();

  traverseEl($widget);
});



	/*__________FINE_FILE_UPLOADER__________*/

	/* Carica File */
	// var uploadFiles = $(".uploadFile");
	// var uploadFileList = [];
	// var file1 = { label: 'nome-file-01.pdf', fileSizeString: '0.5 MB', fileSize: 0.5 };
	// var file2 = { label: 'nome-file-02.pdf', fileSizeString: '0.3 MB', fileSize: 0.3 };
	// var file3 = { label: 'nome-file-03.pdf', fileSizeString: '1.5 MB', fileSize: 1.5 };
	// uploadFileList.push(file1, file2, file3);

	// $.each(uploadFileList, function (index, file) {
	// 	var templateHtml = `<li id="fileInput${index + 1}">
	// 		<div class="d-flex align-items-center justify-content-between">
	// 			<div class="d-flex align-items-center">
	// 				<i class="fa-regular fa-file-lines mr-2"></i>
	// 				<div class="inail-file-uploader-label mr-2">${file.label}</div>
	// 				<div class="mr-3">${file.fileSizeString}</div>
	// 			</div>
	// 			<div class="inail-file-uploader-icon">
	// 				<button class="inail-button-download" aria-label="elimina allegato ${index + 1}">
	// 					<i class="fa fa-trash-alt innerx2 inail-file-uploader-icon-reset" data-id="${index + 1}"></i>
	// 				</button>
	// 			</div>
	// 		</div>
	// 		<div class="inail-uploader-spinner">
	// 			<div>
	// 				<span class="progress" aria-labelledby="progress-label" id="progress-container-${index + 1}">
	// 						<span id="progress-bar-${index + 1}"
	// 						class="progress-bar"
	// 						role="progressbar"
	// 						aria-valuenow="0"
	// 						aria-valuemin="0"
	// 						aria-valuemax="100"
	// 						aria-valuetext="Stato avanzamento: 0%"
	// 						style="width:0%"
	// 						title="Stato avanzamento: 0%">
	// 						</span>
	// 				</span>
	// 			</div>
	// 		</div>
	// 		<div id="divider-${index + 1}"><hr></div></li>`;

	// 	var templateHtmlError = `<li id="fileInput${index + 1}">
	// 		<div class="d-flex align-items-center justify-content-between">
	// 			<div>
	// 			<div class="d-flex align-items-center">
	// 				<div class="inail-file-uploader-label inail-file-uploader-label-error mr-2"><i class="fa-regular fa-file-lines mr-2 inail-file-uploader-icon-error"></i>${file.label} 
	// 				</div>
	// 				<div class="mr-3">${file.fileSizeString}</div>
	// 				</div>
	// 				<div class="inail-file-uploader-error-hint ml-4">
	// 					<i class="fas fa-exclamation-circle inail-file-uploader-icon-error mr-2"></i>Errore durante il caricamento del file allegato.
	// 				</div>
	// 			</div>
	// 			<div class="inail-file-uploader-icon">
	// 				<button class="inail-button-download" aria-label="elimina allegato ${index + 1}">
	// 					<i class="fa fa-trash-alt innerx2 inail-file-uploader-icon-reset" data-id="${index + 1}"></i>
	// 				</button>
	// 			</div>
	// 		</div>
	// 		<div class="inail-uploader-spinner">
	// 			<div>
	// 				<span class="progress" aria-labelledby="progress-label" id="progress-container-${index + 1}">
	// 						<span id="progress-bar-${index + 1}"
	// 						class="progress-bar"
	// 						role="progressbar"
	// 						aria-valuenow="0"
	// 						aria-valuemin="0"
	// 						aria-valuemax="100"
	// 						aria-valuetext="Stato avanzamento: 0%"
	// 						style="width:0%"
	// 						title="Stato avanzamento: 0%">
	// 						</span>
	// 				</span>
	// 			</div>
	// 		</div>
	// 		<div id="divider-${index + 1}"><hr></div></li>`;
	// 	lastIndex = index;

	// 	var isError = file.fileSize > 1;

	// 	if (isError) {
	// 		$(".inail-file-uploader-text-container").append(templateHtmlError);
	// 	} else {
	// 		$(".inail-file-uploader-text-container").append(templateHtml);
	// 	}
	// });

	// $(".inail-file-uploader-text-container").css("visibility", "visible");
	// $(".inail-file-uploader-icon-reset").show();
	// $(".inail-file-uploader-icon-error").show();


	// var lastIndex = 0;
	// if (uploadFiles.length > 0) {
	// 	for (var i = 0; i < uploadFiles.length; i++) {
	// 		var uploadFile = uploadFiles.eq(i);
	// 		uploadFile.find(".fileUpload :file").on('change', function () {
	// 			$(this).parent().addClass('disabled');
	// 			$(this).parent().parent().next().find('button').removeClass('disabled').removeAttr('disabled');

	// 			var input = $(this),
	// 				label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
	// 			var fileSizeString = (input[0].files[0].size / (1024 * 1024)).toFixed(1) + " MB";
	// 			var fileSize = (input[0].files[0].size / (1024 * 1024)).toFixed(1);
	// 			var uploadFile = input.closest(".uploadFile");
	// 			uploadFile.find(".upload-file-button-container input:text").val(label);
	// 			/* uploadFile.find(".upload-file-button-container .inail-file-uploader-label").text(label);
	// 			uploadFile.find(".upload-file-button-container .inail-file-uploader-size").text(fileSize); */
	// 			uploadFile.find(".inail-file-uploader-text-container").css("visibility", "visible");

	// 			uploadFileList.push({ label: label, fileSizeString: fileSizeString, fileSize: fileSize });
	// 			$(".inail-file-uploader-text-container").empty();
	// 			$.each(uploadFileList, function (index, file) {
	// 				var templateHtml = `<li id="fileInput${index + 1}">
	// 						<div class="d-flex align-items-center justify-content-between">
	// 							<div class="d-flex align-items-center">
	// 								<div class="mr-2">
	// 									<i class="fa-regular fa-file-lines"></i>
	// 								</div>
	// 								<div class="inail-file-uploader-label mr-2">${file.label}</div>
	// 								<div class="inail-file-uploader-size mr-3">${file.fileSizeString}</div>
	// 							</div>
	// 							<div class="inail-file-uploader-icon">
	// 								<button class="inail-button-download" aria-label="elimina allegato ${index + 1}">
	// 									<i class="fa fa-trash-alt innerx2 inail-file-uploader-icon-reset" data-id="${index + 1}"></i>
	// 								</button>
	// 							</div>
	// 						</div>
	// 						<div class="inail-uploader-spinner">
	// 							<div>
	// 								<span class="progress" aria-labelledby="progress-label" id="progress-container-${index + 1}">
	// 										<span id="progress-bar-${index + 1}"
	// 										class="progress-bar"
	// 										role="progressbar"
	// 										aria-valuenow="0"
	// 										aria-valuemin="0"
	// 										aria-valuemax="100"
	// 										aria-valuetext="Stato avanzamento: 0%"
	// 										style="width:0%"
	// 										title="Stato avanzamento: 0%">
	// 										</span>
	// 								</span>
	// 							</div>
	// 						</div>
	// 						<div id="divider-${index + 1}"><hr></div></li>`;

	// 				var templateHtmlError = `<li id="fileInput${index + 1}">
	// 						<div class="d-flex align-items-center justify-content-between">
	// 							<div class="d-flex align-items-center">
	// 								<div class="mr-2 inail-file-uploader-icon-error">
	// 									<i class="fa-regular fa-file-lines"></i>
	// 								</div>
	// 								<div class="inail-file-uploader-label inail-file-uploader-label-error mr-2">${file.label}</div>
	// 								<div class="inail-file-uploader-size mr-3">${file.fileSizeString}</div>
	// 							</div>
	// 							<div class="inail-file-uploader-icon">
	// 								<button class="inail-button-download" aria-label="elimina allegato ${index + 1}">
	// 									<i class="fa fa-trash-alt innerx2 inail-file-uploader-icon-reset" data-id="${index + 1}"></i>
	// 								</button>
	// 							</div>
	// 						</div>
	// 						<div class="inail-file-uploader-error-hint ml-4">
	// 							<i class="fas fa-exclamation-circle inail-file-uploader-icon-error mr-2"></i>Errore durante il caricamento del file allegato.
	// 						</div>
	// 						<div class="inail-uploader-spinner">
	// 							<div>
	// 								<span class="progress" aria-labelledby="progress-label" id="progress-container-${index + 1}">
	// 										<span id="progress-bar-${index + 1}"
	// 										class="progress-bar"
	// 										role="progressbar"
	// 										aria-valuenow="0"
	// 										aria-valuemin="0"
	// 										aria-valuemax="100"
	// 										aria-valuetext="Stato avanzamento: 0%"
	// 										style="width:0%"
	// 										title="Stato avanzamento: 0%">
	// 										</span>
	// 								</span>
	// 							</div>
	// 						</div>
	// 						<div id="divider-${index + 1}"><hr></div></li>`;
	// 				lastIndex = index;

	// 				var isError = file.fileSize > 1;

	// 				if (isError) {
	// 					$(".inail-file-uploader-text-container").append(templateHtmlError);
	// 				} else {
	// 					$(".inail-file-uploader-text-container").append(templateHtml);
	// 				}
	// 			});

	// 			// uploadFile.find(".fileUpload").hide();
	// 			// uploadFile.find(".fileSubmit").show();
	// 			// uploadFile.find(".innerx").click(function(e) {
	// 			//    $(this).parent().parent().find('.upload-container').removeClass('disabled');
	// 			//    $(this).parent().parent().find('.add-file').addClass('disabled').attr("disabled", 'disabled');
	// 			// 	var uploadFile = $(this).closest(".uploadFile");
	// 			// 	e.stopImmediatePropagation();
	// 			// 	e.preventDefault();
	// 			// 	uploadFile.find(".fileUpload").show();
	// 			// 	// uploadFile.find(".fileSubmit").hide();
	// 			// 	uploadFile.find(".upload-file-button-container input:text").val("");
	// 			// 	uploadFile.find(".fileUpload input:file").val("");
	// 			// });

	// 			/* uploadFile.find(".innerx2").click(function(e) { */
	// 			uploadFile.find(".innerx2").on("click keydown", function (e) {
	// 				if (e.type === "click" || e.key === "Enter") {
	// 					var fileId = $(this).data('id'); // Ottieni l'ID del file da eliminare
	// 					$("#" + 'fileInput' + fileId).remove(); // Rimuovi l'elemento dal DOM
	// 					uploadFileList.splice(fileId - 1, 1);
	// 				}
	// 			});

	// 			// PROGRESS BAR ANIMATION
	// 			//  var progressBar = uploadFile.find(".progress-bar");
	// 			//  var progressContainer = uploadFile.find(".inail-uploader-spinner .progress");
	// 			var progressBar = $("#progress-bar-" + (lastIndex + 1));
	// 			var progressContainer = $("#progress-container-" + (lastIndex + 1));
	// 			var divider = $("#divider-" + (lastIndex + 1));
	// 			var lastFile = $("#fileInput" + (lastIndex + 1));
	// 			divider.remove();
	// 			/* var iconSuccess = uploadFile.find(".inail-file-uploader-icon-success"); */
	// 			var iconReset = uploadFile.find(".inail-file-uploader-icon-reset");
	// 			var iconError = uploadFile.find(".inail-file-uploader-icon-error");
	// 			iconError.show();
	// 			var deleteButton = uploadFile.find(".innerx2");

	// 			progressContainer.show();
	// 			progressContainer[0].style.setProperty("display", "block", "important");
	// 			iconReset.show();

	// 			var progress = 0;
	// 			var interval = setInterval(function () {
	// 				progress += 20;
	// 				progressBar.css("width", progress + "%").attr("aria-valuenow", progress).attr("aria-valuetext", "Stato avanzamento: " + progress + "%");

	// 				if (progress >= 100) {
	// 					var status = document.getElementById('ariaStatus');
	// 					status.textContent = ''; // Pulisci il messaggio
	// 					clearInterval(interval);
	// 					setTimeout(function () {
	// 						if (lastFile.find(".inail-file-uploader-error-hint").length > 0) {
	// 							status.textContent = 'Errore durante il caricamento del file allegato.';
	// 						} else {
	// 							status.textContent = 'Caricamento completato con successo';
	// 						}

	// 						progressContainer.hide();
	// 						/* iconSuccess.show(); */
	// 						/* iconError.show(); */
	// 						deleteButton.show();
	// 						/* iconReset.hide(); */

	// 						var progressBar = uploadFile.find(".progress-bar");
	// 						progressBar.css("width", "0%").attr("aria-valuenow", 0).attr("aria-valuetext", "Stato avanzamento: " + "0%");
	// 					}, 500);
	// 				}
	// 			}, 40);
	// 		});

	// 		/* $(".innerx2").click(function(e) { */
	// 		$(".innerx2").on("click keydown", function (e) {
	// 			if (e.type === "click" || e.key === "Enter") {
	// 				var fileId = $(this).data('id'); // Ottieni l'ID del file da eliminare
	// 				$("#" + 'fileInput' + fileId).remove(); // Rimuovi l'elemento dal DOM
	// 				uploadFileList.splice(fileId - 1, 1);
	// 			}
	// 		});

	// 	}
	// }









	/*INPUT FILE FUNCTION*/

	// $("#onUploadFile").on("click", function () {
	// 	$("#addfileN").click();
	// });

	// $('.btn-file :file').on('fileselect', function (event, numFiles, label) {
	// 	var input = $(this).parents('.upload-file-container').find(':text'),
	// 		log = numFiles > 1 ? numFiles + ' files selezionati' : label;

	// 	if (input.length) {
	// 		input.val(log);
	// 	} else {
	// 		if (log) alert(log);
	// 	}

	// });

	// $(document).on('change', '.btn-file :file', function () {

	// 	var input = $(this),
	// 		numFiles = input.get(0).files ? input.get(0).files.length : 1,
	// 		label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
	// 	input.trigger('fileselect', [numFiles, label]);
	// });


	// if ($(".uploadBtn").length > 0) {
	// 	document.getElementById("uploadBtn").onchange = function () {
	// 		document.getElementById("addFile").value = this.value;
	// 	};
	// }


	// /* Nuova versione carica File */
	// var newUploadWidgetSelector = ".uploadFileNew";
	// var uploadFilesWidget = $(newUploadWidgetSelector);
	// var browseButtonFocusHandler = function (fileInput) {
	// 	$(fileInput).on("focus", function () {
	// 		$(this).closest(".upload-container").find("span").css("text-decoration", "underline");
	// 	}).on("focusout", function () {
	// 		$(this).closest(".upload-container").find("span").css("text-decoration", "none");
	// 	});

	// }

	// var selectedFileHandler = function (fileInput, isFileSelected) {
	// 	if (isFileSelected) {

	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("label, input, button").attr("aria-hidden", "false");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".add-file").removeAttr("disabled").removeClass("disabled").attr("aria-hidden", "false");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-container input").addClass("disabled").attr("aria-hidden", "true");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-container").addClass("disabled");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("button").attr("tabindex", "0").removeAttr("disabled", "disabled").css("opacity", "1");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("span").attr("aria-hidden", "true");
	// 		//$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("input").blur();
	// 		//$(fileInput).closest(newUploadWidgetSelector).find(".upload-container input").blur();			
	// 		//$(fileInput).closest(newUploadWidgetSelector).find(".upload-container").blur();
	// 		$('.fileUpload button.add-file').focus();
	// 		$(fileInput).attr("disabled", "disabled");
	// 		$(fileInput).closest(".upload-container").find("span").css("text-decoration", "none");
	// 	}
	// 	else {

	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("label, input, button").attr("aria-hidden", "true");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("input").val("");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".add-file").addClass("disabled").attr("disabled", "disabled").attr("aria-hidden", "true");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-container input").removeClass("disabled").attr("aria-hidden", "false");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-container").removeClass("disabled")
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-container").find("input").removeAttr("disabled");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("button").attr("tabindex", "-1").attr("disabled", "disabled").css("opacity", "0.5");
	// 		$(fileInput).closest(newUploadWidgetSelector).find(".upload-file-button-container").children("span").attr("aria-hidden", "false");
	// 		$(fileInput).removeAttr("disabled");
	// 	}
	// }

	// var fileHandler = function (fileInput) {
	// 	if ($(fileInput).val() != "") {
	// 		selectedFileHandler($(fileInput), true);
	// 	}
	// 	else {
	// 		selectedFileHandler($(fileInput), false);
	// 	}
	// 	var input = $(fileInput),
	// 		label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
	// 	var uploadFile = input.closest(newUploadWidgetSelector);
	// 	uploadFile.find(".upload-file-button-container input:text").val(label);
	// 	uploadFile.find(".innerx").click(function (e) {
	// 		e.preventDefault();
	// 		var originalInputFile = input.clone();
	// 		originalInputFile.val("");
	// 		originalInputFile.on('change', function () {
	// 			fileHandler($(this));
	// 		});
	// 		browseButtonFocusHandler(originalInputFile);
	// 		uploadFile.find(".upload-file-button-container input:text").val("");
	// 		uploadFile.closest(newUploadWidgetSelector).find(".upload-container input:file").remove();
	// 		uploadFile.closest(newUploadWidgetSelector).find(".upload-container").append(originalInputFile);
	// 		selectedFileHandler(originalInputFile, false);
	// 		$('.fileUpload input#addfileN').focus();
	// 	});

	// 	var hiddenVar = false;
	// 	var hideFileButton = true;
	// 	if (uploadFile.closest(newUploadWidgetSelector).find(".upload-file-button-container input.form-control").val().replace(/ /g, "") == "") {
	// 		hiddenVar = true;
	// 		hideFileButton = false;
	// 	}
	// }

	// var traverseEl = function (elArray) {
	// 	if (elArray.length > 0) {
	// 		for (var i = 0; i < uploadFilesWidget.length; i++) {
	// 			var uploadFile = uploadFilesWidget.eq(i);
	// 			selectedFileHandler(uploadFile.find(".upload-file-button-container input.form-control"), false);
	// 			browseButtonFocusHandler(uploadFile.find(".fileUpload :file"));
	// 			uploadFile.find(".fileUpload :file").on('change', function () {
	// 				fileHandler($(this));
	// 			});
	// 		}
	// 	}
	// }

	// traverseEl(uploadFilesWidget);

	// $(".add-file").click(function () {
	// 	//BOTTONE FILE NUOVO
	// 	var nuovoScegli = '<input id="addfileN" accept=".pdf" class="btn-primary upload" type="file" aria-label="Scegli il file" aria-hidden="false">';
	// 	$(".upload-container input:file").remove();
	// 	$(".upload-container span").attr('aria-hidden', 'false');
	// 	$(".upload-container").append(nuovoScegli);
	// 	$('.fileUpload input#addfileN').focus();
	// 	traverseEl($(this).closest(newUploadWidgetSelector));
	// });
	/* ***************************************************************************** */




	/* gestione degli elementi custom dei form che non vengono resettati automaticamente all'evento reset */
	function formResetActions(e) {
		var target = e.target;
		/* resetto contatore caratteri Textarea */
		$(target).find("div.remainingChar").each(function () {
			var myTextarea = $(this).siblings("textarea");
			$(this).html(function () {
				return "<strong>" + myTextarea.attr("maxlength") + "</strong> caratteri disponibili";
			})
		})

		/* riabilito pulsanti del componente upload-files */
		// $(target).find(".upload-container").removeClass("disabled");
		// $(target).find(".add-file").addClass("disabled").attr("disabled", "disabled");
		// $(target).find(".fileUpload").show();

		/* log */
		$("#reset-log").append("<strong>#" + e.target.id + "</strong> resettato <br>")

		/*reset nuovo upload-files*/
		// traverseEl(uploadFilesWidget);

	}

	$("form").on("reset", formResetActions);




});

$(window).on('load', function () {
	//CORREZIONE BOOTSTRAP.JS - Rimuove i title ai popover
	//$('a[data-toggle="popover"]').attr('title','Popover');

	$('th.sorting').focusin(function (e) {
		setTimeout(function () {
			$(this).find('.thLabel').focus();
		}, 200);
	});



	$('.datePicker input.form-control[type="text"]').on('keypress', function (event) {
		var regex = new RegExp("^[0-9-/]");
		var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
		if (!regex.test(key)) {
			$(this).parent().parent().parent().append('<span role="alert" class="sr-only">sono consentiti solo caratteri numerici e la barra</span>');
			setTimeout(function () {
				$('.datePicker span[role="alert"]').remove();
			}, 1000);
			event.preventDefault();
			return false;
		}
	});
	$('.datePicker').on('changeDate', function () {
		var dataInserita = $(this).find('input[type="text"]').val();

		if (dataInserita == "GG/MM/AA") {
			//$(this).find('input[type="text"]').css('color', '#999');
		} else {
			//$(this).find('input[type="text"]').css('color', '#000');
		}
	});

	$('.datePicker input[type="text"]').click(function () {
		//$(this).removeAttr('value');
	});

	//GESTIONE CLICK ICONE TABELLA CON NOTIFICHE (APERTURA MODALE TRAMITE TASTO INVIO)
	$('.iconaNotifica').on('keydown', function (e) {
		if (e.which == 13) {
			//console.log('in');
			//console.log($(this).attr('aria-describedby'));
			var modale = $(this).find('span').attr('data-target');
			$(modale).modal('show');
			//console.log(modale);
		}
	});

});

//Menu orizzontale
function menuOrizzontaleW() {
	var menuW = 0;
	$('.menu_orizzontale').each(function () {
		menuW = parseInt($(this).outerWidth());
		$(this).find('ul').css('width', menuW);
	});
	$('.menu_orizzontale li.selected').each(function () {
		$(this).find('ul').first().css('display', 'block');
	});
}
function menuOrizzontaleH() {
	var menuH = 0;
	var nMenu = 0;
	$('.menu_orizzontale').each(function () {
		menuH = parseInt($(this).outerHeight());
		nMenu = $(this).find('ul:visible').length;
		if (nMenu > 1) {
			menuH = (menuH - 5) * nMenu;
			$(this).css('height', menuH);
		}
	});
}
$(window).resize(function () {
	menuOrizzontaleW();
});
$(document).ready(function () {
	menuOrizzontaleW();
	menuOrizzontaleH();
});
// Fine Menu orizzontale




