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




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


	//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");
	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 uploadFile = input.closest(".uploadFile");
					uploadFile.find(".upload-file-button-container input:text").val(label);
					// 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("");
					});
			});
		}
	}

    
    /*INPUT FILE FUNCTION*/
     $('.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

