/* Minification failed. Returning unminified contents.
(1001,37-39): run-time error JS1006: Expected ')': =>
(1001,36): run-time error JS1004: Expected ';'
(1008,31): run-time error JS1004: Expected ';'
(1018,10-11): run-time error JS1195: Expected expression: )
 */
/**
 * Applies the :focus-visible polyfill at the given scope.
 * A scope in this case is either the top-level Document or a Shadow Root.
 *
 * @param {(Document|ShadowRoot)} scope
 * @see https://github.com/WICG/focus-visible
 */
function applyFocusVisiblePolyfill(scope) {
  var hadKeyboardEvent = true;
  var hadFocusVisibleRecently = false;
  var hadFocusVisibleRecentlyTimeout = null;

  var inputTypesAllowlist = {
    text: true,
    search: true,
    url: true,
    tel: true,
    email: true,
    password: true,
    number: true,
    date: true,
    month: true,
    week: true,
    time: true,
    datetime: true,
    'datetime-local': true
  };

  /**
   * Helper function for legacy browsers and iframes which sometimes focus
   * elements like document, body, and non-interactive SVG.
   * @param {Element} el
   */
  function isValidFocusTarget(el) {
    if (
      el &&
      el !== document &&
      el.nodeName !== 'HTML' &&
      el.nodeName !== 'BODY' &&
      'classList' in el &&
      'contains' in el.classList
    ) {
      return true;
    }
    return false;
  }

  /**
   * Computes whether the given element should automatically trigger the
   * `focus-visible` class being added, i.e. whether it should always match
   * `:focus-visible` when focused.
   * @param {Element} el
   * @return {boolean}
   */
  function focusTriggersKeyboardModality(el) {
    var type = el.type;
    var tagName = el.tagName;

    if (tagName === 'INPUT' && inputTypesAllowlist[type] && !el.readOnly) {
      return true;
    }

    if (tagName === 'TEXTAREA' && !el.readOnly) {
      return true;
    }

    if (el.isContentEditable) {
      return true;
    }

    return false;
  }

  /**
   * Add the `focus-visible` class to the given element if it was not added by
   * the author.
   * @param {Element} el
   */
  function addFocusVisibleClass(el) {
    if (el.classList.contains('focus-visible')) {
      return;
    }
    el.classList.add('focus-visible');
    el.setAttribute('data-focus-visible-added', '');
  }

  /**
   * Remove the `focus-visible` class from the given element if it was not
   * originally added by the author.
   * @param {Element} el
   */
  function removeFocusVisibleClass(el) {
    if (!el.hasAttribute('data-focus-visible-added')) {
      return;
    }
    el.classList.remove('focus-visible');
    el.removeAttribute('data-focus-visible-added');
  }

  /**
   * If the most recent user interaction was via the keyboard;
   * and the key press did not include a meta, alt/option, or control key;
   * then the modality is keyboard. Otherwise, the modality is not keyboard.
   * Apply `focus-visible` to any current active element and keep track
   * of our keyboard modality state with `hadKeyboardEvent`.
   * @param {KeyboardEvent} e
   */
  function onKeyDown(e) {
    if (e.metaKey || e.altKey || e.ctrlKey) {
      return;
    }

    if (isValidFocusTarget(scope.activeElement)) {
      addFocusVisibleClass(scope.activeElement);
    }

    hadKeyboardEvent = true;
  }

  /**
   * If at any point a user clicks with a pointing device, ensure that we change
   * the modality away from keyboard.
   * This avoids the situation where a user presses a key on an already focused
   * element, and then clicks on a different element, focusing it with a
   * pointing device, while we still think we're in keyboard modality.
   * @param {Event} e
   */
  function onPointerDown(e) {
    hadKeyboardEvent = false;
  }

  /**
   * On `focus`, add the `focus-visible` class to the target if:
   * - the target received focus as a result of keyboard navigation, or
   * - the event target is an element that will likely require interaction
   *   via the keyboard (e.g. a text box)
   * @param {Event} e
   */
  function onFocus(e) {
    // Prevent IE from focusing the document or HTML element.
    if (!isValidFocusTarget(e.target)) {
      return;
    }

    if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {
      addFocusVisibleClass(e.target);
    }
  }

  /**
   * On `blur`, remove the `focus-visible` class from the target.
   * @param {Event} e
   */
  function onBlur(e) {
    if (!isValidFocusTarget(e.target)) {
      return;
    }

    if (
      e.target.classList.contains('focus-visible') ||
      e.target.hasAttribute('data-focus-visible-added')
    ) {
      // To detect a tab/window switch, we look for a blur event followed
      // rapidly by a visibility change.
      // If we don't see a visibility change within 100ms, it's probably a
      // regular focus change.
      hadFocusVisibleRecently = true;
      window.clearTimeout(hadFocusVisibleRecentlyTimeout);
      hadFocusVisibleRecentlyTimeout = window.setTimeout(function () {
        hadFocusVisibleRecently = false;
      }, 100);
      removeFocusVisibleClass(e.target);
    }
  }

  /**
   * If the user changes tabs, keep track of whether or not the previously
   * focused element had .focus-visible.
   * @param {Event} e
   */
  function onVisibilityChange(e) {
    if (document.visibilityState === 'hidden') {
      // If the tab becomes active again, the browser will handle calling focus
      // on the element (Safari actually calls it twice).
      // If this tab change caused a blur on an element with focus-visible,
      // re-apply the class when the user switches back to the tab.
      if (hadFocusVisibleRecently) {
        hadKeyboardEvent = true;
      }
      addInitialPointerMoveListeners();
    }
  }

  /**
   * Add a group of listeners to detect usage of any pointing devices.
   * These listeners will be added when the polyfill first loads, and anytime
   * the window is blurred, so that they are active when the window regains
   * focus.
   */
  function addInitialPointerMoveListeners() {
    document.addEventListener('mousemove', onInitialPointerMove);
    document.addEventListener('mousedown', onInitialPointerMove);
    document.addEventListener('mouseup', onInitialPointerMove);
    document.addEventListener('pointermove', onInitialPointerMove);
    document.addEventListener('pointerdown', onInitialPointerMove);
    document.addEventListener('pointerup', onInitialPointerMove);
    document.addEventListener('touchmove', onInitialPointerMove);
    document.addEventListener('touchstart', onInitialPointerMove);
    document.addEventListener('touchend', onInitialPointerMove);
  }

  function removeInitialPointerMoveListeners() {
    document.removeEventListener('mousemove', onInitialPointerMove);
    document.removeEventListener('mousedown', onInitialPointerMove);
    document.removeEventListener('mouseup', onInitialPointerMove);
    document.removeEventListener('pointermove', onInitialPointerMove);
    document.removeEventListener('pointerdown', onInitialPointerMove);
    document.removeEventListener('pointerup', onInitialPointerMove);
    document.removeEventListener('touchmove', onInitialPointerMove);
    document.removeEventListener('touchstart', onInitialPointerMove);
    document.removeEventListener('touchend', onInitialPointerMove);
  }

  /**
   * When the polfyill first loads, assume the user is in keyboard modality.
   * If any event is received from a pointing device (e.g. mouse, pointer,
   * touch), turn off keyboard modality.
   * This accounts for situations where focus enters the page from the URL bar.
   * @param {Event} e
   */
  function onInitialPointerMove(e) {
    // Work around a Safari quirk that fires a mousemove on <html> whenever the
    // window blurs, even if you're tabbing out of the page. ¯\_(ツ)_/¯
    if (e.target.nodeName && e.target.nodeName.toLowerCase() === 'html') {
      return;
    }

    hadKeyboardEvent = false;
    removeInitialPointerMoveListeners();
  }

  // For some kinds of state, we are interested in changes at the global scope
  // only. For example, global pointer input, global key presses and global
  // visibility change should affect the state at every scope:
  document.addEventListener('keydown', onKeyDown, true);
  document.addEventListener('mousedown', onPointerDown, true);
  document.addEventListener('pointerdown', onPointerDown, true);
  document.addEventListener('touchstart', onPointerDown, true);
  document.addEventListener('visibilitychange', onVisibilityChange, true);

  addInitialPointerMoveListeners();

  // For focus and blur, we specifically care about state changes in the local
  // scope. This is because focus / blur events that originate from within a
  // shadow root are not re-dispatched from the host element if it was already
  // the active element in its own scope:
  scope.addEventListener('focus', onFocus, true);
  scope.addEventListener('blur', onBlur, true);

  // We detect that a node is a ShadowRoot by ensuring that it is a
  // DocumentFragment and also has a host property. This check covers native
  // implementation and polyfill implementation transparently. If we only cared
  // about the native implementation, we could just check if the scope was
  // an instance of a ShadowRoot.
  if (scope.nodeType === Node.DOCUMENT_FRAGMENT_NODE && scope.host) {
    // Since a ShadowRoot is a special kind of DocumentFragment, it does not
    // have a root element to add a class to. So, we add this attribute to the
    // host element instead:
    scope.host.setAttribute('data-js-focus-visible', '');
  } else if (scope.nodeType === Node.DOCUMENT_NODE) {
    document.documentElement.classList.add('js-focus-visible');
    document.documentElement.setAttribute('data-js-focus-visible', '');
  }
}

