/* Minification failed. Returning unminified contents.
(1,56-57): run-time warning JS1195: Expected expression: >
(5,18-19): run-time warning JS1004: Expected ';': l
(5,50-51): run-time warning JS1004: Expected ';': o
(5,53-54): run-time warning JS1006: Expected ')': l
(5,85-86): run-time warning JS1004: Expected ';': )
(11,1-2): run-time warning JS1002: Syntax error: }
(13,52-53): run-time warning JS1195: Expected expression: >
(16,9-10): run-time warning JS1004: Expected ';': f
(18,9-10): run-time warning JS1004: Expected ';': t
(33,27-28): run-time warning JS1195: Expected expression: >
(35,9-10): run-time warning JS1002: Syntax error: }
(39,17-18): run-time warning JS1004: Expected ';': l
(45,17-18): run-time warning JS1004: Expected ';': i
(47,25-26): run-time warning JS1195: Expected expression: )
(47,28-29): run-time warning JS1195: Expected expression: >
(54,13-14): run-time warning JS1002: Syntax error: }
(59,9-10): run-time warning JS1002: Syntax error: }
(61,57-58): run-time warning JS1195: Expected expression: )
(67,8-9): run-time warning JS1195: Expected expression: c
(67,40-41): run-time warning JS1004: Expected ';': o
(68,62-63): run-time warning JS1195: Expected expression: >
(70,5-6): run-time warning JS1002: Syntax error: }
(73,3-11): run-time warning JS1197: Too many errors. The file might not be a JavaScript file: function
(21,9-16): run-time warning JS1018: 'return' statement outside of function: return;
(34,13-36): run-time warning JS1018: 'return' statement outside of function: return response.text();
 */
document.addEventListener("DOMContentLoaded", (event) => {
    const loadAntiForgeryTokenOnSubmitDivs = document.querySelectorAll(".load-anti-forgery-token-on-submit-js");

    if (loadAntiForgeryTokenOnSubmitDivs.length > 0) {
        for (let loadAntiForgeryTokenOnSubmitDiv of loadAntiForgeryTokenOnSubmitDivs) {
            const closestForm = loadAntiForgeryTokenOnSubmitDiv.closest("form");

            closestForm.addEventListener("submit", onSubmitFormLoadAntiForgeryTokenEvent);
        }
    }
});

const onSubmitFormLoadAntiForgeryTokenEvent = (e) => {
    e.preventDefault();

    let form = e.target;

    let tokenLoadedAttributeValue = form.getAttribute("data-token-loaded");

    if (tokenLoadedAttributeValue === "true") {
        return;
    }

    fetch("GetAntiForgeryToken?cacheKill=" + new Date().getTime(),
        {
            headers: {
                "Accept": "application/json"
            },
            method: "GET",
            cache: 'no-cache',
            mode: "same-origin"
        })
        .then((response) => {
            return response.text();
        })
        .then((responseText) => {
            form.setAttribute("data-token-loaded", true);

            let loadAntiForgeryTokenOnSubmitDiv = form.querySelector(".load-anti-forgery-token-on-submit-js");

            loadAntiForgeryTokenOnSubmitDiv.innerHTML = responseText;

            form.removeEventListener("submit", onSubmitFormLoadAntiForgeryTokenEvent);

            let isAjaxForm = form.getAttribute("data-is-ajax-form") === "true";

            setTimeout(() => {
                //If the form does post with javascript event with ajax i needed to dispatch event. If form.submit() it ignores all javascript events and performs postback
                if (isAjaxForm) {
                    form.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
                } else {
                    form.submit();
                }
            },
                100);
        })
        .catch((error) => {
            console.log(error);
        });
};
document.addEventListener("DOMContentLoaded", function () {

  const showMoreContactInfoButtons = document.querySelectorAll(
    "[data-show-more-contact-info]"
  );

  for (const showMoreContactInfoButton of showMoreContactInfoButtons) {
    showMoreContactInfoButton.addEventListener("click", (e) => {
      showMoreContactInfo(e.target.id);
    });
  }

  function showMoreContactInfo(id) {
    var expandButton = document.getElementById(id);

    var showMoreContainerId = expandButton.getAttribute("aria-controls");
    var showMoreContainer = document.getElementById(showMoreContainerId);

    showMoreContainer.removeAttribute("hidden");

    expandButton.remove();
  }
});
;
document.addEventListener("DOMContentLoaded", function () {
  var largeCrisisBoxHasBeenClosed = sessionStorage.getItem(
    "largeCrisisBoxHasBeenClosed"
  );

  var mainAlertContainer = document.getElementById("main-alert-container");

  if (mainAlertContainer === null) {
    return false;
  }

  if (largeCrisisBoxHasBeenClosed && largeCrisisBoxHasBeenClosed === "true") {
    mainAlertContainer.style.display = "none";
  } else {
    mainAlertContainer.removeAttribute("hidden");
  }

  const closeCrisisLargeButton = document.querySelector(
    "[data-close-crisis-large]"
  );

  if (closeCrisisLargeButton !== null) {
    closeCrisisLargeButton.addEventListener("click", (e) => {
      hideCrisisLarge();
    });
  } else {
    return false;
  }
});

function hideCrisisLarge() {
  var mainAlertContainer = document.getElementById("main-alert-container");
  mainAlertContainer.setAttribute("hidden", "true");

  sessionStorage.setItem("largeCrisisBoxHasBeenClosed", true);
}
;
class Accordion {
    constructor(domNode) {
        this.accordionSectionRootEl = domNode;

        this.blockId = this.accordionSectionRootEl.getAttribute("data-id");
        this.buttonEl = this.accordionSectionRootEl.querySelector(
            "button[aria-expanded]"
        );

        const controlsId = this.buttonEl.getAttribute("aria-controls");
        this.contentEl = document.getElementById(controlsId);

        this.expandIconEl = this.accordionSectionRootEl.querySelector(
            ".accordion-block__icon--expand"
        );
        this.collapseIconEl = this.accordionSectionRootEl.querySelector(
            ".accordion-block__icon--collapse"
        );

        this.open = this.buttonEl.getAttribute("aria-expanded") === "true";

        // add event listeners
        this.buttonEl.addEventListener("click", this.onButtonClick.bind(this));
    }

    onButtonClick() {
        this.toggle(!this.open);
    }

    toggle(open) {
        // don't do anything if the open state doesn't change
        if (open === this.open) {
            return;
        }

        // update the internal state
        this.open = open;

        // handle DOM updates
        this.buttonEl.setAttribute("aria-expanded", `${open}`);

        open
            ? this.contentEl.removeAttribute("hidden")
            : this.contentEl.setAttribute("hidden", "");

        open
            ? this.collapseIconEl.classList.remove("hidden")
            : this.collapseIconEl.classList.add("hidden");

        open
            ? this.expandIconEl.classList.add("hidden")
            : this.expandIconEl.classList.remove("hidden");

        open
            ? this.accordionSectionRootEl.classList.add(
                "accordion-block__section--expanded"
            )
            : this.accordionSectionRootEl.classList.remove(
                "accordion-block__section--expanded"
            );

        if (open) {
            window.location.hash = this.blockId;
        }
    }
}

function initAccordions() {
    // init accordions
    const accordions = document.querySelectorAll(".accordion-block__section--js");

    accordions.forEach((accordionEl) => {
        new Accordion(accordionEl);
    });

    if (
        accordions.length > 0 &&
        window.location.hash &&
        window.location.hash.length > 0
    ) {
        console.log("window.location.hash : ", window.location.hash);
        openAccordionBasedOnHash(window.location.hash);
    }
}

document.addEventListener("DOMContentLoaded", function () {
    initAccordions();
});

function openAccordionBasedOnHash(hash) {
    let dataID = hash.replace("#", "");

    let accordionEl = document.querySelector(`[data-id="${dataID}"]`);

    if (!accordionEl) {
        return false;
    }

    expandAncestorsIfExists(accordionEl);

    let accordionButtonEl = accordionEl.querySelector("button[aria-expanded]");

    if (!accordionButtonEl) {
        return false;
    }

    accordionButtonEl.click();

    setTimeout(function () {
        accordionButtonEl.scrollIntoView({
            behavior: "smooth",
        });
    }, 100);
}

//IF level two section need to expand lvl 1 section aswell
function expandAncestorsIfExists(accordionEl) {
    var ancestors = getAncestorsWithClass(
        accordionEl,
        "accordion-block__section"
    );

    if (ancestors && ancestors.length > 0) {
        ancestors.forEach((ancestor) => {
            let ancestorButton = ancestor.querySelector("button[aria-expanded]");

            ancestorButton.click();
        });
    }
}

