// Global Scripts
document.getElementById("page-padding").style.height = document.getElementById("page-header").offsetHeight + "px";
if (document.getElementById("listing")) document.querySelector("main").style.minHeight = window.innerHeight - document.getElementById("page-header").offsetHeight + "px";
window.addEventListener("DOMContentLoaded", function () {
  // #region UTILITIES
  $(window).on("resize", function () {
    $("#page-padding").css("height", $("header").outerHeight());
    $("main:not(#listing)").css("min-height", window.innerHeight - $("header").outerHeight() + "px");
  });
  $("#page-content").on("click", ".account-button", function () {
    $(".modal").modal("hide");
    if ($("#modal-login").length) $("#modal-login").modal("show");
    else window.location.href = "profil#profile";
  });
  $(".toast").toast("show");
  $("#toast-close").on("click", function () {
    AppelAjax(["DésactiveToast"]);
  });
  $(".copyright-year").text(new Date().getFullYear());
  $(".fit-1").fitText(1.135);
  $(".fit-2").fitText(1.4185);
  $(".fit-3").fitText(1.621);
  $(".fit-4").fitText(1.891);
  $(".fit-5").fitText(2.27);
  $(".fit-6").fitText(2.837);
  $(".slick-1").slick({
    centerMode: true,
    arrows: true,
    centerPadding: "0px",
    slidesToShow: 1,
    //slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 5000,
    lazyLoad: "ondemand",
    responsive: [
      {
        breakpoint: 992,
        settings: {
          arrows: false,
        },
      },
    ],
  });

  $(".slick-5").slick({
    centerMode: true,
    centerPadding: "0px",
    slidesToShow: 5,
    autoplay: true,
    autoplaySpeed: 5000,
    lazyLoad: "ondemand",
    responsive: [
      {
        breakpoint: 1200,
        settings: {
          slidesToShow: 3,
        },
      },
      {
        breakpoint: 768,
        settings: {
          arrows: false,
          slidesToShow: 2,
        },
      },
      {
        breakpoint: 576,
        settings: {
          arrows: false,
          slidesToShow: 1,
        },
      },
    ],
  });
  $(".slick-list").css("overflow-y", "visible");
  $(".slick-1 .slick-track").each(function () {
    if ($(this).children().length < 2) $(this).addClass("slick-disabled");
  });
  $(".slick-5 .slick-track").each(function () {
    if ($(this).children().length < 6) $(this).addClass("slick-disabled");
  });

  $("[data-bs-toggle=tooltip]").tooltip();
  // if (window.matchMedia("(min-width: 768px)").matches) {
  //   $(".carousel:not(.article)").on("mouseover", function () {
  //     $(".carousel-item.active img").css("z-index", "");
  //     $(this).find(".carousel-item.active img").css("z-index", "99999999");
  //   });
  //   $(".carousel:not(.article)").on("mouseout", function () {
  //     setTimeout(() => {
  //       $(this).css("z-index", "");
  //     }, 150);
  //   });
  // }
  $(".slick-list").addClass("lazy-container");
  $.extend($.lazyLoadXT, {
    scrollContainer: ".lazy-container",
  });
  $(".selectize").selectize({
    placeholder: "Choisissez",
    plugins: ["auto_position"],
  });
  $("#newsletter-subscribe").on("click", function () {
    const email = $("#newsletter-email").val();
    if (email) {
      $("#error-newsletter-email").addClass("d-none");
      AppelAjax(["InscrisNewsletter", email]);
    } else {
      $("#error-newsletter-email span").text("Email vide");
      $("#error-newsletter-email").removeClass("d-none");
    }
  });
  $(".article-stock").on("click", function () {
    popupMessage("Stocks", "Pour mettre à jour vos stocks, veuillez les réimporter via un fichier Excel");
  });

  // #endregion UTILITIES

  //#region MODAL
  $(".modal").on("show.bs.modal", function () {
    $("html,#lazy-container").addClass("overflow-hidden");
  });
  $(".modal").on("hidden.bs.modal", function () {
    $("html,#lazy-container").removeClass("overflow-hidden");
  });
  $(".confirm-btn").on("click", function () {
    $("#modal-confirm .modal-body").text($(this).data("message"));
    $("#modal-confirm").modal("show");
    const confirmAction = $(this).data("confirmed").split(",");
    $("#modal-confirm #confirm-yes").on("click", function () {
      $("#modal-confirm").modal("hide");
      var fn = window[confirmAction[0]];
      if (confirmAction.length === 2) fn(confirmAction[1]);
      else if (confirmAction.length === 3) fn(confirmAction[1], confirmAction[2]);
      else fn();
    });
  });
  $("#modal-confirm").on("hide.bs.modal", function () {
    $("#modal-confirm #confirm-yes").off("click");
  });
  if (Cookies.get("STCPRO_MESSAGE")) {
    let messageCookie = Cookies.get("STCPRO_MESSAGE").replaceAll("[egal]", "=").replaceAll("[pv]", ";");
    $("#modal-message .modal-title").html(messageCookie.split(",,")[0]);
    $("#modal-message .modal-body p").html(messageCookie.split(",,")[1]);
    $("#modal-message").modal("show");
    Cookies.remove("STCPRO_MESSAGE", { path: "" });
    Cookies.remove("STCPRO_MESSAGE");
  } else {
    $("#modal-message .modal-title").html("");
    $("#modal-message .modal-body p").html("");
  }
  //#endregion MODAL

  //#region CONTACT
  $(".btn-contact").on("click", function () {
    $("#modal-contact").modal("show");
  });
  $("#contact-send").on("click", function () {
    const inputIDs = ["email", "lastname", "firstname", "object", "message", "company", "phone", "subject"];
    const inputNames = ["Email", "Nom", "Prénom", "Objet", "Message", "Société", "Téléphone", "Sujet"];
    const inputTypes = ["email", "letters", "letters", "text", "text", "text", "phone", "text"];
    let validated = true;
    let values = [];
    let nbParams = 8;
    switch ($("#contact-subject").val()) {
      case "Une Commande":
        inputIDs.push("order-number");
        inputNames.push("N° de commande");
        inputTypes.push("numbers");
        nbParams = 9;
        break;
      case "Une Facture et/ou un Paiement":
        inputIDs.push("invoice-number");
        inputNames.push("N° de facture");
        inputTypes.push("numbers");
        nbParams = 9;
        break;
      case "Une Livraison":
        inputIDs.push("shipping-number");
        inputNames.push("N° de BL");
        inputTypes.push("numbers");
        nbParams = 9;
        break;
      case "Un Retour Produit(s)":
        inputIDs.push("shipping-number");
        inputNames.push("N° de BL");
        inputTypes.push("numbers");
        inputIDs.push("sku");
        inputNames.push("Réf produits");
        inputTypes.push("text");
        nbParams = 10;
        break;
    }
    $.each(inputIDs, function (index, ID) {
      if (!validateInput("contact-" + ID, inputNames[index], inputTypes[index])) {
        validated = false;
      }
      values.push($("#contact-" + ID).val());
    });
    if ($("#contact-subject").val() === "Candidature") {
      if (!$("#contact-application-resume-filename").text()) {
        validated = false;
        $("#error-contact-application-resume > span").text("Veuillez ajouter un C.V.");
        $("#error-contact-application-resume").removeClass("d-none");
      } else values.push($("#contact-application-resume-filename").text().trim());
      if (!$("#contact-application-letter-filename").text()) {
        validated = false;
        $("#error-contact-application-letter > span").text("Veuillez ajouter une L.M.");
        $("#error-contact-application-letter").removeClass("d-none");
      } else values.push($("#contact-application-letter-filename").text().trim());
      nbParams = 10;
      if (validated) {
        $("#M16").click();
        $("#M31").click();
      }
    }
    if (validated) {
      switch (nbParams) {
        case 8:
          AppelAjax(["ContacteSupport", values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]]);
          break;
        case 9:
          AppelAjax(["ContacteSupport", values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8]]);
          break;
        case 10:
          if ($("#contact-subject").val() === "Candidature") {
            var observerCV = new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                if (mutation.addedNodes[0].data === "1") {
                  $("#contact-application-files-sent")
                    .val(parseInt($("#contact-application-files-sent").val()) + 1)
                    .trigger("change");
                }
              });
            });
            var observerLM = new MutationObserver(function (mutations) {
              mutations.forEach(function (mutation) {
                if (mutation.addedNodes[0].data === "1") {
                  $("#contact-application-files-sent")
                    .val(parseInt($("#contact-application-files-sent").val()) + 1)
                    .trigger("change");
                }
              });
            });
            const config = {
              attributes: true,
              childList: true,
              characterData: true,
            };
            observerCV.observe($("#tzM5")[0], config);
            observerLM.observe($("#tzM6")[0], config);
            $("#contact-application-files-sent").on("change", function () {
              if ($(this).val() === "2") {
                AppelAjax(["ContacteSupport", values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9]]);
                observerCV.disconnect();
                observerLM.disconnect();
              }
            });
          } else {
            AppelAjax(["ContacteSupport", values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7], values[8], values[9]]);
          }
          break;
      }
    }
  });
  $("#contact-subject").on("change", function () {
    $("#subject-fields").children().addClass("d-none");
    if ($(this).find(":selected").data("fields")) {
      const fields = $(this).find(":selected").data("fields").split(" ");
      $.each(fields, function (index, value) {
        $("label[for=contact-" + value + "]").removeClass("d-none");
        $("#contact-" + value).removeClass("d-none");
        $("#contact-" + value + "-filename").removeClass("d-none");
        $("#contact-" + value + "-filesize").removeClass("d-none");
      });
    }
  });
  $("#contact-application-resume").on("click", function (event) {
    event.preventDefault();
    event.stopPropagation();
    $("#M15").click();
  });
  $("#contact-application-letter").on("click", function (event) {
    event.preventDefault();
    event.stopPropagation();
    $("#M30").click();
  });
  //#endregion CONTACT

  // #region SEARCH
  $("#search-button").on("click", function (event) {
    let words = $("#search-input").val();
    window.location.href = window.location.href.split("/").slice(0, -1).join("/") + "/listing?rec=" + words + "&page=1";
  });
  let timer = 0;
  $("#search-input").on("keyup", function (event) {
    if (event.originalEvent) {
      if (event.key === "Enter") {
        window.location.href = window.location.href.split("/").slice(0, -1).join("/") + "/listing?rec=" + $("#search-input").val() + "&page=1";
      } else if (event.key === "Escape") {
        $("#search-results").hide();
      } else {
        if ($(this).val().length > 2) {
          clearTimeout(timer);
          timer = setTimeout(openSearch, 300);
        } else {
          $("#search-results").hide();
          $("#search-results").html("");
        }
      }
    }
  });

  $("#search-input").on("click", function (event) {
    event.stopPropagation();
    if ($("#search-results").html().length > 0) {
      $("#search-results").show();
    }
  });
  $(document).on("click", function (event) {
    var buttons = $("#desktop-search").toArray();
    if (buttons.indexOf(event.target.parentNode) === -1) {
      closeSearch();
    }
  });
  //#endregion SEARCH
});
// #region FUNCTIONS
function validateInput(inputID, inputName, inputType, errorMsg = "") {
  const inputValue = $("#" + inputID).val();
  let isValid = true;
  if (!inputValue) {
    $("#error-" + inputID + " > span").text(inputName + " invalide, champ vide interdit");
    $("#error-" + inputID).removeClass("d-none");
    isValid = false;
  } else {
    $("#error-" + inputID).addClass("d-none");
    const telRegex = new RegExp("^(?:(?:\\+|00)33|0)\\s*[1-9](?:[\\s.-]*\\d{2}){4}$", "gmi");
    const emailRegex = new RegExp('^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))' + "@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\" + ".[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$", "gmi");
    const strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})");
    // prettier-ignore
    if ((inputType === "phone"    && !telRegex.test(inputValue)) 
    ||  (inputType === "email"    && !emailRegex.test(inputValue)) 
    ||  (inputType === "text"     && !/^[A-Za-z\u00C0-\u017F0-9\s'`/\-,()\.]+$/.test(inputValue)) 
    ||  (inputType === "numbers"  && !/^[0-9]+$/.test(inputValue)) 
    ||  (inputType === "password" && !strongRegex.test(inputValue))
    ||  (inputType === "letters"  && !/^[A-Za-z\s'\-]+$/.test(inputValue))) {
      $("#error-" + inputID + " > span").text(errorMsg.length>0 ? errorMsg : inputName + " invalide");
      $("#error-" + inputID).removeClass("d-none");
      isValid = false;
    } else {
      $("#error-" + inputID).addClass("d-none");
    }
  }
  return isValid;
}
function HSLtoHEX(hsl) {
  let sep = hsl.indexOf(",") > -1 ? "," : " ";
  hsl = hsl.substr(4).split(")")[0].split(sep);
  let h = hsl[0],
    s = hsl[1].substr(0, hsl[1].length - 1) / 100,
    l = hsl[2].substr(0, hsl[2].length - 1) / 100;
  let a = s * Math.min(l, 1 - l);
  let f = (n, k = (n + h / 30) % 12) => l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
  return (
    "#" +
    [f(0), f(8), f(4)]
      .map((x) =>
        Math.round(x * 255)
          .toString(16)
          .padStart(2, 0)
      )
      .join("")
  );
}
function formatNumber(x) {
  var parts = parseFloat(x).toFixed(2).toString().split(".");
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
  if (parts[1] === "00") {
    return parts[0];
  } else {
    return parts.join(",");
  }
}
function parseNumber(x) {
  return parseFloat(x.replace(" ", "").replace(",", "."));
}
function popupMessage(title, message) {
  $("#modal-message-label").text(title);
  $("#modal-message .modal-body").html(message);
  $("#modal-message").modal("show");
}
function spinPage(active) {
  switch (active) {
    case true:
      document.getElementById("spinner-container").style.display = "block";
      break;
    case false:
      document.getElementById("spinner-container").style.display = "none";
      break;
  }
}

function shuffle(elems) {
  allElems = (function () {
    var ret = [],
      l = elems.length;
    while (l--) {
      ret[ret.length] = elems[l];
    }
    return ret;
  })();

  var shuffled = (function () {
      var l = allElems.length,
        ret = [];
      while (l--) {
        var random = Math.floor(Math.random() * allElems.length),
          randEl = allElems[random].cloneNode(true);
        allElems.splice(random, 1);
        ret[ret.length] = randEl;
      }
      return ret;
    })(),
    l = elems.length;

  while (l--) {
    elems[l].parentNode.insertBefore(shuffled[l], elems[l].nextSibling);
    elems[l].parentNode.removeChild(elems[l]);
  }
}
function openSearch() {
  AppelAjax(["RechercheArticles", $("#search-input").val()]);
  $("#search-spinner").removeClass("d-none");
}
function closeSearch() {
  $("#search-results").hide();
}
function monitorEvents(element) {
  var log = function (e) {
    console.log(e);
  };
  var events = [];

  for (var i in element) {
    if (i.startsWith("on")) events.push(i.substr(2));
  }
  events.forEach(function (eventName) {
    element.addEventListener(eventName, log);
  });
}
// #endregion FUNCTIONS