// It is important to wrap all references to global window and document in
// these checks to support server-side rendering use cases
// @see https://github.com/WICG/focus-visible/issues/199
if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  // Make the polyfill helper globally available. This can be used as a signal
  // to interested libraries that wish to coordinate with the polyfill for e.g.,
  // applying the polyfill to a shadow root:
  window.applyFocusVisiblePolyfill = applyFocusVisiblePolyfill;

  // Notify interested libraries of the polyfill's presence, in case the
  // polyfill was loaded lazily:
  var event;

  try {
    event = new CustomEvent('focus-visible-polyfill-ready');
  } catch (error) {
    // IE11 does not support using CustomEvent as a constructor directly:
    event = document.createEvent('CustomEvent');
    event.initCustomEvent('focus-visible-polyfill-ready', false, false, {});
  }

  window.dispatchEvent(event);
}

if (typeof document !== 'undefined') {
  // Apply the polyfill to the global document, so that no JavaScript
  // coordination is required to use the polyfill in the top-level document:
  applyFocusVisiblePolyfill(document);
};
// https://github.com/willmcpo/body-scroll-lock
(function (global, factory) {
    if (typeof define === "function" && define.amd) {
        define(['exports'], factory);
    } else if (typeof exports !== "undefined") {
        factory(exports);
    } else {
        var mod = {
            exports: {}
        };
        factory(mod.exports);
        global.bodyScrollLock = mod.exports;
    }
})(this, function (exports) {
    'use strict';

    Object.defineProperty(exports, "__esModule", {
        value: true
    });

    function _toConsumableArray(arr) {
        if (Array.isArray(arr)) {
            for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
                arr2[i] = arr[i];
            }

            return arr2;
        } else {
            return Array.from(arr);
        }
    }

    // Older browsers don't support event options, feature detect it.

    // Adopted and modified solution from Bohdan Didukh (2017)
    // https://stackoverflow.com/questions/41594997/ios-10-safari-prevent-scrolling-behind-a-fixed-overlay-and-maintain-scroll-posi

    var hasPassiveEvents = false;
    if (typeof window !== 'undefined') {
        var passiveTestOptions = {
            get passive() {
                hasPassiveEvents = true;
                return undefined;
            }
        };
        window.addEventListener('testPassive', null, passiveTestOptions);
        window.removeEventListener('testPassive', null, passiveTestOptions);
    }

    var isIosDevice = typeof window !== 'undefined' && window.navigator && window.navigator.platform && (/iP(ad|hone|od)/.test(window.navigator.platform) || window.navigator.platform === 'MacIntel' && window.navigator.maxTouchPoints > 1);


    var locks = [];
    var documentListenerAdded = false;
    var initialClientY = -1;
    var previousBodyOverflowSetting = void 0;
    var previousBodyPaddingRight = void 0;

    // returns true if `el` should be allowed to receive touchmove events.
    var allowTouchMove = function allowTouchMove(el) {
        return locks.some(function (lock) {
            if (lock.options.allowTouchMove && lock.options.allowTouchMove(el)) {
                return true;
            }

            return false;
        });
    };

    var preventDefault = function preventDefault(rawEvent) {
        var e = rawEvent || window.event;

        // For the case whereby consumers adds a touchmove event listener to document.
        // Recall that we do document.addEventListener('touchmove', preventDefault, { passive: false })
        // in disableBodyScroll - so if we provide this opportunity to allowTouchMove, then
        // the touchmove event on document will break.
        if (allowTouchMove(e.target)) {
            return true;
        }

        // Do not prevent if the event has more than one touch (usually meaning this is a multi touch gesture like pinch to zoom).
        if (e.touches.length > 1) return true;

        if (e.preventDefault) e.preventDefault();

        return false;
    };

    var setOverflowHidden = function setOverflowHidden(options) {
        // If previousBodyPaddingRight is already set, don't set it again.
        if (previousBodyPaddingRight === undefined) {
            var _reserveScrollBarGap = !!options && options.reserveScrollBarGap === true;
            var scrollBarGap = window.innerWidth - document.documentElement.clientWidth;

            if (_reserveScrollBarGap && scrollBarGap > 0) {
                previousBodyPaddingRight = document.body.style.paddingRight;
                document.body.style.paddingRight = scrollBarGap + 'px';
            }
        }

        // If previousBodyOverflowSetting is already set, don't set it again.
        if (previousBodyOverflowSetting === undefined) {
            previousBodyOverflowSetting = document.body.style.overflow;
            document.body.style.overflow = 'hidden';
        }
    };

    var restoreOverflowSetting = function restoreOverflowSetting() {
        if (previousBodyPaddingRight !== undefined) {
            document.body.style.paddingRight = previousBodyPaddingRight;

            // Restore previousBodyPaddingRight to undefined so setOverflowHidden knows it
            // can be set again.
            previousBodyPaddingRight = undefined;
        }

        if (previousBodyOverflowSetting !== undefined) {
            document.body.style.overflow = previousBodyOverflowSetting;

            // Restore previousBodyOverflowSetting to undefined
            // so setOverflowHidden knows it can be set again.
            previousBodyOverflowSetting = undefined;
        }
    };

    // https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight#Problems_and_solutions
    var isTargetElementTotallyScrolled = function isTargetElementTotallyScrolled(targetElement) {
        return targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : false;
    };

    var handleScroll = function handleScroll(event, targetElement) {
        var clientY = event.targetTouches[0].clientY - initialClientY;

        if (allowTouchMove(event.target)) {
            return false;
        }

        if (targetElement && targetElement.scrollTop === 0 && clientY > 0) {
            // element is at the top of its scroll.
            return preventDefault(event);
        }

        if (isTargetElementTotallyScrolled(targetElement) && clientY < 0) {
            // element is at the bottom of its scroll.
            return preventDefault(event);
        }

        event.stopPropagation();
        return true;
    };

    var disableBodyScroll = exports.disableBodyScroll = function disableBodyScroll(targetElement, options) {
        // targetElement must be provided
        if (!targetElement) {
            // eslint-disable-next-line no-console
            console.error('disableBodyScroll unsuccessful - targetElement must be provided when calling disableBodyScroll on IOS devices.');
            return;
        }

        // disableBodyScroll must not have been called on this targetElement before
        if (locks.some(function (lock) {
            return lock.targetElement === targetElement;
        })) {
            return;
        }

        var lock = {
            targetElement: targetElement,
            options: options || {}
        };

        locks = [].concat(_toConsumableArray(locks), [lock]);

        if (isIosDevice) {
            targetElement.ontouchstart = function (event) {
                if (event.targetTouches.length === 1) {
                    // detect single touch.
                    initialClientY = event.targetTouches[0].clientY;
                }
            };
            targetElement.ontouchmove = function (event) {
                if (event.targetTouches.length === 1) {
                    // detect single touch.
                    handleScroll(event, targetElement);
                }
            };

            if (!documentListenerAdded) {
                document.addEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
                documentListenerAdded = true;
            }
        } else {
            setOverflowHidden(options);
        }
    };

    var clearAllBodyScrollLocks = exports.clearAllBodyScrollLocks = function clearAllBodyScrollLocks() {
        if (isIosDevice) {
            // Clear all locks ontouchstart/ontouchmove handlers, and the references.
            locks.forEach(function (lock) {
                lock.targetElement.ontouchstart = null;
                lock.targetElement.ontouchmove = null;
            });

            if (documentListenerAdded) {
                document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
                documentListenerAdded = false;
            }

            // Reset initial clientY.
            initialClientY = -1;
        } else {
            restoreOverflowSetting();
        }

        locks = [];
    };

    var enableBodyScroll = exports.enableBodyScroll = function enableBodyScroll(targetElement) {
        if (!targetElement) {
            // eslint-disable-next-line no-console
            console.error('enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices.');
            return;
        }

        locks = locks.filter(function (lock) {
            return lock.targetElement !== targetElement;
        });

        if (isIosDevice) {
            targetElement.ontouchstart = null;
            targetElement.ontouchmove = null;

            if (documentListenerAdded && locks.length === 0) {
                document.removeEventListener('touchmove', preventDefault, hasPassiveEvents ? { passive: false } : undefined);
                documentListenerAdded = false;
            }
        } else if (!locks.length) {
            restoreOverflowSetting();
        }
    };
});;
var AP = AP || {}

