/**
 * Created by m.niciarelli on 09/06/2015.
 */

jQuery(document).ready(function () {

  /*jQuery(".fc-event").click(function(){
     jQuery(".box-dettaglio-evento").collapse('toggle');
     jQuery(".box-calendario-eventi").collapse('toggle');
     });*/


  /********** MENU ORIZZONTALE ********************/
    $(".inail-menu-orizzontale .inail-tertiary-button").on("click", function (e) {
    e.preventDefault();

    var $btn = $(this);
    var target = $($btn.data("target"));
    var isExpanded = $btn.attr("aria-expanded") === "true";

    // trovo il menu del livello corrente
    var $parentMenu = $btn.closest("ul");

    // Chiudi solo gli altri bottoni dello stesso livello
    $parentMenu.find(".inail-tertiary-button").not($btn).each(function () {
      var $otherBtn = $(this);
      var otherTarget = $($otherBtn.data("target"));
      $otherBtn.attr("aria-expanded", "false");
      otherTarget.collapse("hide");
    });

    // Toggle quello cliccato
    if (isExpanded) {
      $btn.attr("aria-expanded", "false");
      target.collapse("hide");
    } else {
      $btn.attr("aria-expanded", "true");
      target.collapse("show");
    }
});

  //  Menu intranet
  let showSidebar = false;

  $('#inail-intranet-toggle-btn').on('click', function () {
    showSidebar = !showSidebar;

    $('#inail-intranet-aside-menu')
      .toggleClass('hidden', !showSidebar)
      .attr('aria-hidden', !showSidebar);

    $('#inail-intranet-main-menu')
      .toggleClass('col-md-12 col-lg-12 col-sm-12 col-xs-12', !showSidebar)
      .toggleClass('col-md-9 col-lg-9 col-sm-7 col-xs-3', showSidebar);

    // Toggle icons
    $('#inail-intranet-toggle-btn .fa-bars').toggleClass('active', !showSidebar);
    $('#inail-intranet-toggle-btn .fa-times').toggleClass('active', showSidebar);

    // Update aria attributes
    $(this).attr({
      'aria-expanded': showSidebar,
      'aria-label': showSidebar ? `Chiudi il menu dell'applicativo` : `Apri il menu dell'applicativo`
    });
  });
  // finish menu intranet

  // jQuery("#trigger-slider-menu,#close-slider-menu").click(function () {
  //   // Set the effect type
  //   var effect = "slide";

  //   // Set the options for the effect type chosen
  //   var options = "direction: left";

  //   // Set the duration (default: 400 milliseconds)
  //   var duration = 500;
  //   /*jQuery('#trigger-slider-menu').toggle();*/
  //   jQuery(".slider-menu").toggle(effect, options, duration);
  // });

  /* GESTISCO LA VISIBILITA' DEL MENU SLIDER */
  let showMenu = false;
  jQuery("#trigger-slider-menu,#close-slider-menu").click(function () {
    showMenu = !showMenu;

    $('#trigger-slider-menu .fa-bars').toggleClass('active', !showMenu);
    $('#trigger-slider-menu .fa-times').toggleClass('active', showMenu);

    $(this).attr({
      'aria-expanded': showMenu,
      'aria-label': showMenu ? `Chiudi il menu dell'applicativo` : `Apri il menu dell'applicativo`
    });
    // Set the effect type
    var effect = "slide";

    // Set the options for the effect type chosen
    var options = "direction: left";

    // Set the duration (default: 400 milliseconds)
    var duration = 500;
    /*jQuery('#trigger-slider-menu').toggle();*/
    jQuery(".slider-menu").toggle(effect, options, duration);
  });

  jQuery(".inail-mat-hamburger-menu #trigger-slider-menu-hamburger").click(
    function () {
      jQuery("#navigazionesecondaria").attr(
        "style",
        "display: block !important"
      );
    }
  );

  /* INIZIALIZIO IL CALENDARIO EVENTI */
  jQuery(".date input").datepicker({
    format: "dd/mm/yyyy",
    weekStart: 1,
    todayBtn: "linked",
    language: "it",
    todayHighlight: true,
    showOnFocus: false
  });

  /*           
            $('.date input').on('change', function(){
                $('.datepicker').hide();
            });
            */
});

/* Handle button click */
// jQuery(".inail-button-calendar").on("click", function () {
//   let input = jQuery(this).closest(".input-relative").find("input");
//   input.datepicker("show");
//   input.focus(); // Make sure the input is focused to interact with the datepicker
// });

/* Handle Enter or Space key press on the button */
// jQuery(".inail-button-calendar").on("keydown", function (e) {
//   if (e.key === "Enter" || e.key === " " || e.keyCode === 13 || e.keyCode === 32) {
//     e.preventDefault(); // Prevent default button behavior
//     let input = jQuery(this).closest(".input-relative").find("input");
//     input.datepicker("show");
//     input.focus();
//   }
// });