//Can be moved to helper javascript file later when we use webpack with es6 modules
function getAncestorsWithClass(element, className) {
    let nodes = [];

    while (element.parentElement) {
        if (element.parentElement.classList.contains(className)) {
            nodes.unshift(element.parentElement);
        }
        element = element.parentElement;
    }

    return nodes;
}

function sendMailToAllChildLinksContainingMailTo(button) {
    // Container
    var content = button.parentNode.parentNode;
    if (!content) return;

    var allLinks = Array.from(content.querySelectorAll("a[href^='mailto']"));
    
    var allEmails = allLinks.map(function (email) {
        return email.href.replace("mailto:", "")
    });
    var fullEmailStr = "mailto:" + allEmails.join(";");

    const emailLink = document.createElement("a");
    emailLink.href = fullEmailStr;
    emailLink.target = "_self";

    emailLink.click();
};
document.addEventListener("DOMContentLoaded", function (event) {
  (function () {
    const handleFeedbackButtonClick = function (isPositive, onSuccessFunc) {
      if (isPosting) {
        return false;
      }

      const pageName = document.getElementById("current-page-name").value;

      isPosting = true;

      const postModel = {
        pageExternalUrl: window.location.href,
        pageName,
        isPositive,
      };

      const positiveFeedbackError = document.getElementById("simple-feedback-error");
      positiveFeedbackError.setAttribute("hidden", "true");

      fetch(`/PageFeedback/SendSimplePageFeedback`, {
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
        body: JSON.stringify(postModel),
        method: "POST",
        mode: "same-origin",
      })
        .then(handleFetchResponse)
        .then(function (json) {
          onSuccessFunc();

          isPosting = false;
        })
        .catch(function (error) {
          positiveFeedbackError.removeAttribute("hidden");

          setTimeout(function () {
            isPosting = false;
          }, 3000);
        });
    };

    const onFeedbackSuccess = function (doScrollToSuccessDiv = false) {
      const successDiv = document.querySelector(".page-feedback__success");
      const mainPageFeedbackView = document.querySelector(".page-feedback");

      successDiv.removeAttribute("hidden");
      mainPageFeedbackView.setAttribute("hidden", "true");

      if (doScrollToSuccessDiv) {
        successDiv.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });
      }
    };

    const onCancelNegativeFeedback = function (feedBackForm, openFeedbackButton, feedbackControls) {
      feedBackForm.setAttribute("hidden", "true");
      feedbackControls.removeAttribute("hidden");
      openFeedbackButton.setAttribute("aria-expanded", "false");
      openFeedbackButton.focus();
      clearInvalidationState();
    };

    const onNegativeFeedbackSuccess = function () {
      negativeFeedbackButton.setAttribute("aria-expanded", "true");
      pageNegativeFeedbackForm.removeAttribute("hidden");
      loadAntiForgeryTokenOnNegativeFeedbackForm();

      pageNegativeFeedbackForm.elements.Comment.focus();
      feedbackControlButtons.setAttribute("hidden", "");
    };

    const clearInvalidationState = function () {
      const validationErrorException = document.getElementById("Comment_error");
      const unexpectedErrorException = document.getElementById(
        "feedback-form-unexpected-exception"
      );

      pageNegativeFeedbackForm.elements.Comment.classList.remove("page-feedback__field--invalid");
      pageNegativeFeedbackForm.elements.Comment.removeAttribute("aria-describedby");
      validationErrorException.setAttribute("hidden", "true");
      validationErrorException.innerText = "";

      unexpectedErrorException.setAttribute("hidden", "true");
    };

    const onSubmitNegativeFeedbackForm = function (e) {
      e.preventDefault();
      const submitButton = document.getElementById("submit-button-page-negative-feedback-form");

      if (isPosting) {
        console.log("Unexpected error - form is already posting");
        return false;
      }

      var form = e.target;
      let tokenLoadedAttributeValue = form.getAttribute("data-token-loaded");

      if (tokenLoadedAttributeValue !== "true") {
        console.log("Unexpected error - the form's token wasn't loaded before submission");

        return false;
      }
      clearInvalidationState();

      isPosting = true;
      submitButton.disabled = true;

      const formData = new FormData(form);
      formData.append("ExternalUrl", window.location.href);
      fetch(`/PageFeedback/SendNegativeFeedbackForm`, {
        headers: {
          Accept: "application/json",
        },
        body: formData,
        method: "POST",
        mode: "same-origin",
      })
        .then(handleFetchResponse)
        .then(function (json) {
          onFeedbackSuccess(true);
        })
        .catch(function (error) {
          setTimeout(() => {
            isPosting = false;
            submitButton.disabled = false;
          }, 3000);

          if (error.status && error.status === 400) {
            handleSubmitValidationError(error);
          }

          //500 error unexpected
          else {
            let unexpectedErrorException = document.getElementById(
              "feedback-form-unexpected-exception"
            );
            unexpectedErrorException.removeAttribute("hidden");
          }
        });
    };

    //TODO move to module when we render scripts with webpack
    const handleFetchResponse = function (response) {
      return response.json().then(function (json) {
        if (!response.ok) {
          const error = Object.assign({}, json, {
            status: response.status,
            statusText: response.statusText,
          });
          return Promise.reject(error);
        }

        return json;
      });
    };
    //For honeypot don't want to use thats name on function.
    //TODO Move to module and import when we use webpack. (stolen from scripts.js)
    const initializeXOnForm = function (isPostback, formId, submitButtonId) {
      var focusedAt;
      var loadedAt = Date.now();

      var conf = {
        inPoint: "firstname-hp",
        outPoint: "lastname-hp",
      };

      var form = document.getElementById(formId);
      var inPoint = document.getElementById(conf.inPoint);
      var outPoint = document.getElementById(conf.outPoint);
      var send = document.getElementById(submitButtonId);

      var setInPoint = function (e) {
        focusedAt = Date.now();
        var inPointAt = !isPostback ? focusedAt : loadedAt;

        inPoint.value = inPointAt;
        form.removeEventListener("focusin", setInPoint);
      };

      var setOutPoint = function (e) {
        var sendAt = Date.now();
        outPoint.value = sendAt;
      };

      form.addEventListener("focusin", setInPoint);
      send.addEventListener("click", setOutPoint);
    };

    const handleSubmitValidationError = function (error) {
      let unexpectedErrorException = document.getElementById("feedback-form-unexpected-exception");

      error.Errors.forEach(function (msg) {
        let [field] = msg.MemberNames;
        let errorMsg = msg.ErrorMessage;
        if (field) {
          let input = document.getElementById(`${field}_input`);
          input.setAttribute("aria-describedby", `${field}_error`);
          input.classList.add("page-feedback__field--invalid");

          let errorElement = document.getElementById(`${field}_error`);
          errorElement.removeAttribute("hidden");

          let node = document.createTextNode(errorMsg);
          errorElement.appendChild(node);
        } else {
          unexpectedErrorException.removeAttribute("hidden");
          unexpectedErrorException.innerText = errorMsg;
        }
      });
      pageNegativeFeedbackForm.elements.Comment.focus();
    };

    const loadAntiForgeryTokenOnNegativeFeedbackForm = function () {
      let tokenLoadedAttributeValue = pageNegativeFeedbackForm.getAttribute("data-token-loaded");

      if (tokenLoadedAttributeValue === "true") {
        return;
      }

      const controllerUrl = document.getElementById("controller-url").value;

      fetch(controllerUrl + "GetAntiForgeryToken?cacheKill=" + new Date().getTime(), {
        headers: {
          Accept: "application/json",
        },
        method: "GET",
        cache: "no-cache",
        mode: "same-origin",
      })
        .then(function (response) {
          return response.text();
        })
        .then(function (responseText) {
          pageNegativeFeedbackForm.setAttribute("data-token-loaded", true);

          let antiForgeryTokenContainer = document.getElementById(
            "page-feedback-anti-forgery-token-js"
          );
          antiForgeryTokenContainer.innerHTML = responseText;
          negativeFeedbackButton.focus();
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    let isPosting = false;

    var positiveFeedBackButton = document.getElementById("positive-feedback-button");

    //has no feedback form. So don't register events
    if (!positiveFeedBackButton) {
      return false;
    }

    var feedbackControlButtons = document.getElementById("page-feedback-main-view");

    var negativeFeedbackButton = document.getElementById("negative-feedback-button");

    var pageNegativeFeedbackForm = document.getElementById("page-negative-feedback-form");

    var negativeFeedBackCancelButton = document.getElementById(
      "submit-button-page-negative-feedback-cancel"
    );

    positiveFeedBackButton.addEventListener("click", function (e) {
      handleFeedbackButtonClick(true, onFeedbackSuccess);
    });

    negativeFeedbackButton.addEventListener("click", function (e) {
      e.preventDefault();
      handleFeedbackButtonClick(false, onNegativeFeedbackSuccess);
    });

    pageNegativeFeedbackForm.addEventListener("submit", onSubmitNegativeFeedbackForm);

    negativeFeedBackCancelButton.addEventListener("click", function (e) {
      onCancelNegativeFeedback(
        pageNegativeFeedbackForm,
        negativeFeedbackButton,
        feedbackControlButtons
      );
    });

    initializeXOnForm(
      false,
      "page-negative-feedback-form",
      "submit-button-page-negative-feedback-form"
    );
  })();
});
;
document.addEventListener(
  "DOMContentLoaded",

  (function () {
    const discloseWrapperAttribute = "data-header-expander";
    const discloseDataAttr = "data-disclose";
    const transitionDurationCssProperty = "--js-menu-expand-duration";
    const shimHeightCssProperty = "--js-expand-shim-height";
    const siteHeaderHeightCssProperty = "--js-site-header-height";

    const discloseState = {
      up: "up",
      down: "down",
      beforeup: "beforeup",
      beforedown: "beforedown",
      done: "done",
    };

    const topMenuClick = (button, panel, id, callback) => {
      return new CustomEvent("top.menu.click", {
        bubbles: true,
        detail: {
          button: button,
          panel: panel,
          id: id,
          callback: callback,
        },
      });
    };

    const nav = document.getElementById("top-menu-js");
    /* TODO:REFACTOR change HTML add class to hook with js prefix or use data-attribute */
    const buttonsNodeCollection = nav.querySelectorAll(
      "button.top-menu__disclose-button"
    );

    let navigationButtons = {};
    let expandableMenu = {};
    const discloseWrapper = document.querySelector(
      `[${discloseWrapperAttribute}]`
    );

    //Transitions delay can be use to adjust animation
    const transitionDurationStr = getComputedStyle(
      discloseWrapper
    ).getPropertyValue(transitionDurationCssProperty);
    const transitionDuration = transitionDurationStr.match(/([\d])+/g)[0];
    const transitionStartDelay = 5;

    // Top position of expanded menu --js-site-header-height
    const setExpandedMenyTopPosition = () => {
      if (
        discloseWrapper.getAttribute(discloseWrapperAttribute) === "expanded"
      ) {
        return false;
      }
      discloseWrapper.style.setProperty(
        siteHeaderHeightCssProperty,
        `${discloseWrapper.offsetHeight}px`
      );
    };

    setExpandedMenyTopPosition();
    onresize = () => setExpandedMenyTopPosition();

    let collapseShim = () => {
      discloseWrapper.style.setProperty(shimHeightCssProperty, "0px");
      discloseWrapper.setAttribute(discloseWrapperAttribute, "collapsed");
    };

    let expandShim = (el) => {
      discloseWrapper.style.setProperty(
        shimHeightCssProperty,
        `${el.offsetHeight}px`
      );
      discloseWrapper.setAttribute(discloseWrapperAttribute, "expanded");
    };

    let getExpandedButton = () => nav.querySelector('[aria-expanded="true"]');
    let getAriaControlledBy = (el) => navigationButtons[el.id];
    let getAriaControls = (el) => expandableMenu[getAriaControlsId(el)];
    let getAriaControlsId = (el) => el.getAttribute("aria-controls");

    let closeMenu = (el) => el.setAttribute("aria-expanded", "false");
    let openMenu = (el) => el.setAttribute("aria-expanded", "true");

    //Set data-disclose attribute
    let discloseBeforeUp = (el) =>
      el.setAttribute(discloseDataAttr, discloseState.beforeup);
    let discloseUp = (el) =>
      el.setAttribute(discloseDataAttr, discloseState.up);
    let discloseBeforeDown = (el) =>
      el.setAttribute(discloseDataAttr, discloseState.beforedown);
    let discloseDown = (el) =>
      el.setAttribute(discloseDataAttr, discloseState.down);
    let discloseDone = (el) =>
      el.setAttribute(discloseDataAttr, discloseState.done);
    let getDiscloseState = (el) => el.getAttribute(discloseDataAttr);

    let onBeforeUp = (el) => {
      setTimeout(() => {
        discloseUp(el);
      }, transitionStartDelay);
    };

    let onUp = (panel) => {
      let button = getAriaControlledBy(panel);
      collapseShim();
      closeMenu(button);
      setTimeout(() => {
        discloseDone(panel);
      }, transitionDuration);
    };

    let onBeforeDown = (el) => {
      setTimeout(() => {
        expandShim(el);
        discloseDown(el);
      }, transitionStartDelay);
    };

    let onDown = (panel) => {
      let button = getAriaControlledBy(panel);
      openMenu(button);
        if (panel.id === "topNavSearch") {
            let searchInput = document.getElementById("top-search-field");
            searchInput.focus();
        }
        
      setTimeout(() => {
        discloseDone(panel);
      }, transitionDuration);
    };

    const targetNode = document.querySelector(".site-header");
    const config = { attributes: true, childList: true, subtree: true };

    const callback = (mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === "attributes" && mutation.attributeName) {
          let panel = mutation.target;
          if (getDiscloseState(panel) == discloseState.beforedown) {
            onBeforeDown(panel);
          } else if (getDiscloseState(panel) == discloseState.down) {
            onDown(panel);
          } else if (getDiscloseState(panel) == discloseState.beforeup) {
            onBeforeUp(panel);
          } else if (getDiscloseState(panel) == discloseState.up) {
            onUp(panel);
          }
        }
      }
    };

    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);

    nav.addEventListener(
      "top.menu.click",
      (e) => {
        let button = e.detail.button;
        let panel = e.detail.panel;
        let expandedButton = getExpandedButton();

        if (button.getAttribute("aria-expanded") === "true") {
          discloseBeforeUp(panel);
        } else if (!expandedButton) {
          discloseBeforeDown(panel);
        } else if (expandedButton && !button.isSameNode(expandedButton)) {
          let expandedPanel = getAriaControls(expandedButton);
          discloseBeforeUp(expandedPanel);
          discloseBeforeDown(panel);
        }
      },
      true
    );

    //Close on escepe
    document.onkeydown = function (evt) {
      evt = evt || window.event;
      if (evt.keyCode == 27) {
        let expandedButton = getExpandedButton();
        if (expandedButton) {
          discloseBeforeUp(getAriaControls(expandedButton));
        }
      }
    };

    //Initialize
    for (let i = 0; i < buttonsNodeCollection.length; i++) {
      let button = buttonsNodeCollection[i];
      let ariaControlsId = button.getAttribute("aria-controls");
      let ariaControlled = document.getElementById(ariaControlsId);
      navigationButtons[ariaControlsId] = button;
      expandableMenu[ariaControlsId] = ariaControlled;

      button.addEventListener(
        "click",
        (e) => {
          button.dispatchEvent(
            topMenuClick(button, ariaControlled, ariaControlsId)
          );
        },
        true
      );
    }
  })()
);
;
document.addEventListener(
  "DOMContentLoaded",

  (function () {
    const selectors = {
      siteHeaderMobile: ".site-header-mobile",
      menuButton: "MobileMenuButton",
      mobileRootMenu: "MobileRootMenu",
      mobileMenuSearchButton: "MobileSearchMenuButton",
      mobileSearchForm: "MobileSearchForm",
      mainContent: "main-content",
      footer: "footer",
    };
    const cssTransitionClass = {
      expand: "expand",
      collapse: "collapse",
    };

    const menuLevels = {
      root: {
        attr: "data-mmi-root",
        values: {
          collapsed: "collapsed",
          expanded: "expanded",
        },
      },
      sublevel: {
        attr: "data-mmi-sublevel",
      },
    };
    const siteHeaderMobile = document.querySelector(selectors.siteHeaderMobile);
    const searchForm = document.getElementById(selectors.mobileSearchForm);
    const searchButton = document.getElementById(
      selectors.mobileMenuSearchButton
    );

    const mainContent = document.getElementById(selectors.mainContent);
    const footer = document.querySelector(selectors.footer);
    const menuButton = document.getElementById(selectors.menuButton);
    const mobileRootMenu = document.getElementById(selectors.mobileRootMenu);
    const rootItemSelector = `[${menuLevels.root.attr}]`;
    const rootMenuItems = Array.from(
      document.querySelectorAll(rootItemSelector)
    );

    var transitionDurationCss = getComputedStyle(
      siteHeaderMobile
    ).getPropertyValue("--menu-transition-duration");
    transitionDurationCss = transitionDurationCss ?? "400ms";

    const transitionDurationStr = transitionDurationCss.match(/([\d])+/g)[0];
    const transitionDuration = Number.parseInt(transitionDurationStr);
    const transitionStartDelay = 5;
    var firstFocusable, lastFocusable;

    /* toggle search form */
    searchButton.addEventListener("click", function () {
      toggleMobileSearch(searchButton);
    });

    /* set esc to exit menu and search */
    const exitOnEsc = document.querySelectorAll("[data-exit-esc]");
    addEventExitOnEsc(exitOnEsc);

    /* Set menu to closed onload */
    closeMenuOverlay();

    /*toggle hamgurger menu */
    menuButton.addEventListener("click", function () {
      toggleMobileMenu(menuButton);
    });

    /*toggle menu items */
    mobileRootMenu.addEventListener("click", function (e) {
      if (e.target.ariaExpanded === null) {
        return false;
      }

      /*
        currently selected menu item / button
        */
      var pressedButton = event.target;

      /*
        root level button pressed
        */
      if (isRootLevelButton(pressedButton)) {
        toggle1stLevel(pressedButton, true);
      }

      /*
        sublevels
        */
      if (isSublevelButton(pressedButton)) {
        toggleSublevelItem(pressedButton);
      }
    });
    
    function addEventExitOnEsc(elems) {
      elems.forEach(function (el) {
        el.addEventListener("keyup", function (e) {
      if (e.type === "keyup" && e.key === "Escape") {
            let escFor = el.getAttribute("data-exit-esc");
          if (escFor === selectors.menuButton) {
              collapseMobileMenu(menuButton, true, true);
              menuButton.focus();
              return;
          }
          if (escFor === selectors.mobileMenuSearchButton) {
              collapseMobileSearch(searchButton, true, true);
              searchButton.focus();
              return;
          }
      }
        });
      });
    }

    const toggleInert = (...args) => {
        args.forEach(element => {
            if (!element.nodeType) {
                return;
            }

            if (element.getAttribute("inert") === null) {
                element.setAttribute("inert", "true");
                element.setAttribute("aria-hidden", "true");
            } else {
                element.removeAttribute("inert");
                element.removeAttribute("aria-hidden");
            }
        });
    };

    function collapseMobileSearch(elem, animate, shouldCloseOverlay) {
      if (!isAriaExpanded(elem)) {
        return;
      }

      let start = function () {
        closeMenuOverlay(true);
      };

      let end = function () {
        collapseAria(elem);
      };

      let callbacks = shouldCloseOverlay ? { start, end } : { end };

      if (animate) {
        animateCssTransition(
          cssTransitionClass.collapse,
          elem,
          callbacks,
          setAnimationDuration(0.5)
        );
      } else {
        end();
      }
      toggleInert(mainContent, footer);
    }

    function expandMobileSearch(elem, animate) {
      if (isAriaExpanded(elem)) {
        return;
      }

      collapseMobileMenu(menuButton, true, false);

      let start = function () {
        openMenuOverlay(true);
      };

      let end = function () {
        expandAria(elem);
        focusableInSearch();
      };

      let callbacks = !isOverlayOpen() ? { start, end } : { end };

      if (animate) {
        animateCssTransition(
          cssTransitionClass.expand,
          elem,
          callbacks,
          setAnimationDuration(1)
        );
      } else {
        start();
        end();
      }
      toggleInert(mainContent, footer);
    }

    function toggleMobileSearch(elem) {
      if (!isAriaExpanded(elem)) {
        expandMobileSearch(elem, true);
      } else {
        collapseMobileSearch(elem, true, true);
      }
    }

    function collapseMobileMenu(elem, animate, shouldCloseOverlay) {
      if (!isAriaExpanded(elem)) {
        return;
      }

      let start = function () {
        closeMenuOverlay(true);
      };

      let end = function () {
        collapseAria(elem);
        clearAllRootItemState();
        collapseSublevelItems(elem);
        focusableInMenu(elem);
      };

      let callbacks = shouldCloseOverlay ? { start, end } : { end };

      if (animate) {
        animateCssTransition(
          cssTransitionClass.collapse,
          elem,
          callbacks,
          setAnimationDuration(0.5)
        );
      } else {
        end();
      }
      toggleInert(mainContent, footer);
    }

    function expandMobileMenu(elem) {
      if (isAriaExpanded(elem)) {
        return;
      }

      /* let shouldOpenOverlay = !isOverlayOpen(); */
      collapseMobileSearch(searchButton, true, false);

      let start = function () {
        openMenuOverlay(true);
      };

      let during = function () {
        expandAria(elem);
      };

      let end = function () {
        focusableInMenu(getAriaCurrentPage() || elem);
      };
      let callbacks = !isOverlayOpen()
        ? { start, during, end }
        : { during, end };

      expandMenuToCurrentPage();
      animateCssTransition(
        cssTransitionClass.expand,
        elem,
        callbacks,
        setAnimationDuration(1)
      );
      toggleInert(mainContent, footer);
    }

    function toggleMobileMenu(elem) {
      if (!isAriaExpanded(elem)) {
        expandMobileMenu(elem);
      } else {
        collapseMobileMenu(elem, true, true);
      }
    }

    function expand1stLevel(elem, animate) {
      let menuItem = elem.closest("li");

      let expanding = function () {
        expandAria(elem);
      };

      let expandingEnd = function () {
        focusableInMenu(elem);
      };

      if (animate) {
         collapseAllRootItemState();
         expandRootItemState(menuItem);
         animateCssTransition(cssTransitionClass.expand, elem, {
           start: expanding,
           end: expandingEnd,
      });
      } else {
         collapseAllRootItemState();
         expandRootItemState(menuItem);
         expanding();
         expandingEnd();
      }
    }

    function collapse1stLevel(elem, animate) {
      let start = function () {
        clearAllRootItemState();
      };
      let collapsing = function () {
        focusableInMenu(elem);
      };

      if (animate) {
        collapseAria(elem);
        collapseSublevelItems(elem);
        clearAllRootItemState();
        animateCssTransition(
          cssTransitionClass.expand,
          mobileRootMenu,
          {
            start: start,
            end: collapsing,
          },
          setAnimationDuration(0.5)
        );
      } else {
        collapseAria(elem);
        collapseSublevelItems(elem);
        
        collapsing();
      }
    }

    function toggle1stLevel(elem, animate) {
      if (!isAriaExpanded(elem)) {
        expand1stLevel(elem, animate);
      } else {
        collapse1stLevel(elem, animate);
      }
    }

    function toggleSublevelItem(elem) {
      if (isAriaExpanded(elem)) {
        collapseSublevel(elem, true);
      } else {
        expandSublevel(elem, true);
      }
      focusableInMenu(elem);
    }

    function expandSublevel(elem, animate) {
      let end = function () {
        expandAria(elem);
        setMaxHeightForSublevelMenu(elem, 0);
        focusableInMenu(elem);
      };

      if (!animate) {
        expandAria(elem);
      } else {
        setMaxHeightForSublevelMenu(elem);
        animateCssTransition(cssTransitionClass.expand, elem, { end: end });
      }
    }

    function collapseSublevel(elem, animate) {
      let end = function () {
        collapseAria(elem);
        setMaxHeightForSublevelMenu(elem, 0);
        collapseSublevelItems(elem);
        focusableInMenu(elem);
      };

      if (!animate) {
        collapseAria(elem);
        return;
      } else {
        let maxHeight = getSubmenuForButton(elem).offsetHeight;
        setMaxHeightForSublevelMenu(elem, maxHeight);
        animateCssTransition(
          cssTransitionClass.collapse,
          elem,
          {
            end: end,
          },
          setAnimationDuration(0.5)
        );
      }
    }

    function setMaxHeightForSublevelMenu(elem, maxHeight) {
      let hiddenMenu = getSubmenuForButton(elem);
      let subMenuMaxHeight =
        maxHeight ?? hiddenMenu.children.length * elem.offsetHeight * 1.1;

      mobileRootMenu.style.setProperty(
        "--js-approximate-max-height",
        `${subMenuMaxHeight}px`
      );
    }

    function setAnimationDuration(ratio) {
      let duration = ratio * transitionDuration;
      siteHeaderMobile.style.setProperty(
        "--menu-transition-duration",
        `${duration}ms`
      );
      return duration;
    }

    function resetAnimationDuration() {
      siteHeaderMobile.style.setProperty(
        "--menu-transition-duration",
        `${transitionDuration}ms`
      );
    }

    function openMenuOverlay(animate) {
      let start = function () {
        document.documentElement.classList.add("mobile-menu--open");
        document.documentElement.classList.remove("mobile-menu--closed");
      };

      if (animate) {
        animateCssTransition("open", document.documentElement, {
          start: start,
        });
      } else {
        start();
      }
    }

    function closeMenuOverlay(animate) {
      let end = function () {
        document.documentElement.classList.remove("mobile-menu--open");
        document.documentElement.classList.add("mobile-menu--closed");
      };

      if (animate) {
        animateCssTransition(
          "close",
          document.documentElement,
          {
            end: end,
          },
          setAnimationDuration(0.5)
        );
      } else {
        end();
      }
    }

    function isOverlayOpen() {
      return document.documentElement.classList.contains("mobile-menu--open");
    }

    function isRootLevelButton(elem) {
      let menuItem = elem.closest("li");
      if (!menuItem) return false;
      return menuItem.hasAttribute(menuLevels.root.attr);
    }

    function isSublevelButton(elem) {
      let menuItem = elem.closest("li");
      return menuItem.hasAttribute(menuLevels.sublevel.attr);
    }

    function expandAria(elem) {
      elem.setAttribute("aria-expanded", "true");
    }

    function collapseAria(elem) {
      elem.setAttribute("aria-expanded", "false");
    }

    function animateCssTransition(cssClass, elem, callback, duration) {
      elem.classList.add(`transition-${cssClass}`);
      elem.classList.add(`start-${cssClass}`);
      let start = function () {
        if (callback.start) {
          callback.start.call();
        }
        elem.classList.add(`during-${cssClass}`);
        elem.classList.remove(`start-${cssClass}`);
      };

      let during = function () {
        if (callback.during) {
          callback.during.call();
        }
        elem.classList.add(`end-${cssClass}`);
        elem.classList.remove(`during-${cssClass}`);
      };

      let end = function () {
        if (callback.end) {
          callback.end.call();
        }
        elem.classList.remove(`transition-${cssClass}`);
        elem.classList.remove(`end-${cssClass}`);
        resetAnimationDuration();
      };
      let animationDuration = duration ?? transitionDuration;
      setTimeout(start, transitionStartDelay);
      setTimeout(during, animationDuration - transitionStartDelay);
      setTimeout(end, animationDuration);
    }

    function isAriaExpanded(elem) {
      if (elem.getAttribute("aria-expanded") === "false") {
        return false;
      }
      if (elem.getAttribute("aria-expanded") === "true") {
        return true;
      }
    }

    function collapseRootItemState(elem) {
      elem.setAttribute(menuLevels.root.attr, menuLevels.root.values.collapsed);
    }

    function expandRootItemState(elem) {
      elem.setAttribute(menuLevels.root.attr, menuLevels.root.values.expanded);
    }

    function clearRootItemState(elem) {
      elem.setAttribute(menuLevels.root.attr, "");
    }

    function clearAllRootItemState() {
      rootMenuItems.forEach((item) => {
        clearRootItemState(item);
      });
    }

    function collapseSublevelItems(elem) {
      let currentSubmenu = getSubmenuForButton(elem);
      let openItems = currentSubmenu.querySelectorAll("[aria-expanded='true']");
      openItems.forEach((item) => {
        collapseAria(item);
      });
    }

    function getSubmenuForButton(elem) {
      let currentSubmenuId = elem.getAttribute("aria-controls");
      return document.getElementById(currentSubmenuId);
    }

    function getButtonForSubmenu(elem) {
      return elem.parentElement.querySelector(`[aria-controls=${elem.id}`);
    }

    function collapseAllRootItemState() {
      rootMenuItems.forEach((item) => {
        collapseRootItemState(item);
      });
    }

    function ariaControlsForCurrent(elem) {
      let children = elem.closest("li")?.children;
      return Array.from(children).find((el) =>
        el.hasAttribute("aria-controls")
      );
    }

    function expandMenuToCurrentPage() {
      var currentLocation = getAriaCurrentPage();
      if (!currentLocation) {
        return;
      }
      if (isRootLevelButton(currentLocation)) {
        expand1stLevel(currentLocation, false);
      } else {
        let expanButtonForCurrent = ariaControlsForCurrent(currentLocation);
        if (expanButtonForCurrent) {
          expandSublevel(expanButtonForCurrent, false);
        }
        expandParent(currentLocation);
      }
    }

    function expandParent(elem) {
      let menuList = elem.closest("ul");
      let parentExpandButton = getButtonForSubmenu(menuList);

      if (isRootLevelButton(parentExpandButton)) {
        expand1stLevel(parentExpandButton, false);
      } else {
        expandSublevel(parentExpandButton, false);
        expandParent(parentExpandButton);
      }
    }

    function getAriaCurrentPage() {
      var rootMenu = document.getElementById(selectors.mobileRootMenu);
      return rootMenu.querySelector("[aria-current='page']");
    }

    function focusableInSearch() {
      lastFocusable = searchForm.querySelector("button");
      firstFocusable = searchButton;
      lastFocusable.addEventListener("keydown", moveFocusToTop);
    }

    function showsRootLevel(elem) {
      if (elem === menuButton) {
        return true;
      }
      return isRootLevelButton(elem) && !isAriaExpanded(elem);
    }

    function focusableInMenu(elem) {
      let querySublevel =
        "li > *:is(.mobile-menu__link--sublevel, .mobile-menu__btn--sublevel)";
      let queryRoot = ".mobile-menu__item--root > *:is(a, button)";
      let queryVisible = showsRootLevel(elem) ? queryRoot : querySublevel;
      if (lastFocusable) {
        lastFocusable.removeEventListener("keydown", moveFocusToTop);
      }

      firstFocusable = menuButton;

      var focusable = mobileRootMenu.querySelectorAll(
        `[aria-expanded=true] + ul > ${queryVisible}`
        );
      var focusableBackButton = mobileRootMenu.querySelector("button[aria-expanded=true]");

      if (focusable.length > 0) {
        lastFocusable = focusable.item(focusable.length - 1);
      } 
      if (focusable.length === 0 && focusableBackButton) {
        lastFocusable = focusableBackButton;
      }
      if (lastFocusable) {
        lastFocusable.addEventListener("keydown", moveFocusToTop);
      }
    }

    function moveFocusToTop(e) {
      if (e.key === "Tab" && !e.shiftKey) {
        e.preventDefault();
        firstFocusable.focus();
      }
    }
    return null;
  })()
);
;
document.addEventListener("DOMContentLoaded", function () {
  const AutoCompleteSearchUrlPath = "/find/rest/autocomplete/get/";

  const mobileSearchInputFieldId = "MobileSearchField";
  const desktopSearchFieldId = "top-search-field";

  const searchInputDesktopSearch = document.getElementById(desktopSearchFieldId);
  const searchInputMobileSearch = document.getElementById(mobileSearchInputFieldId);

  const desktopAutoCompleteList = document.getElementById("top-search-autocomplete-listbox");
  const mobileAutoCompleteList = document.getElementById("mobile-top-search-autocomplete-listbox");

  const svgSearchIcon =
    '<svg class="autocomplete__button-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path fill="none" d="M0 0h24v24H0z"></path><path d="M18.031 16.617l4.283 4.282-1.415 1.415-4.282-4.283A8.96 8.96 0 0 1 11 20c-4.968 0-9-4.032-9-9s4.032-9 9-9 9 4.032 9 9a8.96 8.96 0 0 1-1.969 5.617zm-2.006-.742A6.977 6.977 0 0 0 18 11c0-3.868-3.133-7-7-7-3.868 0-7 3.132-7 7 0 3.867 3.132 7 7 7a6.977 6.977 0 0 0 4.875-1.975l.15-.15z"></path></svg>';

  let autoCompleteOptions = [];
  let autoCompleteLoading = false;
  let inputValue = "";
  let isMobileSearch = false;

  let arrowCounter = -1;

  const debounce = (func, delay) => {
    let timeoutId;
    return function (...args) {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(() => func.apply(this, args), delay);
    };
  };

  const onInputChange = (event) => {
    inputValue = event.target.value;

    isMobileSearch = event.target.id === mobileSearchInputFieldId;

    if (inputValue.length < 3) {
      autoCompleteOptions.length = 0;
      return false;
    }

    debounceSearch();
  };

  const autocompleteSearch = () => {
    autoCompleteLoading = true;

    let siteGuidElement = document.getElementById("currentSiteGUID");

    let siteId = siteGuidElement.value;
    let searchUrl = `${AutoCompleteSearchUrlPath}${inputValue}/5?tag=siteid:${siteId}`;

    fetch(searchUrl)
      .then((response) => {
        if (!response.ok) {
          throw new Error(`Network response was not ok: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        autoCompleteOptions = data.Hits;
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        autoCompleteLoading = false;
        updateAutoCompleteList();
      });
  };

  const debounceSearch = debounce(autocompleteSearch, 300);

  const handleClickOutside = (event) => {
    let isClickInside;

    let currentAutoComplete = isMobileSearch ? mobileAutoCompleteList : desktopAutoCompleteList;

    isClickInside = currentAutoComplete.contains(event.target);

    if (!isClickInside) {
      autoCompleteOptions.length = 0;
      arrowCounter = -1;
      updateAutoCompleteList();
    }
  };

  const autoCompleteOptionClick = (autoCompleteOption) => {
    searchInputDesktopSearch.value = autoCompleteOption.Query;
    autoCompleteOptions.length = 0;
    emitSearch();
  };

  const onArrowDown = () => {
    if (arrowCounter < autoCompleteOptions.length - 1) {
      arrowCounter += 1;
      updateAutoCompleteList();
    }
  };

  const onArrowUp = () => {
    if (arrowCounter > 0) {
      arrowCounter -= 1;
      updateAutoCompleteList();
    }
  };

  const onEnter = () => {
    if (arrowCounter > -1) {
      let currentInput = isMobileSearch ? searchInputMobileSearch : searchInputDesktopSearch;

      currentInput.value = autoCompleteOptions[arrowCounter].Query;
    }

    autoCompleteOptions.length = 0;
    arrowCounter = -1;
    emitSearch();
  };

  const onEscape = () => {
    autoCompleteOptions.length = 0;
    arrowCounter = -1;
    searchInputDesktopSearch.value = "";
    searchInputMobileSearch.value = "";

    updateAutoCompleteList();
  };

  const emitSearch = () => {
    autoCompleteOptions.length = 0;
    arrowCounter = -1;

    let currentInput = isMobileSearch ? searchInputMobileSearch : searchInputDesktopSearch;
    let closestForm = currentInput.closest("form");
    closestForm.submit();
  };

  const updateAutoCompleteList = () => {
    mobileAutoCompleteList.innerHTML = "";
    desktopAutoCompleteList.innerHTML = "";

    let currentInput = isMobileSearch ? searchInputMobileSearch : searchInputDesktopSearch;

    currentInput.setAttribute("aria-expanded", autoCompleteOptions.length > 0);

    if (isMobileSearch && autoCompleteOptions.length > 0) {
      mobileAutoCompleteList.setAttribute("role", "listbox");
    } else if (autoCompleteOptions.length > 0) {
      desktopAutoCompleteList.setAttribute("role", "listbox");
    }

    autoCompleteOptions.forEach((autoCompleteOption, index) => {
      const listItem = document.createElement("li");

      const button = document.createElement("button");
      button.type = "button";
      button.classList.add("autocomplete__button");

      if (index === arrowCounter) {
        button.classList.add("autocomplete__button--active");
      }

      button.innerHTML = `${svgSearchIcon}<span>${autoCompleteOption.Query}</span>`;
      button.addEventListener("click", () => autoCompleteOptionClick(autoCompleteOption));

      listItem.appendChild(button);

      if (isMobileSearch) {
        mobileAutoCompleteList.appendChild(listItem);
      } else {
        desktopAutoCompleteList.appendChild(listItem);
      }
    });
  };

  [searchInputDesktopSearch, searchInputMobileSearch].forEach(function (element) {
    element.addEventListener("input", onInputChange);

    element.addEventListener("keydown", (event) => {
      if (event.key === "ArrowDown") {
        onArrowDown();
      } else if (event.key === "ArrowUp") {
        onArrowUp();
      } else if (event.key === "Enter") {
        onEnter();
      } else if (event.key === "Escape") {
        onEscape();
      }
    });
  });

  document.addEventListener("click", handleClickOutside);
});
;
document.addEventListener("DOMContentLoaded", function () {
  findRichTextTablesAndWrapWithDiv();

  function findRichTextTablesAndWrapWithDiv() {
    const richTextTables = document.querySelectorAll(".rich-text table");

    richTextTables.forEach((tableEl) => {
      wrapTableWithDiv(tableEl);
    });
  }

  function wrapTableWithDiv(tableEl) {
    let wrapperEl = document.createElement("div");
    let classArr = Array.from(tableEl.classList);

    let wrapperClassArr = classArr.map((x) => x.replace("table", "table-wrapper"));

    wrapperClassArr.forEach((c) => {
      wrapperEl.classList.add(c);
    });

    tableEl.parentNode.insertBefore(wrapperEl, tableEl);
    wrapperEl.appendChild(tableEl);

    if (isScrollable(wrapperEl, tableEl)) {
      addScrollHintText(wrapperEl);
      addHorizontalScrollBar(wrapperEl, tableEl, true);
    }
  }

  function addScrollHintText(wrapperEl) {
    let div = document.createElement("div");
    div.classList.add("rich-text__table--scroll-hint");
    div.innerText = getTranslatedHintText();
    wrapperEl.after(div);
  }

  function isScrollable(wrapperEl, tableEl) {
    return tableEl.offsetWidth > wrapperEl.offsetWidth;
  }

  function getTranslatedHintText() {
    if (document.documentElement.lang === "sv") {
      return "Scrolla åt sidan för att se mer av tabellen.";
    }

    return "Scroll to the side to reveal more of the table.";
  }

  function addHorizontalScrollBar(wrapperEl, tableEl, buttons = true) {
    const scrollbarContainer = document.createElement("div");
    scrollbarContainer.classList.add("horizontal-scrollbar");
    const buttonLeft = document.createElement("div");
    buttonLeft.classList.add("horizontal-scrollbar__button--left");
    const buttonRight = document.createElement("div");
    buttonRight.classList.add("horizontal-scrollbar__button--right");
    if (buttons) {
      addButtons();
    }
    const scrollbarThumb = document.createElement("div");
    scrollbarThumb.classList.add("horizontal-scrollbar__thumb");
    scrollbarContainer.appendChild(scrollbarThumb);
    wrapperEl.after(scrollbarContainer);
    let dragStartPosition;
    let thumbPosition = 0;
    let dragStartThumbPosition;
    const containerPadding =
      parseInt(
        window
          .getComputedStyle(scrollbarContainer, null)
          .getPropertyValue("padding-inline")
          .replace("px", "")
      ) * 2;

    // Helper functions
    function addButtons() {
      scrollbarContainer.style.paddingInline = "16px";
      scrollbarContainer.appendChild(buttonLeft);
      scrollbarContainer.appendChild(buttonRight);
    }

    function getViewableAreaPercent() {
      return (wrapperEl.offsetWidth / tableEl.offsetWidth) * 100;
    }

    function setScrollThumbPosition(pixelAmount) {
      const percentAmount = (pixelAmount / scrollbarContainer.offsetWidth) * 100;
      scrollbarThumb.style.transform = `translateX(${percentAmount}%)`;
      updateThumbPosition();
    }

    function updateThumbPosition() {
      thumbPosition =
        wrapperEl.scrollLeft * (scrollbarThumb.offsetWidth / scrollbarContainer.offsetWidth);
    }

    // Handler functions
    function handleScrollThumbParameters() {
      const thumbWidthPx =
        (scrollbarContainer.offsetWidth - containerPadding) * (getViewableAreaPercent() / 100);
      scrollbarThumb.style.width = `${thumbWidthPx}px`;
      setScrollThumbPosition(wrapperEl.scrollLeft);
    }

    function handleHorizontalScroll() {
      wrapperEl.scroll(wrapperEl.scrollLeft, 0);
      setScrollThumbPosition(wrapperEl.scrollLeft);
    }

    function handleScrollBarClick(event) {
      if (
        event.offsetX < containerPadding / 2 ||
        event.offsetX > scrollbarContainer.offsetWidth - containerPadding / 2
      ) {
        return;
      }

      const scrollTo =
        (event.offsetX - containerPadding / 2 - scrollbarThumb.offsetWidth / 2) /
        (scrollbarThumb.offsetWidth / scrollbarContainer.offsetWidth);
      wrapperEl.scroll(scrollTo, 0);
    }

    function handleThumbDrag(event) {
      event.preventDefault();
      event.stopImmediatePropagation();
      dragStartPosition = event.clientX;
      dragStartThumbPosition = thumbPosition;
      document.addEventListener("pointerup", handleStopDrag);
      document.addEventListener("pointermove", handleThumbMove);
    }

    function handleThumbMove(event) {
      let dragAmountPx = event.clientX - dragStartPosition + dragStartThumbPosition;
      let scrollAmount =
        dragAmountPx / (scrollbarThumb.offsetWidth / scrollbarContainer.offsetWidth);
      wrapperEl.scroll(scrollAmount, 0);
    }

    function handleStopDrag() {
      document.removeEventListener("pointermove", handleThumbMove);
      document.removeEventListener("pointerup", handleStopDrag);
    }

    function jumpLeft(event) {
      event.stopImmediatePropagation();
      wrapperEl.scroll(wrapperEl.scrollLeft - scrollbarThumb.offsetWidth, 0);
    }

    function jumpRight(event) {
      event.stopImmediatePropagation();
      wrapperEl.scroll(wrapperEl.scrollLeft + scrollbarThumb.offsetWidth, 0);
    }

    // Observers
    const tableSizeObserver = new ResizeObserver((entries) => {
      handleScrollThumbParameters();
    });
    tableSizeObserver.observe(tableEl);

    // Event listeners
    window.addEventListener("resize", handleScrollThumbParameters);
    wrapperEl.addEventListener("scroll", handleHorizontalScroll);
    scrollbarContainer.addEventListener("pointerdown", handleScrollBarClick);
    scrollbarThumb.addEventListener("pointerdown", handleThumbDrag);
    if (buttons) {
      buttonLeft.addEventListener("pointerdown", jumpLeft);
      buttonRight.addEventListener("pointerdown", jumpRight);
    }
  }
});
;
function getFilesForDocServiceFileBlockV3(id) {
    let getDocumentsUrl = `/DocServiceFileListingBlockV3/GetDocuments?id=${id}`;

    let docServiceFilesContainer = document.getElementById(`docServiceFileListingBlockV3-${id}`);

    fetch(getDocumentsUrl)
        .then((response) => {
            if (!response.ok) {
                throw new Error(`Network response was not ok: ${response.status}`);
            }
            return response.text();
        })
        .then((data) => {

            //replace the content of the container with the new content
            docServiceFilesContainer.innerHTML = data;
        })
        .catch((error) => {
            console.log(error);
        });
}
;
document.addEventListener("DOMContentLoaded", function () {
  const selectors = {
    form: "[data-rs-validation]",
    field: ".form-field",
    input: ".form-input",
    error: ".form-validation",
  };

  const simpleForm = document.querySelector(selectors.form);
  if (simpleForm == null) return false;

  const requiredFields = (fields) => {
    return fields.filter((i) => i?.hasAttribute("aria-required"));
  };

  const invalidFields = (fields) => {
    return fields.map((i) => validate.run(i)).filter((x) => x);
  };

  const validateOnblur = (elems) => {
    let formDataAttr = selectors.form.slice(1, -1);
    if (simpleForm.getAttribute(formDataAttr) === "true") {
      return false;
    }

    simpleForm.setAttribute(formDataAttr, "true");
    elems.forEach(function (el) {
      el.addEventListener("blur", function (e) {
        let invalid = validate.run(el);
        if (invalid) {
          validate.displayElementError(invalid);
        } else {
          validate.clearElementMessage(el);
        }
      });
    });
  };

  const validate = {
    run: function (el) {
      let inputType = el.tagName.toLowerCase();
      return this[inputType](el);
    },

    textarea: function (el) {
      if (el.value?.length === 0) {
        return { label: this.label(el), el: el };
      }
    },
    select: function (el) {
      if (el.value === "") {
        return { label: this.label(el), el: el };
      }
    },

    input: function (el) {
      return this[el.type](el);
    },

    email: function (el) {
      let regex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g;
      let langStr = { en: "valid", sv: "giltig" };

      if (el.value === "") {
        return { label: this.label(el), el: el };
      }
      if (!regex.test(el.value)) {
        let label = `${langStr[document.documentElement.lang]} ${this.label(el)}`;
        return { label: label, el: el };
      }
    },
    text: function (el) {
      if (el.value === "") {
        return { label: this.label(el), el: el };
      }
    },
    number: function (el) {
      if (el.value === "") {
        return { label: this.label(el), el: el };
      }
    },
    label: function (el) {
      let regex = /\([^)]*\)|[^()]+/;
      let str = el.labels.item(0)?.innerText;
      str = str.match(regex).at(0);
      str = str.replace(":", "");
      return str.toLowerCase();
    },

    message: function (el) {
      let langStr = { sv: "Du behöver fylla i", en: "You need to enter" };
      return langStr[document.documentElement.lang];
    },

    clearAllMessages: function () {
      let msgs = document.querySelectorAll(selectors.error);
      msgs.forEach((x) => (x.innerHtml = ""));
    },

    clearElementMessage: function (el) {
      let msgEl = this.getValidationEl(el);
      msgEl.setAttribute("hidden", "");
    },

    displayErrors: function (elems) {
      for (var i in elems) {
        this.displayElementError(elems[i]);
      }
    },

    displayElementError: function (elem) {
      let msgEl = this.getValidationEl(elem.el);
      msgEl.innerText = `${this.message(elem.el)} ${elem.label}`;
      msgEl.removeAttribute("hidden");
    },
    getFieldEl: function (el) {
      return el.closest(selectors.field);
    },

    getValidationEl: function (el) {
      let field = this.getFieldEl(el);
      return field.querySelector(`:scope > ${selectors.error}`);
    },
  };

  simpleForm.addEventListener("submit", function (e) {
    e.preventDefault();
    let allRequired = requiredFields(Array.from(simpleForm.elements));
    let allInvalid = invalidFields(allRequired);
    if (allInvalid.length === 0) {
      simpleForm.submit();
    } else {
      validateOnblur(allRequired);
      validate.displayErrors(allInvalid);
    }
  });
});
;
var lilum_hostname = "https://lilum.lightsinline.se"; window.performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var timing = performance.timing || {}, navigation = performance.navigation || {}, lilum_supported = !0, lilum_transactions = {}; Date.now || (Date.now = function () { return (new Date).getTime() }); function lilum_startTransaction(a) { a && (lilum_transactions[a] = Date.now()) }
function lilum_stopTransaction(a) { if (0 < lilum_transactions[a] && lilum_transactions[a] <= Date.now()) { var b = Date.now() - lilum_transactions[a]; lilum_sendWithId(lilum_hostname + "/log.aspx?RTClient=" + b + "&RTTotal=" + b + "&Custom=" + encodeURIComponent(a)); lilum_transactions[a] = 0 } } function lilum_getTiming(a) { return timing ? timing[a] : 0 }
function lilum_isDone() { lilum_supported && (lilum_getTiming("navigationStart") ? 0 >= lilum_getTiming("loadEventEnd") ? window.setTimeout("lilum_isDone()", 200) : lilum_sendLogInfo() : (lilum_supported = !1, lilum_sendWithId(lilum_hostname + "/log.aspx?Custom=NoNavigationSupport"))) }
function lilum_sendLogInfo() {
    var a = lilum_getTiming("domainLookupEnd") - lilum_getTiming("domainLookupStart"), b = lilum_getTiming("connectEnd") - lilum_getTiming("connectStart"), c = lilum_getTiming("responseStart") - lilum_getTiming("requestStart"), d = lilum_getTiming("responseEnd") - lilum_getTiming("responseStart"), e = lilum_getTiming("loadEventEnd") - lilum_getTiming("responseEnd"), f = lilum_getTiming("loadEventEnd") - lilum_getTiming("navigationStart"); a = lilum_hostname + "/log.aspx?RTDns=" + a + "&RTConnect=" + b + "&RTNet=" +
    d + "&RTClient=" + (f - (a + b + c + d + e)) + "&RTServer=" + c + "&RTPage=" + e + "&RTTotal=" + f; (b = window.lilum_custom || 0) && (a += "&Custom=" + encodeURIComponent(b)); a += "&PageURL=" + encodeURIComponent(window.location.href.split("?")[0]); lilum_sendWithId(a)
}
function lilum_sendWithId(a) { if (sessionStorage && localStorage) { var b = sessionStorage.getItem("LILUM"); b || (b = lilum_uuidv4(), sessionStorage.setItem("LILUM", b)); a += "&SessionID=" + encodeURIComponent(b) } (b = window.lilum_siteid || 0) && (a += "&SiteID=" + encodeURIComponent(b)); b = new XMLHttpRequest; b.open("GET", a, !0); b.send() } function lilum_uuidv4() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (a) { var b = 16 * Math.random() | 0; return ("x" == a ? b : b & 3 | 8).toString(16) }) }
window.setTimeout("lilum_isDone()", 200);;
const EssentialCookieName = "consent-essential-cookies";
const NonEssentialCookieName = "consent-non-essential-cookies";
var hasClickedLoadTrackingCookies = false;

var consentAllCookiesButton = document.getElementById("consent-all-cookies");
var consentNoTrackingButton = document.getElementById("consent-no-tracking");
var cookieInfoBox = document.getElementById("cookie-info-box");
var saveChoicesButton = document.getElementById("btn-save-cookies-choices-on-block");
var saveChoicesButtonV3 = document.getElementById("cookieConsentSettingsBlockButton");

// Close cookie .msg
if (!JSON.parse(getCookie(EssentialCookieName))) {
    cookieInfoBox = document.getElementById("cookie-info-box");
    cookieInfoBox.classList.remove("hide");
}

//has allowed trackign scripts
if (JSON.parse(getCookie(NonEssentialCookieName))) {
    loadTrackingScripts();
} else {
    //Delete lights in line local storage
    window.localStorage.removeItem("LILUM");
}

consentAllCookiesButton.addEventListener("click", function () {
    slideToggle(cookieInfoBox);
    consentCookies(true, true);
});

consentNoTrackingButton.addEventListener("click", function () {
    slideToggle(cookieInfoBox);
    consentCookies(true, false);
});

if (saveChoicesButton) {
    saveChoicesButton.addEventListener("click", function () {
        var trackingConsentCheckbox = document.getElementById("cb-tracking-cookies-on-block");
        var saveCookieSuccess = document.querySelector(".save-cookie-settings-success");

        var trackingConsentIsChecked = trackingConsentCheckbox.checked;
        var expireTime = trackingConsentIsChecked ? 999 : -1;

        setExpCookie(NonEssentialCookieName, true, expireTime);
        setMatomoTracking(trackingConsentIsChecked);

        saveCookieSuccess.style.display = "none";
        saveCookieSuccess.classList.remove("hide");
        fadeIn(saveCookieSuccess);

        setTimeout(function () {
            fadeOutAndHide(saveCookieSuccess);
        }, 3000);
    });
}

if (saveChoicesButtonV3) {
    saveChoicesButtonV3.addEventListener("click", function () {
        var webAnalyticsTrackingConsentRadioButton = document.getElementById("acceptWebAnalyticsCookies");
        var saveCookieSuccess = document.getElementById("cookieConsentSettingsBlockSuccessMessage");

        var webAnalyticsTrackingConsentIsChecked = webAnalyticsTrackingConsentRadioButton.checked;
        var expireTime = webAnalyticsTrackingConsentIsChecked ? 999 : -1;

        setExpCookie(NonEssentialCookieName, true, expireTime);
        setMatomoTracking(webAnalyticsTrackingConsentIsChecked);
        
        saveCookieSuccess.style.display = "none";
        saveCookieSuccess.classList.remove("hide");
        fadeIn(saveCookieSuccess);

        setTimeout(function () {
            fadeOutAndHide(saveCookieSuccess);
        }, 3000);
    });
}

function loadTrackingScripts() {
    //prevent multiple clicks
    if (hasClickedLoadTrackingCookies) {
        return false;
    }

    hasClickedLoadTrackingCookies = true;
    var content = document.getElementById("trackingScriptsSection");

    if (content === undefined || content === null) {
        return false;
    }

    content.innerHTML = content.innerHTML.replace("<!--", "").replace("-->", "");

    var scripts = content.getElementsByTagName("script");

    var scriptsClone = [].slice.call(scripts);

    for (var i = 0; i < scriptsClone.length; ++i) {
        var script = scriptsClone[i];

        if (script.src !== "") {
            var el = document.createElement("script");

            el.src = script.src;

            document.getElementsByTagName("head")[0].appendChild(el);
        } else {
            eval(script.innerHTML);
        }
    }
}

function setMatomoTracking(consent) {
    document.dispatchEvent(
        new CustomEvent("set.matomo.cookie", {
            bubbles: true,
            detail: {consent: consent},
        })
    );
}

function consentCookies(consentNecessary, consentTracking) {
    if (consentNecessary) {
        setExpCookie(EssentialCookieName, true, 999);
    }

    if (consentTracking) {
        setExpCookie(NonEssentialCookieName, true, 999);
        setMatomoTracking(consentTracking);
        loadTrackingScripts();
    }
}

function setExpCookie(cookieName, value, days) {
    var escapedValue = escape(value);

    var now = new Date();
    now.setTime(now.getTime() + days * 24 * 60 * 60 * 1000);

    document.cookie =
        cookieName + "=" + value + "; path=/;" + "expires=" + now.toGMTString();
}

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(";");
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

var deleteCookie = function (name) {
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;";
};

function slideToggle(element) {
    if (window.getComputedStyle(element).display === "none") {
        element.style.display = "block";
    } else {
        element.style.display = "none";
    }
}

function fadeIn(element) {
    element.style.opacity = 0;
    element.style.display = "block";
    var tick = function () {
        element.style.opacity = +element.style.opacity + 0.04;
        if (+element.style.opacity < 1) {
            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
        }
    };
    tick();
}

function fadeOutAndHide(element) {
    element.style.opacity = 1;
    var tick = function () {
        element.style.opacity = +element.style.opacity - 0.04;
        if (+element.style.opacity > 0) {
            (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
        } else {
            element.style.display = "none";
            element.classList.add("hide");
        }
    };
    tick();
};
document.addEventListener("DOMContentLoaded", () => {
    initAccessibilityMenu();
});

function initAccessibilityMenu() {
    const easyToReadLink = document.getElementById("easy-to-read-link");
    const signLangLink = document.getElementById("sign-lang-link");

    if (easyToReadLink) {
        easyToReadLink.addEventListener("click", () => {
            hideOtherAccessibilityContainer(signLangLink);
            showAccessibilityContainer(easyToReadLink);
        });
    }

    if (signLangLink) {
        signLangLink.addEventListener("click", () => {
            hideOtherAccessibilityContainer(easyToReadLink);
            showAccessibilityContainer(signLangLink);
        });
    }
}

function showAccessibilityContainer(ele) {
    var expandLink = ele;

    var showMoreContainerId = expandLink.getAttribute("aria-controls");
    var showMoreContainer = document.getElementById(showMoreContainerId);

    if (showMoreContainer.hasAttribute("hidden")) {
        showMoreContainer.removeAttribute("hidden");
        expandLink.innerHTML = expandLink.getAttribute("data-close-text");
    }
    else {
        showMoreContainer.setAttribute("hidden", "");
        expandLink.innerHTML = expandLink.getAttribute("data-open-text");
    }
}

function hideOtherAccessibilityContainer(ele) {
    var otherLink = ele;

    if (otherLink) {
        var hideContainerId = otherLink.getAttribute("aria-controls");
        var hideContainer = document.getElementById(hideContainerId);

        hideContainer.setAttribute("hidden", "");
        otherLink.innerHTML = otherLink.getAttribute("data-open-text");
    }
}

function skipToContent(sender) {
    let mainContent = document.getElementsByTagName("h1");
    
    if (!mainContent) {
        return false;
    }
    
    mainContent = mainContent[0];
    let rectElement = mainContent.getBoundingClientRect()
    const mobileElement = document.querySelector(".site-header-mobile");
        
    if (mainContent){
        window.scrollTo({top: rectElement.top - mobileElement.offsetHeight, behavior: 'smooth'});
        mainContent.tabIndex = -1;
        mainContent.focus();
    }
    return false;
};
document.addEventListener(
  "DOMContentLoaded",

  (function () {
    const surveyDataElement = document.querySelector("[data-survey]");

    if (!surveyDataElement || surveyDataElement.getAttribute("data-survey") == "") {
      return null;
    }

    const SurveyPopup = {
      url: surveyDataElement.getAttribute("data-url"),
      popupDelay: surveyDataElement.getAttribute("data-popup-delay"),
      cookieName: `survey${surveyDataElement.getAttribute("data-survey")}`,
    };

    const getCookie = function (name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(";");
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == " ") c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) {
          return c.substring(nameEQ.length, c.length);
        }
      }
      return null;
    };

    const setCookie = function (name, value, days) {
      let expires = "";
      if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
        expires = "; expires=" + date.toGMTString();
      }
      document.cookie = name + "=" + value + expires + "; path=/";
    };

    const addEventListener = function () {
      let buttons = surveyDataElement.querySelectorAll("[data-event]");
      Array.from(buttons).forEach(function (elm) {
        elm.addEventListener("click", popupEvents);
      });
    };

    const removeEventListener = function () {
      let buttons = surveyDataElement.querySelectorAll("[data-event]");
      Array.from(buttons).forEach(function (elm) {
        elm.removeEventListener("click", popupEvents);
      });
    };

    const createPopup = function () {
      addEventListener();
      setTimeout(function () {
        setCookie(SurveyPopup.cookieName, true, 90);
        surveyDataElement.removeAttribute("hidden");
      }, SurveyPopup.popupDelay * 1000);
    };

    const popupEvents = function (e) {
      if (clickedYes(e.currentTarget)) {
        e.preventDefault();
        window.open(SurveyPopup.url, "_blank");
        closePopup();
        return;
      }
      if (clickedNo(e.currentTarget)) {
        e.preventDefault();
        closePopup();
        return;
      }
    };

    const clickedYes = (el) => el.getAttribute("data-event") == "yes-to-survey";

    const clickedNo = (el) => el.getAttribute("data-event") == "no-to-survey";

    const closePopup = () => {
      removeEventListener();
      surveyDataElement.setAttribute("hidden", "");
    };

    if (!getCookie(SurveyPopup.cookieName)) {
      createPopup();
    }
  })()
);
;