AP.Navigation = (AP => {
    // Scroll
    let shouldLockBodyScroll = false;
    let isBodyLocked = false;
    const desktop = 1024
    const tablet = 768
    const $scrollElements = $('.header__primary-list, .header__secondary, .header__tertiary')

    // Elements
    const $root = $('div.root')
    const $sidebar = $('.sidebar-navigation');

    // States
    const states = {
        stateAnimation: 'state-animates',
        statePushDown: 'state-push-down',
        statePushUp: 'state-push-up',
        statePushDownLeft: 'state-push-down-left',
        statePushUpLeft: 'state-push-up-left',
        statePushDownLeftSearch: 'state-push-down-left-search',
        statePushUpLeftSearch: 'state-push-up-left-search'
    }
    const statesSelector = Object.values(states).join(' ');

    function initNavigation() {
        // Mobile toggler
        $('.header__toggler').click(function (event) {
            event.preventDefault();

            if (state(states.statePushDown)) {
                addState(states.statePushUp)
                enableBodyScroll()
            }
            else if (state(states.statePushUp)) {
                addState(states.statePushDown)
            }
            else if (state(states.statePushUpLeft)) {
                addState(states.statePushDownLeft)
            }
            else if (state(states.statePushDownLeft)) {
                addState(states.statePushUpLeft)
                enableBodyScroll()
            }
            else if (state(states.statePushUpLeftSearch)) {
                addState(states.statePushDownLeftSearch)
            }
            else if (state(states.statePushDownLeftSearch)) {
                addState(states.statePushUpLeftSearch)
                enableBodyScroll()
            }
            else {
                addState(states.statePushDown)
                disableBodyScroll()
            }

            // Close contact
            const $contact = $('.contact-widget')
            if ($contact.length && $contact.hasClass('contact-widget--mobile-open')) {
                $contact.removeClass('contact-widget--mobile-open');
            }
        })

        // Wait for transitions to end before removing class names
        $('.header__secondary, .header__bottom').on('transitionend webkitTransitionEnd oTransitionEnd', function () {
            if (state(states.statePushUp) || state(states.statePushUpLeft) || state(states.statePushUpLeftSearch)) {
                $root.removeClass(statesSelector)
            }
        });

        // Search toggler
        $('.header__search-toggler').click(function () {
            addState(states.statePushDownLeftSearch)
            $('.header__search-input').focus()
        });

        // Search input
        $('.header__search-input').blur(function () {
            if ($(window).width() >= desktop && $(this).val() === "") {
                addState(states.statePushUpLeftSearch)
            }
        });

        // Search clear button
        $('.header__search-clear-button').click(function () {
            $('#search .header__search-input').val('');

            if ($(window).width() >= desktop) {
                addState(states.statePushUpLeftSearch)
            }
        });


        // Toggle secondary lvl state
        const primaryLinks = $('.header__primary-link');
        primaryLinks.not('a').click(function (event) {
            event.preventDefault();
            addState(states.statePushDown)

            const index = $(this).parent().index();

            primaryLinks.removeClass('header__primary-link--active');
            $(this).addClass('header__primary-link--active');
            $('a.header__contact-link--active').removeClass('header__contact-link--active');

            $(`ul.header__secondary-list`)
                .removeClass('header__secondary-list--active')
                .filter(`[data-index="${index}"]`)
                .addClass('header__secondary-list--active');
        });

        // Toggle third lvl state
        const secondaryLinks = $('button.header__secondary-link');
        secondaryLinks.click(function (event) {
            event.preventDefault();

            const parentIndex = $(this).closest('.header__secondary-list').data('index');
            const index = $(this).parent().index();

            // Close the navigation if already open
            if (state(states.statePushDownLeft) &&
                $(`ul.header__tertiary--active[data-index="${parentIndex}-${index}"]`).length) {
                return addState(states.statePushUpLeft);
            }

            addState(states.statePushDownLeft);

            secondaryLinks.removeClass('header__secondary-link--active');
            $(this).addClass('header__secondary-link--active');

            $(`ul.header__tertiary`)
                .removeClass('header__tertiary--active')
                .filter(`[data-index="${parentIndex}-${index}"]`)
                .addClass('header__tertiary--active');
        })

        $('.header__tertiary-back-button').click(function (event) {
            event.preventDefault();
            addState(states.statePushDown);
        })

        $('.overlay')
            .on('click', $.noop) // iOS workaround for event bubbling
            .click(function () {
                addState(states.statePushUpLeft)
            })

        // Check if we are on tablet/mobile
        checkIfShouldLockBodyScroll()

        // Check if we should open sidebar on tablet/desktop
        checkIfShouldOpenSidebar();

        // Check if state changed during resize
        const viewportWidthDebounder = debounce(checkScreenSize, 100);
        $(window).resize('resize', () => {
            viewportWidthDebounder()
            checkIfShouldOpenSidebar()
        });

        // Add class to root if iOS
        if (iOSCheck()) {
            $root.addClass('ios');

            // Calculate viewport height because iOS treats it differently then other browsers
            setIosViewportHeight();
            const viewportHeightDebounder = debounce(setIosViewportHeight, 100);
            $(window).resize('resize', viewportHeightDebounder);
        }
    }

    function setIosViewportHeight() {
        let vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
    }

    function checkScreenSize() {
        if (checkIfShouldLockBodyScroll()) {
            if ($root.is('[class*="state-push-down"]') && !isBodyLocked) {
                disableBodyScroll();
            }
        } else if ($root.is('[class*="state-push-down"]') && isBodyLocked) {
            enableBodyScroll();
        }
    }

    function debounce(func, wait) {
        let timeout;

        return function (...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                func.apply(this, args);
            }, wait);
        };
    }

    function checkIfShouldLockBodyScroll() {
        return shouldLockBodyScroll = $(window).width() < desktop
    }

    function checkIfShouldOpenSidebar() {
        const isOpen = $sidebar.prop('open');
        const isDesktop = $(window).width() >= desktop;

        if (!isOpen && isDesktop) {
            $sidebar.prop('open', true)
        }
        else if (isOpen && !isDesktop) {
            $sidebar.prop('open', false)
        }
    }

    function disableBodyScroll() {
        if (!shouldLockBodyScroll) {
            return
        }

        isBodyLocked = true;

        $scrollElements.each(function () {
            const scrollElement = $(this)[0];
            bodyScrollLock.disableBodyScroll(scrollElement);
        })
    }

    function enableBodyScroll() {
        isBodyLocked = false;
        bodyScrollLock.clearAllBodyScrollLocks()
    }

    function state(stateName) {
        return $root.hasClass(stateName)
    }

    function addState(stateName) {
        return $root.removeClass(statesSelector).addClass(states.stateAnimation).addClass(stateName)
    }

    function iOSCheck() {
        return [
            'iPad Simulator',
            'iPhone Simulator',
            'iPod Simulator',
            'iPad',
            'iPhone',
            'iPod'
        ].includes(navigator.platform)
            // iPad on iOS 13 detection
            || (navigator.userAgent.includes("Mac") && "ontouchend" in document)
    }

    return {
        initialize: () => {
            initNavigation()
        },
    }
})(AP)