function getContatore(urlServizio) {
  $("#bannerEvento").html("");
  //var debug=true;
  $.ajax({
    url: urlServizio,
    type: "GET",
    dataType: "jsonp",
    jsonp: "callback",
    jsonpCallback: "contatoreCallback",
    timeout: 10000,
    error: function (xhr, ajaxOptions, thrownError) {
      //if (debug) alert ('Errore di comunicazione con servizio REST ['+xhr.status+'] ('+ajaxOptions+') '+thrownError);
    },
    success: function (jsonp) {
      $("#bannerEvento").html(contatoreFormat(jsonp));
    },
  });
}

function contatoreCallback(data) {
  $("#bannerEvento").html(contatoreFormat(data));
}

function contatoreFormat(mycount) {
  mycount += "";
  x = mycount.split(".");
  x1 = x[0];
  x2 = x.length > 1 ? "." + x[1] : "";

  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, "$1" + "." + "$2");
  }
  return x1;
}

function getAjaxWithJSONResponse(_successEvent, _urlService, _errorEvent) {
  $.ajax({
    type: "GET",
    url: _urlService,
    dataType: "json",
    success: function (data) {
      _successEvent(data);
    },
    error: function (xhr, textStatus, errorThrown) {
      if (_errorEvent) {
        _errorEvent(xhr, textStatus);
      } else {
        if (xhr.status && (xhr.status == "401" || xhr.status == "403")) {
          showMessage("fail", MSG_USER_UNAUTHORIZED);
        } else if (xhr.responseText && xhr.responseText != "") {
          var json_obj = JSON.parse(xhr.responseText);
          showMessage("fail", json_obj.message);
        } else {
          showMessage("fail");
        }
        hideLoadingAnimation();
      }
    },
  });
}

function getMenuServiziOnLine(url) {
  var _successEvent = function (data) {
    if ($.isArray(data) && data.length) {
      var items = [];
      $.each(data, function (id, menu) {
        items.push(
          '<li title="' +
          menu.description +
          '"><a href="' +
          menu.url +
          '"><span class="fa ' +
          menu.icon +
          '"></span>' +
          menu.description +
          "</a></li>"
        );
      });
      $(".ul_menu").empty();
      $(".ul_menu").html(items.join(""));
    }
  };
  getAjaxWithJSONResponse(_successEvent, url);
}

function setCharAt(str, index, chr) {
  if (index > str.length - 1) return str;
  str = "" + str;
  return str.substr(0, index) + chr + str.substr(index + 1);
}

function loadHeaderFoto(urlRest, matricolaCorrente) {
  var url;
  //recupero foto
  url = urlRest + "personeStrutture/getFoto/" + matricolaCorrente;
  $.ajax({
    type: "GET",
    url: url,
    timeout: 7000, //millisecondi
    responseType: "text",
    complete: function (xhr, status) {
      if (xhr.status > 199 && xhr.status < 300) {
        var response = "" + xhr.responseText;
        if (response.startsWith('"') && response.endsWith('"')) {
          response = setCharAt(response, 0, "");
          response = setCharAt(response, response.length - 1, "");
        }

        $("#profile_header_img").attr(
          "src",
          "data:image/png;base64," + response
        );
        // $("#profile_header_img").attr("src","data:image/png;base64," + xhr.responseText);
      } else {
        $("#profile_header_img").attr("src", "/static/img/anonimo.jpg");
      }
    },
  });
}

// Recupero UToken e notifiche
var wcpRootUrl = "/esc-rest/api/";

function recuperaUToken() {
  var wcpResourcesSite = wcpRootUrl + "resourceIndex";
  $.getJSON(wcpResourcesSite)
    .done(function (data) {
      $.each(data.links, function (key, link) {
        if (link.href) {
          var startIndex = link.href.indexOf("utoken=");
          utoken = link.href.substring(startIndex + 7, link.href.length);

          if (utoken) {
            console.log(
              "GetTokenAndNotifications - Retrieved utoken - Utoken = " + utoken
            );
            return utoken;
          }
        }
      });
    })
    .fail(function () {
      console.log("Errore nel recupero del utoken");
    });
}
function impostaNumeroNotifice() {
  var urlUltimaDataLettura =
    wcpRootUrl + "notifications/count?utoken=" + recuperaUToken();
  var notificationsEl = $(".strumenti-profilo>.notifica-social").last();
  $.getJSON(urlUltimaDataLettura).done(function (count) {
    if (count && count > 0) {
      notificationsEl.html(count);
      notificationsEl.removeClass("hidden");
    } else {
      notificationsEl.addClass("hidden");
    }
  });
}
