/* 
**  
**  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 () {

	// 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"]';
	let justFocusedPopover = false;

	// 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');

		// Gestione focus - mostra automaticamente ogni volta
		$(popoverSelector).on('focus.popover', function () {
			const $element = $(this);
			$element.popover('show');
			$element.attr('aria-expanded', 'true');
			justFocusedPopover = true;
			setTimeout(() => {
				justFocusedPopover = false;
			}, 100); // tempo sufficiente per ignorare il click immediato
		});

		// Chiudo popover alla perdita del focus
		$(popoverSelector).on('focusout.popover', function () {
			$(this).popover('hide');
			$(this).attr('aria-expanded', 'false');
		});

		// 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(); // Evita il comportamento default
				const $element = $(this);
				const isVisible = $element.attr('aria-describedby') &&
					$('.popover[id="' + $element.attr('aria-describedby') + '"]').length > 0;
				if (isVisible) {
					// Se è visibile, nascondilo
					$element.popover('hide');
					$element.attr('aria-expanded', 'false');
				} else {
					// Se è nascosto, mostralo
					$element.popover('show');
					$element.attr('aria-expanded', 'true');
				}
			}
		});

		// Gestione click
		$(popoverSelector).on('click.popover', function (e) {
			if (justFocusedPopover) return;

			const $element = $(this);
			const isVisible = $element.attr('aria-describedby') &&
				$('.popover[id="' + $element.attr('aria-describedby') + '"]').length > 0;

			if (isVisible) {
				$element.popover('hide');
				$element.attr('aria-expanded', 'false');
			} else {
				$element.popover('show');
				$element.attr('aria-expanded', 'true');
			}
		});
	}

	// 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 */

	/* 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">
						<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="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} 
					<small class="mr-3">${file.fileSizeString}</small>
					</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">
						<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);
				console.log('uploadFile', uploadFile)
				/* 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">
										<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">
										<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
						console.log('fileId', fileId)
						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
					console.log('fileId', fileId)
					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