AP.Form = (AP => {
    const $contactQuestion = $('.contact select.form-select')
    const $contactFormArea = $('.contact .contact__form-area')

    function initForm() {
        $contactQuestion.on('change', function () {
            if ($(this).val()) {
                $contactFormArea.addClass('contact__form-area--active');
            } else {
                $contactFormArea.removeClass('contact__form-area--active');
            }
        });
    }

    return {
        initialize: () => {
            initForm()
        },
    }
})(AP)

AP.Contact = (AP => {
    const $widget = $('.contact-widget');
    const $mobileToggler = $widget.find('.contact-widget__mobile-toggler');
    const $desktopToggler = $widget.find('.contact-widget__desktop-toggler');
    const $desktopWriteToggler = $widget.find('.contact-widget__tabs-button--write');
    const $desktopCallToggler = $widget.find('.contact-widget__tabs-button--call');
    const $content = $widget.find('.contact-widget__content');
    const disableBodyScroll = bodyScrollLock.disableBodyScroll;
    const enableBodyScroll = bodyScrollLock.enableBodyScroll;

    function initWidget() {
        if ($widget.length) {
            $mobileToggler.click(event => {
                event.preventDefault();

                if ($widget.hasClass('contact-widget--mobile-open')) {
                    $widget.removeClass('contact-widget--mobile-open');
                    enableBodyScroll($content[0]);
                } else {
                    $widget.addClass('contact-widget--mobile-open');
                    disableBodyScroll($content[0]);
                }
            });

            $desktopToggler.click(event => {
                event.preventDefault();

                if ($widget.hasClass('contact-widget--desktop-closed')) {
                    $widget.removeClass('contact-widget--desktop-closed');
                    try { localStorage.removeItem('ap:contact-desktop') } catch (e) { }
                } else {
                    $widget.addClass('contact-widget--desktop-closed');
                    try { localStorage.setItem('ap:contact-desktop', 'closed') } catch (e) { }
                }
            });

            try {
                if (localStorage.getItem('ap:contact-desktop') === 'closed') {
                    $widget.addClass('contact-widget--desktop-closed');
                }
            } catch (e) { }

            $desktopWriteToggler.click(event => {
                event.preventDefault();
                $widget.removeClass('contact-widget--desktop-call').toggleClass('contact-widget--desktop-write');
            });
            $desktopCallToggler.click(event => {
                event.preventDefault();
                $widget.removeClass('contact-widget--desktop-write').toggleClass('contact-widget--desktop-call');
            });
        }
    }

    return {
        initialize: () => {
            initWidget()
        },
    }
})(AP)

AP.Popup = (AP => {
    const $closeButtons = $('a.popup__close')
    const $reloadButtons = $('a.popup__close--reload');
    const $withoutReloadButtons = $('a.popup__close--without--reload');
    
    function initPopup() {

        $closeButtons.click(function (event) {
            event.preventDefault();

            if (document.referrer.indexOf(window.location.host) !== -1) {
                window.history.go(-1);
            } else {
                location.href = location.href.split('#')[0]
            }
        });

        $reloadButtons.click(function (event) {
            event.preventDefault();
            location.href = location.href.split('#')[0]
        });

        $withoutReloadButtons.click(function (event) {
            //Avoid postback
            event.preventDefault();
            window.history.pushState('', '/', location.href.split('#')[0]);

            $('html').removeClass('popup-visible');
        });

        // Tell the CSS that the popup is ready
        $('html').addClass('popup-visible');
    }

    return {
        initialize: () => {
            initPopup()
        },
    }
})(AP)

AP.SearchResult = (AP => {
    const $filter = $('.search-result__filter')

    function initFilter() {
        // Mobile
        $filter.find('.search-result__filter-text').click(function () {
            $filter.toggleClass('search-result__filter--active');
        });
    }

    function initClear() {
        $('.search-result__clear-button').click(function () {
            $('.search-result__input').val('');
        });
    }

    return {
        initialize: () => {
            initFilter()
            initClear()
        },
    }
})(AP)

AP.SearchSuggestions = (AP => {
    const $data = $('.header__search-data')
    const $input = $('.header__search-input');
    const formPath = $('.header__search-form').attr('action')
    const apiPath = $('.header__search-form').data('suggestions')
    let controller = new AbortController();
    let loading = false;

    const Item = ({ url, text, title }) => `
    <li class="search-suggestions__list-item">
      <a href="${url}" class="search-suggestions__link">
        <span class="search-suggestions__title">${title}</span>
        <span class="search-suggestions__text">${text}</span>
      </a>
    </li>
  `
    function markup(total, query, viewalltext) {
        return `
      <div class="header__search-suggestions">
        <ul class="search-suggestions">#results</ul>
        <ul class="links">
          <li><a href="${formPath}?q=${query}">${viewalltext} (${total})</a></li>
        </ul>
      </div>
    `
    }

    function getData(query) {
        loading = true;

        if (!query) {
            return Promise.resolve();
        }

        return fetch(`${window.location.origin}${apiPath}?query=${query}`, {
            signal: controller.signal
        })
            .then(response => response.json())
            .then(data => data)
            .catch(() => null)
            .finally(() => loading = false);
    }

    function init() {
        if (!$data.length) {
            return
        }

        $input.on('input', async () => {
            if (loading) {
                controller.abort();
                controller = new AbortController();
            }

            const query = $input.val();
            const data = await getData(query)

            if (data && query) {
                const jsdata = JSON.parse(data);
                const items = jsdata.items.map(Item).join('');
                const output = markup(jsdata.total, query, jsdata.viewalltext)
                $data.html(output.replace('#results', items))
            } else {
                $data.empty()
            }
        });

        $('.header__search-clear-button').click(function () {
            $data.empty()
        });
    }

    return {
        initialize: () => {
            init()
        },
    }
})(AP)

$(document).ready(function () {
    AP.Navigation.initialize()
    AP.Form.initialize()
    AP.Contact.initialize()
    AP.Popup.initialize()
    AP.SearchResult.initialize()
    AP.SearchSuggestions.initialize()

    // jQuery tooltips
    $('[data-toggle="tooltip"]').tooltip()
});;
AP.Forms = (AP => {
    const $formsElements = $('.ValidationRequired')

    function initForms() {
        $formsElements.each(function () {

            var element = $(this).find('label');
            if (element !== undefined) {
                element.append("<i>*</i>");
            }
        });
    }

    return {
        initialize: () => {
            initForms()
        },
    }
})(AP)

$(document).ready(function () {
    AP.Forms.initialize();
    formFileUploadInputChange();
    datetimepickerCloseOnSelect();
    formsProgressSlashSpace();
});

var formsProgressSlashSpace = function () {
    // *** Mellemrum foran '/'  :   'Trin 1/ 6' -> 'Trin 1 / 6'
    $('.Form__NavigationBar__ProgressBar--Text').each(function () {
        $(this).html($(this).html().replace("</span>/", "</span>  /"));
    });
};

var formFileUploadInputChange = function () {
    $(".FormFileUpload__Input").parent('div').append("<span class=fillistemaxsizeerror>Den samlede størrelse på de overførte filer må højst være <span class=fillistemaxsizeval></span>.<br/>Der er nu: <span class=fillistemaxsizeerrorval></span><br/></span>");
    $(".fillistemaxsizeerror").addClass("Form__Element__ValidationError");
    $(".fillistemaxsizeerror", $(".FormFileUpload__Input").parent('div').parent('section')).hide();

    $(".FormFileUpload__Input").parent('div').parent('section').append("<div class=buttonmaxsizeerror>Send</div>");
    $(".buttonmaxsizeerror").addClass("button button--primary button--full-mobile button--large disabled");
    $(".buttonmaxsizeerror").hide();

    $(".FormFileUpload__Input").change(function () {
        $(".Form__Element__ValidationError").hide();
        if ($("#FormFileUpload__InputCopyElement")[0] !== undefined) {
            $($(this)[0]).prop('files', new FileListItemsConcatenate($("#FormFileUpload__InputCopyElement")[0].files, $(this)[0].files));
            $(".FormFileUpload__InputCopy").remove();
        }

        // *** gem kopi af input
        var inputCopyFiles = $(this)[0].files;
        $(this).parent('div').parent('section').append("<input id=FormFileUpload__InputCopyElement name=newName type=file class=FormFileUpload__InputCopy multiple=multiple></input>");
        $($("#FormFileUpload__InputCopyElement")).prop('files', new FileListItems(inputCopyFiles));

        var fileList = $(this)[0].files;
        $(".filliste", $(this).parent('div')).remove();

        if (fileList.length > 0) {
            var size = 0;
            for (let i = 0; i < fileList.length; i++) {
                $(this).parent('div').append("<span class=filliste title=fjern data-fileid=" + i + "><span class=fillistenavn>" + fileList[i].name + " - " + GetBytesSizeDisplay(fileList[i].size) + "</span><br/></span>");
                size = size + fileList[i].size;
            }

            var filesmaxsize = 10485760;

            $("main").children().each(function () {
                if ($(this).hasClass("filesmaxsizemb")) {
                    filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                }
            });

            var bFoundMaxSize = false;
            $(this).closest("form").parent().children().each(function () {
                if ($(this).hasClass("filesmaxsizemb")) {
                    filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                    bFoundMaxSize = true;
                }
            });
            if (!bFoundMaxSize) {
                $(this).closest("form").parent().parent().children().each(function () {
                    if ($(this).hasClass("filesmaxsizemb")) {
                        filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                    }
                });
            }

            $(".fillistemaxsizeerror").html("Den samlede størrelse på de overførte filer må højst være <span class=fillistemaxsizeval></span>.<br/>Der er nu: <span class=fillistemaxsizeerrorval></span><br/>");

            $(".fillistemaxsizeval", $(this).parent('div').parent('section')).html(GetBytesSizeDisplay(filesmaxsize));

            var sects = 0;
            $("section", $("main")).each(function () {
                if (typeof $(this).data('f-stepindex') !== 'undefined') {
                    sects++;
                }
            });
            if (sects > 1) {
                $(".buttonmaxsizeerror").addClass("multisections");
            }

            if (size > filesmaxsize) {

                $("button", $(this).parent('div').parent('section')).hide();
                $(".fillistemaxsizeerrorval", $(this).parent('div').parent('section')).html(GetBytesSizeDisplay(size));
                $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).show();
                $(".buttonmaxsizeerror").show();
            }
            else {
                $("button", $(this).parent('div').parent('section')).show();
                $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).hide();
                $(".buttonmaxsizeerror").hide();
            }
        }
        else {
            $("button", $(this).parent('div').parent('section')).show();
            $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).hide();
            $(".buttonmaxsizeerror").hide();
        }

        fillisteClick();
    });
};

var fillisteClick = function () {
    $(".filliste").click(function () {
        var removeItem = $(this).attr("data-fileid");
        var fileInputContainer = $(this).parent('div');

        $(".FormFileUpload__Input", fileInputContainer).each(function () {
            // *** fjern én fil
            $($(this)[0]).prop('files', new FileListItems(ListRemovedItem(removeItem, $(this)[0].files)));
            $(".filliste", fileInputContainer).remove();
            var fileList = $(this)[0].files;
            var size = 0;
            if (fileList.length > 0) {
                for (let i = 0; i < fileList.length; i++) {
                    $(this).parent('div').append("<span class=filliste title=fjern data-fileid=" + i + "><span class=fillistenavn>" + fileList[i].name + " - " + GetBytesSizeDisplay(fileList[i].size) + "</span><br/></span>");
                    size = size + fileList[i].size;
                }

                var filesmaxsize = 10485760;

                $("main").children().each(function () {
                    if ($(this).hasClass("filesmaxsizemb")) {
                        filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                    }
                });

                var bFoundMaxSize = false;
                $(this).closest("form").parent().children().each(function () {
                    if ($(this).hasClass("filesmaxsizemb")) {
                        filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                        bFoundMaxSize = true;
                    }
                });
                if (!bFoundMaxSize) {
                    $(this).closest("form").parent().parent().children().each(function () {
                        if ($(this).hasClass("filesmaxsizemb")) {
                            filesmaxsize = this.dataset.filesmaxsizemb * 1024 * 1024;
                        }
                    });
                }

                if (size > filesmaxsize) {

                    $("button", $(this).parent('div').parent('section')).hide();
                    $(".fillistemaxsizeerrorval", $(this).parent('div').parent('section')).html(GetBytesSizeDisplay(size));
                    $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).show();
                    $(".buttonmaxsizeerror").show();
                }
                else {
                    $("button", $(this).parent('div').parent('section')).show();
                    $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).hide();
                    $(".buttonmaxsizeerror").hide();
                }
            }
            else {
                $("button", $(this).parent('div').parent('section')).show();
                $(".fillistemaxsizeerror", $(this).parent('div').parent('section')).hide();
                $(".buttonmaxsizeerror").hide();
            }

            $(".FormFileUpload__InputCopy").remove();
            // *** gem kopi af input
            $(this).parent('div').parent('section').append("<input id=FormFileUpload__InputCopyElement name=newName type=file class=FormFileUpload__InputCopy multiple=multiple></input>");
            $($("#FormFileUpload__InputCopyElement")).prop('files', new FileListItems(fileList));
        });

        fillisteClick();
    });
};

var datetimepickerCloseOnSelect = function () {
    // *** datetimepicker box lukker når der vælges en dato
    $('div.FormDateTime').each(function () {
        $(this).find('input').click(function () {
            $('td[data-handler=selectDay]').click(function () {
                $('#ui-datetimepicker-div').hide();
            });
        });
    });
};

function FileListItems(files) {
    var b = new ClipboardEvent("").clipboardData || new DataTransfer()
    for (var i = 0, len = files.length; i < len; i++) b.items.add(files[i])
    return b.files
}

function FileListItemsConcatenate(files1, files2) {
    var b = new ClipboardEvent("").clipboardData || new DataTransfer()
    for (var i = 0, len = files1.length; i < len; i++) b.items.add(files1[i])
    for (var i = 0, len = files2.length; i < len; i++) b.items.add(files2[i])
    return b.files
}

function ListRemovedItem(itemIndex, fileListCopy) {
    var removeItem = fileListCopy[itemIndex];
    fileListCopy = jQuery.grep(fileListCopy, function (value) {
        return value != removeItem;
    });
    return fileListCopy;
}


function GetBytesSizeDisplay(fileSize) {
    var dFilesSize = "0 kB";
    if (fileSize > 0) {
        if (fileSize > 1024 * 1024) {
            dFilesSize = (fileSize / (1024 * 1024)).toFixed(2) + " MB";
        }
        else {
            dFilesSize = (fileSize / 1024).toFixed(2) + " kB";
        }
    }
    return dFilesSize;
};
if (typeof $$epiforms !== 'undefined') {

    var $body = $("body");
    var $loadingDiv = $('<div class="modal"></div>');
    $body.append($loadingDiv);
    epi.EPiServer.Forms.AsyncSubmit = true;

    $$epiforms(document).ready(function myfunction() {
        // listen to event when form is about submitting
        $$epiforms(".EPiServerForms").on("formsStartSubmitting", function (data) {
            //var $formContainer = $('#' + data.workingFormInfo.Id);
            //$formContainer.addClass("loading");
            $body.addClass('loading');
        });

        // listen to event when form is successfully submitted
        $$epiforms(".EPiServerForms").on("formsSubmitted", function (data) {
            $body.removeClass('loading');
        });

        // formsSubmittedError
        $$epiforms(".EPiServerForms").on("formsSubmittedError", function (data) {
            $body.removeClass('loading');
        });

        // formsNavigationPrevStep
        $$epiforms(".EPiServerForms").on("formsNavigationPrevStep", function (event, param1, param2) {
            //console.log($$epiforms(this).get(0), event);
        });

        $$epiforms(".EPiServerForms").on("formsStepValidating", function (event, param1, param2) {
            //console.log($$epiforms(this).get(0), event);
        });

        // formsNavigationNextStep
        $$epiforms(".EPiServerForms").on("formsNavigationNextStep formsSetupCompleted", function (event, param1, param2) {
            //Go through step, to see if there are any check- and radiobuttons needed to be hidden if datavisibility is set

            //Current step
            var _currentStep = $$epiforms(this).get(0).getElementsByClassName("Form__Element Form__SystemElement FormHidden FormHideInSummarized").__FormCurrentStepIndex.value;
            var _currentStepNum = parseInt(_currentStep) + 1;

            for (var sectionIdx = _currentStepNum; sectionIdx < _currentStepNum + 2; sectionIdx++) { //Set hidden fields 2 steps ahead, to handle non visible steps

                var section = $('*[data-f-stepindex="' + sectionIdx + '"]');

                if (section != null && section.length == 1) {

                    //Get formelements on this step
                    var elements = section[0].children;

                    for (var elementIdx = 0; elementIdx < elements.length; elementIdx++) {
                        if (elements[elementIdx].className.includes("Form__Element")
                            && elements[elementIdx].attributes.datavisibility != null
                        ) {

                            if (elements[elementIdx].attributes.datavisibility != null) {
                                //Combobox or checkbox
                                var elementValue = elements[elementIdx].attributes.datavisibility.value;

                                var elementVisibilityValues = elementValue.split('||'); //We can have multiple target/source elements in the 'datavisibility' field

                                for (var elementVisibilityIdx = 0; elementVisibilityIdx < elementVisibilityValues.length; elementVisibilityIdx++) {

                                    var elementValues = elementVisibilityValues[elementVisibilityIdx].split(';');

                                    if (elementValues.length == 3
                                        && (elements[elementIdx].className == "Form__Element FormChoice" || elements[elementIdx].className == "Form__Element FormChoice ValidationRequired" || elements[elementIdx].className == 'form-radio__text')
                                        && elementValues[0].includes('sourceName:')
                                        && elementValues[1].includes('sourceVal:')
                                        && elementValues[2].includes('targetName:')) {

                                        var sourceName = elementValues[0].replace('sourceName:', '');
                                        var sourceVal = elementValues[1].replace('sourceVal:', '');
                                        var targetName = elementValues[2].replace('targetName:', '');

                                        var targetNames = targetName.split('|');

                                        for (var tnIdx = 0; tnIdx < targetNames.length; tnIdx++) {

                                            //Get targetElement
                                            var targetContainer = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"]');
                                            var targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] input');

                                            if (targetContainer.length == 1 && targetElement.length == 0) {
                                                targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] textarea');
                                            }
                                            else if (targetContainer.length == 0) {
                                                //DateTime
                                                targetContainer = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"]');
                                                targetElement = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"] input');
                                            }

                                            //Defualt hide target element
                                            targetContainer.addClass('hide');

                                            //Get radio- or checkbox buttons
                                            var radioElements = $('input:radio[name="' + sourceName + '"]')
                                            var checkboxElements = $('input:checkbox[name="' + sourceName + '"]')

                                            if (radioElements.length > 0) {
                                                for (var rdIdx = 0; rdIdx < radioElements.length; rdIdx++) {

                                                    var sourceValues = sourceVal.split('|');

                                                    for (var svIdx = 0; svIdx < sourceValues.length; svIdx++) {

                                                        if (radioElements[rdIdx].value == sourceValues[svIdx] && radioElements[rdIdx].checked) {
                                                            //We have target checked and target has sourcevalue - Show target
                                                            targetContainer.removeClass('hide');
                                                        }
                                                        else if (radioElements[rdIdx].value == sourceValues[svIdx] && !radioElements[rdIdx].checked) {
                                                            //We do not have target checked but it hassourcevalue - Hide target and paste in dummy value
                                                            //targetElement.val('¤');

                                                            if (!targetContainer.hasClass('FormDateTime')) {

                                                                if (!targetElement.hasClass('FormChoice__Input')) {
                                                                    if (targetElement.val() != '¤') //we have double postback - so avoid overwriting value if set
                                                                    {
                                                                        targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                                                    }

                                                                    targetElement.val('¤');
                                                                }
                                                            }
                                                            else {
                                                                if (targetElement.val() != '01-01-1900') //we have double postback - so avoid overwriting value if set
                                                                {
                                                                    targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                                                }

                                                                targetElement.val('01-01-1900');
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            else if (checkboxElements.length > 0) {
                                                for (var cbIdx = 0; cbIdx < checkboxElements.length; cbIdx++) {

                                                    if (checkboxElements[cbIdx].value == sourceVal && checkboxElements[cbIdx].checked) {
                                                        //We have target checked and target has sourcevalue - Show target
                                                        targetContainer.removeClass('hide');
                                                    }
                                                    else if (checkboxElements[cbIdx].value == sourceVal && !checkboxElements[cbIdx].checked) {
                                                        //We do not have target checked but it has sourcevalue - Hide target and paste in dummy value
                                                        //targetElement.val('¤');

                                                        if (!targetContainer.hasClass('FormDateTime')) {
                                                            if (targetElement.val() != '¤') //we have double postback - so avoid overwriting value if set
                                                            {
                                                                targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                                            }

                                                            targetElement.val('¤');
                                                        }
                                                        else {
                                                            if (targetElement.val() != '01-01-1900') //we have double postback - so avoid overwriting value if set
                                                            {
                                                                targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                                            }

                                                            targetElement.val('01-01-1900');
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }


            }

            //console.log($$epiforms(this).get(0), event);
        });
    });
}

(function ($) {

    if (typeof (epi) == 'undefined' || typeof (epi.EPiServer) == 'undefined' || typeof (epi.EPiServer.Forms) == 'undefined') {
        console.error('Forms is not initialized correctly');
        return;
    }

    if (typeof ($) == 'undefined') {
        console.error('Forms cannot work without jQuery');
        return;
    }

    /// add forms events
    /// ========================================
    document.addEventListener('keyup', onKeyUp, true);
    document.addEventListener('blur', onBlur, true);
    document.addEventListener('focus', onFocus, true);
    document.addEventListener('click', onClick, true);

    function onKeyUp(e) {
        if (e.metaKey || e.altKey) {
            return;
        }

        if (e.srcElement.maxLength !== null && e.srcElement.maxLength > 0) {
            var maxLength = e.srcElement.maxLength;
            var elementLength = e.srcElement.value.length;

            var sum = maxLength - elementLength;

            $(e.srcElement.parentNode).find('.itemsLeft').remove();
            $(e.srcElement).closest("div").append("<label class='itemsLeft' style='display: inline; float: right; margin-top: 0;'>(" + sum + " tegn tilbage)</label>"); // Under textelt
        }
    }

    //Leave field
    function onBlur(e) {
        $(e.srcElement.parentNode).find('.itemsLeft').remove();
    }

    //Enter field
    function onFocus(e) {
        if (e.srcElement.maxLength !== null && e.srcElement.maxLength > 0) {
            var maxLength = e.srcElement.maxLength;
            var elementLength = e.srcElement.value.length;

            var sum = maxLength - elementLength;

            $(e.srcElement).closest("div").append("<label class='itemsLeft' style='display: inline; float: right; margin-top: 0;'>(" + sum + " tegn tilbage)</label>"); // Under textelt
        }
    }

    function onClick(e) {

        var element = e.srcElement;

        if (element.className == 'FormChoice__Input FormChoice__Input--Radio'
            || element.className == 'FormChoice__Input FormChoice__Input--Radio focus-visible'
            || element.className == 'form-radio__text'
            || element.className == 'FormChoice__Input FormChoice__Input--Checkbox focus-visible'
            || element.className == 'form-checkbox__text') {

            //Define on elements in CMS

            //Single target
            //sourceName:[Field to trigger from];sourceVal:[Value to match];targetName:[Target field to set visible]
            //Eg.
            //sourceName:__field_6192;sourceVal:Ja;targetName:__field_6193

            //Multiple targets
            //sourceName:[Field to trigger from];sourceVal:[Value to match];targetName:[Target field to set visible]|[Other target field to set visible]
            //Eg.
            //sourceName:__field_6192;sourceVal:Ja;targetName:__field_6193|__field_7521
            //sourceName:__field_6192;sourceVal:Ja|Nej;targetName:__field_6193|__field_7521

            //Multiple sources and targets
            //sourceName:[Field to trigger from];sourceVal:[Value to match];targetName:[Target field to set visible]||sourceName:[Other Field to trigger from];sourceVal:[Other Value to match];targetName:[Other Target field to set visible]
            //Eg.
            //sourceName:__field_6192;sourceVal:Ja;targetName:__field_6193||sourceName:__field_6192;sourceVal:Nej|Måske;targetName:__field_6193|__field_7521

            //In ordre to bypass validation on the required textfield, we temporary set value to '¤' below upon click-event and saves current value in attribute datavisibility-elementvalue
            //In ordre to bypass validation on the required datefield, we temporary set value to '01-01-1900' below upon click-event and saves current value in attribute datavisibility-elementvalue


            if (element.parentNode != null
                && element.parentNode.parentNode != null
                && element.parentNode.parentNode.parentElement != null
                && element.parentNode.parentNode.parentElement.attributes != null
                && element.parentNode.parentNode.parentElement.attributes.datavisibility != null
                && element.parentNode.parentNode.parentElement.attributes.datavisibility.value != "") {

                var elementValue = element.parentNode.parentNode.parentElement.attributes.datavisibility.value;

                var elementVisibilityValues = elementValue.split('||'); //We can have multiple target/source elements in the 'datavisibility' field

                for (var elementVisibilityIdx = 0; elementVisibilityIdx < elementVisibilityValues.length; elementVisibilityIdx++) {

                    var elementValues = elementVisibilityValues[elementVisibilityIdx].split(';');

                    if (elementValues.length == 3
                        && (element.className == 'FormChoice__Input FormChoice__Input--Radio' || element.className == 'form-radio__text' || element.className == 'FormChoice__Input FormChoice__Input--Radio focus-visible')
                        && elementValues[0].includes('sourceName:')
                        && elementValues[1].includes('sourceVal:')
                        && elementValues[2].includes('targetName:')) {
                        //Radio buttons (Uses arrows to set through keyboard)

                        var sourceName = elementValues[0].replace('sourceName:', '').trim();
                        var sourceVal = elementValues[1].replace('sourceVal:', '').trim();
                        var targetName = elementValues[2].replace('targetName:', '').trim();

                        var targetNames = targetName.split('|');

                        for (var tnIdx = 0; tnIdx < targetNames.length; tnIdx++) {

                            var targetContainer = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"]');
                            var targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] input');

                            if (targetContainer.length == 1 && targetElement.length == 0) {
                                targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] textarea');
                            }
                            else if (targetContainer.length == 0) {
                                //DateTime
                                targetContainer = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"]');
                                targetElement = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"] input');
                            }

                            var sourceValues = sourceVal.split('|');

                            for (var svIdx = 0; svIdx < sourceValues.length; svIdx++) {

                                if (element.name == sourceName && element.value == sourceValues[svIdx]) {
                                    targetContainer.removeClass('hide');
                                    targetElement.val(targetElement.attr('datavisibility-elementvalue'));

                                    break;
                                }
                                else {
                                    targetContainer.addClass('hide');

                                    if (!targetContainer.hasClass('FormDateTime')) {
                                        if (targetElement.val() != '¤') //we have double postback - so avoid overwriting value if set
                                        {
                                            targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                        }

                                        targetElement.val('¤');
                                    }
                                    else {
                                        if (targetElement.val() != '01-01-1900') //we have double postback - so avoid overwriting value if set
                                        {
                                            targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                        }

                                        targetElement.val('01-01-1900');
                                    }
                                }
                            }
                        }
                    }
                    else if (elementValues.length == 3
                        && (element.className == 'form-checkbox__text' || element.className == 'FormChoice__Input FormChoice__Input--Checkbox focus-visible')
                        && elementValues[0].includes('sourceName:')
                        && elementValues[1].includes('sourceVal:')
                        && elementValues[2].includes('targetName:')) {
                        //Checkbox (Uses space to set through keyboard)

                        var sourceName = elementValues[0].replace('sourceName:', '').trim();
                        var sourceVal = elementValues[1].replace('sourceVal:', '').trim();
                        var targetName = elementValues[2].replace('targetName:', '').trim();

                        var targetNames = targetName.split('|');

                        var mouseClicked = false;

                        if (e.screenX == 0 && e.screenY == 0) {
                            mouseClicked = false;
                        } else {
                            mouseClicked = true;
                        }

                        for (var tnIdx = 0; tnIdx < targetNames.length; tnIdx++)
                        {

                            var targetContainer = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"]');
                            var targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] input');

                            if (targetContainer.length == 1 && targetElement.length == 0) {
                                targetElement = $('div.Form__Element[data-f-element-name="' + targetNames[tnIdx] + '"] textarea');
                            }
                            else if (targetContainer.length == 0) {
                                //DateTime
                                targetContainer = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"]');
                                targetElement = $('div.Form__Element[data-epiforms-element-name="' + targetNames[tnIdx] + '"] input');
                            }

                            var sourceValues = sourceVal.split('|');

                            for (var svIdx = 0; svIdx < sourceValues.length; svIdx++) {

                                //Element.checked is delayed. So when we get here and it not checked in front-end, it is checked in the backend!
                                //Furthermore mouseclick and keyboard click has diffent behaviour. So we need to check for both!

                                if (element.parentNode.parentNode.parentNode.attributes[3].value == sourceName && element.parentElement.children[0].value == sourceValues[svIdx] && !element.parentElement.children[0].checked) {

                                    targetContainer.removeClass('hide');
                                    targetElement.val(targetElement.attr('datavisibility-elementvalue'));

                                    break;
                                }
                                else if (element.parentElement.children[0].value == sourceValues[svIdx] && ((element.parentElement.children[0].checked && mouseClicked) || (!element.parentElement.children[0].checked && !mouseClicked)) )  {
                                    targetContainer.addClass('hide');

                                    if (!targetContainer.hasClass('FormDateTime')) {
                                        if (targetElement.val() != '¤') //we have double postback - so avoid overwriting value if set
                                        {
                                            targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                        }

                                        targetElement.val('¤');
                                    }
                                    else {
                                        if (targetElement.val() != '01-01-1900') //we have double postback - so avoid overwriting value if set
                                        {
                                            targetElement.attr('datavisibility-elementvalue', targetElement.val());
                                        }

                                        targetElement.val('01-01-1900');
                                    }
                                }
                                else if (element.parentNode.parentNode.parentNode.attributes[2].value == sourceName && element.parentElement.children[0].value == sourceValues[svIdx] && ((!element.parentElement.children[0].checked && mouseClicked) || (element.parentElement.children[0].checked && !mouseClicked))) {

                                    targetContainer.removeClass('hide');
                                    targetElement.val(targetElement.attr('datavisibility-elementvalue'));

                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        else if (element.className == "Form__NavigationBar__Action FormExcludeDataRebind btnPrev") {

        }
        else if (element.className == "Form__NavigationBar__Action FormExcludeDataRebind btnNext") {

        }

    }

    /// add forms validators
    /// ========================================
    var _utilsSvc = epi.EPiServer.Forms.Utils;

    var customValidators = {
        Validators: {
            //For regular expression validators
            "APPension.dk.Business.Validators.MaxLengthValidator": _utilsSvc.validateRegularExpressionValidator,
            "APPension.dk.Business.Validators.FieldVisibleValidator": _utilsSvc.validateRegularExpressionValidator

            //For other validator
            //"the.full.namespace.of.your.validator" : 
            //    function (fieldName, fieldValue, validatorMetaData){
            // summary:
            //      VALIDATE REQUIRED
            // fieldName: String
            //      Name of the field to be validated.
            // fieldValue: [Object]
            //      User input value for the field.
            // validatorMetaData: [Object]
            //      Validation meta data for the current element
            // returns: Object
            // tags:
            //      private
            // See EpiserverForms.js for examples
            // }
        }
    };

    $.extend(true, epi.EPiServer.Forms, customValidators);

})($$epiforms || $);  // use the Forms's jQuery before using site's jQuery;
