var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 });
import { i as isKeyEvent, k as keyEvents, u as uuidv4, l as loadStyleSheet } from "../chunks/chunk.dcf-utility.js?v=6.1.1";
class DCFModal {
  static {
    __name(this, "DCFModal");
  }
  constructor(modals, bodyScrollLock) {
    this.modals = modals, this.currentModal = null, this.currentBtn = null, this.body = document.querySelector("body"), this.nonModals = [];
    const skipNav = document.getElementById("dcf-skip-nav"), header = document.getElementById("dcf-header"), main = document.getElementById("dcf-main"), footer = document.getElementById("dcf-footer");
    skipNav && this.nonModals.push(skipNav), header && this.nonModals.push(header), main && this.nonModals.push(main), footer && this.nonModals.push(footer), this.disableBodyScroll = null, this.enableBodyScroll = null, bodyScrollLock && bodyScrollLock.disableBodyScroll && bodyScrollLock.enableBodyScroll && (this.disableBodyScroll = bodyScrollLock.disableBodyScroll, this.enableBodyScroll = bodyScrollLock.enableBodyScroll);
  }
  /**
   * Prepend modals to body so that elements outside of modal can be made inert
   * @param {string} element: the element that we are targetting
   */
  appendToBody(element) {
    this.body.appendChild(element);
  }
  // Toggle modal
  toggleModal(modalId, btnId) {
    document.getElementById(modalId).getAttribute("aria-hidden") === "false" ? this.closeModal(modalId) : this.openModal(modalId, btnId);
  }
  // Set nav toggle button state as open or closed
  // Note: Assumes nav toggle buttons are svgs with expected markup
  setNavToggleBtnState(btn, btnState = "open") {
    const btnSVGs = btn.getElementsByTagName("svg"), btnLabels = btn.getElementsByClassName("dcf-nav-toggle-label");
    if (btnSVGs.length) {
      const gTags = btnSVGs[0].getElementsByTagName("g");
      Array.from(gTags).forEach((tag) => {
        tag.classList.contains("dcf-nav-toggle-icon-open") ? btnState.toLowerCase() === "open" ? tag.classList.remove("dcf-d-none") : tag.classList.add("dcf-d-none") : tag.classList.contains("dcf-nav-toggle-icon-close") && (btnState.toLowerCase() === "open" ? tag.classList.add("dcf-d-none") : tag.classList.remove("dcf-d-none"));
      });
    }
    btnLabels.length && (btnState.toLowerCase() === "open" ? btnLabels[0].textContent = btn.getAttribute("data-nav-toggle-label-open") ? btn.getAttribute("data-nav-toggle-label-open") : "Open" : btnLabels[0].textContent = btn.getAttribute("data-nav-toggle-label-closed") ? btn.getAttribute("data-nav-toggle-label-closed") : "Close");
  }
  // Open modal
  openModal(modalId, openBtnId) {
    const navToggleGroup = document.getElementById("dcf-nav-toggle-group"), navToggleGroupParent = navToggleGroup && navToggleGroup.parentElement ? navToggleGroup.parentElement : null;
    this.modals.forEach((modal) => {
      modal.getAttribute("id") !== modalId && this.closeModal(modal.getAttribute("id"));
    });
    const thisModal = document.getElementById(modalId), modalOpen = thisModal.getAttribute("aria-hidden") === "false";
    let modalWithNavToggleGroup = !1;
    if (openBtnId) {
      this.currentBtn = openBtnId;
      const openBtn = document.getElementById(openBtnId);
      modalWithNavToggleGroup = openBtn && openBtn.getAttribute("data-with-nav-toggle-group") === "true", modalWithNavToggleGroup && this.setNavToggleBtnState(openBtn, "closed");
    }
    if (this.currentModal = modalId, modalOpen)
      return;
    const preOpenEventName = `ModalPreOpenEvent_${modalId}`, openButtonElement = document.getElementById(openBtnId);
    let preOpenEvent = new CustomEvent(preOpenEventName);
    openButtonElement !== null && (preOpenEvent = new CustomEvent(preOpenEventName, {
      detail: {
        btn: openButtonElement
      }
    })), document.dispatchEvent(preOpenEvent), this.nonModals.forEach((nonModal) => {
      modalWithNavToggleGroup && navToggleGroup && nonModal === navToggleGroupParent ? (nonModal.setAttribute("aria-hidden", "false"), navToggleGroupParent.childNodes.forEach((child) => {
        child.nodeType === Node.ELEMENT_NODE && (child === navToggleGroup ? child.setAttribute("aria-hidden", "false") : child.setAttribute("aria-hidden", "true"));
      })) : nonModal.setAttribute("aria-hidden", "true");
    }), this.disableBodyScroll && this.disableBodyScroll(thisModal, {
      allowTouchMove: /* @__PURE__ */ __name((element) => {
        let currentEl = element;
        for (; currentEl && currentEl !== document.body; ) {
          if (currentEl.classList.contains("dcf-modal-content"))
            return !0;
          currentEl.parentElement && (currentEl = currentEl.parentElement);
        }
        return !1;
      }, "allowTouchMove")
    }), this.body.classList.add("dcf-modal-is-open"), thisModal.setAttribute("aria-hidden", "false"), thisModal.classList.remove("dcf-opacity-0", "dcf-pointer-events-none", "dcf-invisible"), thisModal.classList.add("dcf-opacity-100", "dcf-pointer-events-auto"), modalWithNavToggleGroup && thisModal.classList.add("dcf-z-modal-behind-nav-toggle-group"), thisModal.focus();
    const tabFocusEls = thisModal.querySelectorAll('button:not([hidden]):not([disabled]), [href]:not([hidden]), input:not([hidden]):not([type="hidden"]):not([disabled]), select:not([hidden]):not([disabled]), textarea:not([hidden]):not([disabled]), [tabindex="0"]:not([hidden]):not([disabled]), summary:not([hidden]), [contenteditable]:not([hidden]), audio[controls]:not([hidden]), video[controls]:not([hidden])'), handleTrapFocus = /* @__PURE__ */ __name((event) => {
      const firstTabFocusEl = tabFocusEls[0], lastTabFocusEl = tabFocusEls[tabFocusEls.length - 1];
      (event.key === "Tab" || event.keyCode === 9) && (event.key === "Tab" || event.keyCode === 9) && (event.shiftKey ? document.activeElement === thisModal ? (event.preventDefault(), firstTabFocusEl.focus()) : document.activeElement === firstTabFocusEl && (event.preventDefault(), lastTabFocusEl.focus()) : document.activeElement === lastTabFocusEl && (event.preventDefault(), firstTabFocusEl.focus()));
    }, "handleTrapFocus");
    thisModal.addEventListener("keydown", handleTrapFocus), document.addEventListener(`ModalCloseEvent_${modalId}`, () => {
      thisModal.removeEventListener("keydown", handleTrapFocus);
    });
    const openEventName = `ModalOpenEvent_${modalId}`;
    document.dispatchEvent(new CustomEvent(openEventName));
  }
  // Close modal
  closeModal(modalId) {
    const navToggleGroup = document.getElementById("dcf-nav-toggle-group"), navToggleGroupParent = navToggleGroup && navToggleGroup.parentElement ? navToggleGroup.parentElement : null, thisModal = document.getElementById(modalId), confirmClose = thisModal.dataset.confirmClose, modalClosed = thisModal.getAttribute("aria-hidden") === "true";
    if (this.currentModal = null, modalClosed)
      return;
    const preCloseEventName = `ModalPreCloseEvent_${modalId}`;
    if (document.dispatchEvent(new CustomEvent(preCloseEventName)), confirmClose && !window.confirm(confirmClose))
      return;
    if (this.body.classList.remove("dcf-modal-is-open"), this.currentBtn) {
      const closeBtn = document.getElementById(this.currentBtn);
      closeBtn && closeBtn.getAttribute("data-with-nav-toggle-group") === "true" && this.setNavToggleBtnState(closeBtn, "open");
    }
    this.nonModals.forEach((nonModal) => {
      navToggleGroup && nonModal === navToggleGroupParent && navToggleGroupParent.childNodes.forEach((child) => {
        child.nodeType === Node.ELEMENT_NODE && child.setAttribute("aria-hidden", "false");
      }), nonModal.setAttribute("aria-hidden", "false");
    }), thisModal.setAttribute("aria-hidden", "true"), thisModal.classList.remove("dcf-opacity-100", "dcf-pointer-events-auto", "dcf-z-modal-behind-nav-toggle-group"), thisModal.classList.add("dcf-opacity-0", "dcf-pointer-events-none");
    function modalTransition() {
      thisModal.removeEventListener("transitionend", modalTransition), thisModal.classList.contains("dcf-invisible") || thisModal.classList.add("dcf-invisible");
    }
    __name(modalTransition, "modalTransition"), thisModal.addEventListener("transitionend", modalTransition), this.currentBtn && document.getElementById(this.currentBtn).focus(), this.enableBodyScroll && this.enableBodyScroll(thisModal);
    const eventName = `ModalCloseEvent_${modalId}`;
    document.dispatchEvent(new CustomEvent(eventName));
  }
  btnToggleListen(btnToggleModal, modalId, btnId) {
    btnToggleModal.addEventListener("click", () => {
      let currentBtnID = btnId;
      btnId !== btnToggleModal.id && (currentBtnID = btnToggleModal.id), this.toggleModal(modalId, currentBtnID);
    }, !1);
  }
  btnCloseListen(btnCloseModal, modal) {
    btnCloseModal.addEventListener("click", () => {
      this.closeModal(modal.getAttribute("id"));
    }, !1);
  }
  overlayListen(modal, modalWrapper) {
    modal.addEventListener("click", (event) => {
      modalWrapper.contains(event.target) || this.closeModal(modal.getAttribute("id"));
    });
  }
  escListen() {
    document.addEventListener("keydown", (event) => {
      isKeyEvent(event, keyEvents("escape")) && this.currentModal && (event.preventDefault(), this.closeModal(this.currentModal));
    });
  }
  initialize() {
    this.modals && this.modals.forEach((modalElement) => {
      const modalId = modalElement.getAttribute("id"), btnsToggleModal = document.querySelectorAll(`.dcf-btn-toggle-modal[data-toggles-modal='${modalId}']`), btnCloseModal = modalElement.querySelector(".dcf-btn-close-modal"), modalWrapper = modalElement.querySelector(".dcf-modal-wrapper"), modalContent = modalElement.querySelector(".dcf-modal-content"), modalHeader = modalElement.querySelector(".dcf-modal-header");
      if (btnCloseModal === null)
        throw new Error(`Modal is missing close button: 
 ${modalElement.outerHTML}`);
      if (modalWrapper === null)
        throw new Error(`Modal is missing wrapper: 
 ${modalElement.outerHTML}`);
      if (modalContent === null)
        throw new Error(`Modal is missing content: 
 ${modalElement.outerHTML}`);
      if (modalHeader === null)
        throw new Error(`Modal is missing header: 
 ${modalElement.outerHTML}`);
      btnsToggleModal.forEach((button) => {
        let btnId = uuidv4();
        button.id !== void 0 && button.id !== "" && (btnId = button.id), button.setAttribute("id", btnId), button.removeAttribute("disabled"), this.btnToggleListen(button, modalId, btnId);
      });
      const modalHeadingId = `${modalId}-heading`, deliberateCloseOnly = typeof modalElement.dataset.deliberateCloseOnly < "u" && modalElement.dataset.deliberateCloseOnly.toLowerCase() !== "false";
      modalHeader.querySelectorAll("h1, h2, h3, h4, h5, h6")[0].setAttribute("id", modalHeadingId), this.appendToBody(modalElement), modalElement.removeAttribute("hidden"), modalElement.setAttribute("aria-labelledby", modalHeadingId), modalElement.setAttribute("aria-hidden", "true"), modalElement.setAttribute("role", "dialog"), modalElement.setAttribute("tabindex", "-1"), modalElement.classList.length === 1 && modalElement.classList.contains("dcf-modal") && modalElement.classList.add("dcf-bg-overlay-dark"), modalElement.classList.add(
        "dcf-fixed",
        "dcf-top-0",
        "dcf-left-0",
        "dcf-h-100%",
        "dcf-w-100%",
        "dcf-d-flex",
        "dcf-ai-center",
        "dcf-jc-center",
        "dcf-opacity-0",
        "dcf-pointer-events-none",
        "dcf-invisible"
      ), modalWrapper.setAttribute("role", "document"), modalWrapper.classList.length === 1 && modalWrapper.classList.contains("dcf-modal-wrapper") && modalWrapper.classList.add("dcf-relative", "dcf-h-auto", "dcf-overflow-y-auto"), modalHeader.classList.length === 1 && modalHeader.classList.contains("dcf-modal-header") && modalHeader.classList.add("dcf-wrapper", "dcf-pt-8", "dcf-sticky", "dcf-top-0"), btnCloseModal.classList.length === 1 && btnCloseModal.classList.contains("dcf-btn-close-modal") && btnCloseModal.classList.add("dcf-btn", "dcf-btn-tertiary", "dcf-absolute", "dcf-top-0", "dcf-right-0", "dcf-z-1"), modalContent.classList.length === 1 && modalContent.classList.contains("dcf-modal-content") && modalContent.classList.add("dcf-wrapper", "dcf-pb-8"), btnCloseModal.setAttribute("type", "button"), btnCloseModal.setAttribute("aria-label", "Close"), this.escListen(), deliberateCloseOnly || this.overlayListen(modalElement, modalWrapper), this.btnCloseListen(btnCloseModal, modalElement);
    });
  }
}
function toConsumableArray(arr) {
  if (Array.isArray(arr)) {
    const arr2 = Array(arr.length);
    for (let index = 0; index < arr.length; index++)
      arr2[index] = arr[index];
    return arr2;
  } else
    return Array.from(arr);
}
__name(toConsumableArray, "toConsumableArray");
let hasPassiveEvents = !1;
if (typeof window < "u") {
  const passiveTestOptions = {
    get passive() {
      hasPassiveEvents = !0;
    }
  };
  window.addEventListener("testPassive", null, passiveTestOptions), window.removeEventListener("testPassive", null, passiveTestOptions);
}
const isIosDevice = typeof window < "u" && window.navigator && window.navigator.platform && (/iP(ad|hone|od)/.test(window.navigator.platform) || window.navigator.platform === "MacIntel" && window.navigator.maxTouchPoints > 1);
let locks = [], documentListenerAdded = !1, initialClientY = -1, previousBodyOverflowSetting, previousBodyPosition, previousBodyPaddingRight;
function allowTouchMove(elem) {
  return locks.some(function(lock) {
    return !!(lock.options.allowTouchMove && lock.options.allowTouchMove(elem));
  });
}
__name(allowTouchMove, "allowTouchMove");
function preventDefault(rawEvent) {
  const event = rawEvent || window.event;
  return allowTouchMove(event.target) || event.touches.length > 1 ? !0 : (event.preventDefault && event.preventDefault(), !1);
}
__name(preventDefault, "preventDefault");
function setOverflowHidden(options) {
  if (previousBodyPaddingRight === void 0) {
    const reserveScrollBarGap = !!options && options.reserveScrollBarGap === !0, scrollBarGap = window.innerWidth - document.documentElement.clientWidth;
    if (reserveScrollBarGap && scrollBarGap > 0) {
      const computedBodyPaddingRight = parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right"), 10);
      previousBodyPaddingRight = document.body.style.paddingRight, document.body.style.paddingRight = `${computedBodyPaddingRight}${scrollBarGap}px`;
    }
  }
  previousBodyOverflowSetting === void 0 && (previousBodyOverflowSetting = document.body.style.overflow, document.body.style.overflow = "hidden");
}
__name(setOverflowHidden, "setOverflowHidden");
function restoreOverflowSetting() {
  previousBodyPaddingRight !== void 0 && (document.body.style.paddingRight = previousBodyPaddingRight, previousBodyPaddingRight = void 0), previousBodyOverflowSetting !== void 0 && (document.body.style.overflow = previousBodyOverflowSetting, previousBodyOverflowSetting = void 0);
}
__name(restoreOverflowSetting, "restoreOverflowSetting");
function setPositionFixed() {
  return window.requestAnimationFrame(function() {
    if (previousBodyPosition === void 0) {
      previousBodyPosition = {
        position: document.body.style.position,
        top: document.body.style.top,
        left: document.body.style.left
      };
      const windowVar = window, scrollY = windowVar.scrollY, scrollX = windowVar.scrollX, innerHeight = windowVar.innerHeight;
      document.body.style.position = "fixed", document.body.style.top = -scrollY, document.body.style.left = -scrollX, setTimeout(function() {
        return window.requestAnimationFrame(function() {
          const bottomBarHeight = innerHeight - window.innerHeight;
          bottomBarHeight && scrollY >= innerHeight && (document.body.style.top = -(scrollY + bottomBarHeight));
        });
      }, 300);
    }
  });
}
__name(setPositionFixed, "setPositionFixed");
function restorePositionSetting() {
  if (previousBodyPosition !== void 0) {
    const yVal = -parseInt(document.body.style.top, 10), xVal = -parseInt(document.body.style.left, 10);
    document.body.style.position = previousBodyPosition.position, document.body.style.top = previousBodyPosition.top, document.body.style.left = previousBodyPosition.left, window.scrollTo(xVal, yVal), previousBodyPosition = void 0;
  }
}
__name(restorePositionSetting, "restorePositionSetting");
function isTargetElementTotallyScrolled(targetElement) {
  return targetElement ? targetElement.scrollHeight - targetElement.scrollTop <= targetElement.clientHeight : !1;
}
__name(isTargetElementTotallyScrolled, "isTargetElementTotallyScrolled");
function handleScroll(event, targetElement) {
  const clientY = event.targetTouches[0].clientY - initialClientY;
  return allowTouchMove(event.target) ? !1 : targetElement && targetElement.scrollTop === 0 && clientY > 0 || isTargetElementTotallyScrolled(targetElement) && clientY < 0 ? preventDefault(event) : (event.stopPropagation(), !0);
}
__name(handleScroll, "handleScroll");
function disableBodyScroll(targetElement, options) {
  if (!targetElement) {
    console.error("disableBodyScroll unsuccessful - targetElement must be provided when calling disableBodyScroll on IOS devices.");
    return;
  }
  if (locks.some(function(lock2) {
    return lock2.targetElement === targetElement;
  }))
    return;
  const lock = {
    targetElement,
    options: options || {}
  };
  locks = [].concat(toConsumableArray(locks), [lock]), isIosDevice ? setPositionFixed() : setOverflowHidden(options), isIosDevice && (targetElement.ontouchstart = function(event) {
    event.targetTouches.length === 1 && (initialClientY = event.targetTouches[0].clientY);
  }, targetElement.ontouchmove = function(event) {
    event.targetTouches.length === 1 && handleScroll(event, targetElement);
  }, documentListenerAdded || (document.addEventListener("touchmove", preventDefault, hasPassiveEvents ? { passive: !1 } : void 0), documentListenerAdded = !0));
}
__name(disableBodyScroll, "disableBodyScroll");
function enableBodyScroll(targetElement) {
  if (!targetElement) {
    console.error("enableBodyScroll unsuccessful - targetElement must be provided when calling enableBodyScroll on IOS devices.");
    return;
  }
  locks = locks.filter(function(lock) {
    return lock.targetElement !== targetElement;
  }), isIosDevice && (targetElement.ontouchstart = null, targetElement.ontouchmove = null, documentListenerAdded && locks.length === 0 && (document.removeEventListener("touchmove", preventDefault, hasPassiveEvents ? { passive: !1 } : void 0), documentListenerAdded = !1)), isIosDevice ? restorePositionSetting() : restoreOverflowSetting();
}
__name(enableBodyScroll, "enableBodyScroll");
const modalCssUrl = "/wdn/templates_6.1/css/components-js/_modals.css?v=6.1.1";
loadStyleSheet(modalCssUrl).then(() => {
  const modals = document.querySelectorAll(".dcf-modal");
  new DCFModal(modals, { enableBodyScroll, disableBodyScroll }).initialize(), modals.forEach((modal) => {
    handleModalVideos(modal);
  });
});
function handleModalVideos(modal) {
  const videos = modal.getElementsByTagName("video");
  videos && videos.length > 0 && (document.addEventListener(`ModalOpenEvent_${modal.id}`, function() {
    Array.prototype.forEach.call(videos, (video) => {
      video.hasAttribute("data-autoplay") && video.play();
    });
  }, !1), document.addEventListener(`ModalCloseEvent_${modal.id}`, function() {
    Array.prototype.forEach.call(videos, (video) => {
      video.pause(), video.load();
    });
    const playBtns = modal.getElementsByClassName("mejs-overlay-play");
    playBtns && playBtns.length > 0 && Array.prototype.forEach.call(playBtns, (playBtn) => {
      playBtn.style.display === "none" && (playBtn.style.display = "block");
    });
  }, !1));
  const iframes = modal.getElementsByTagName("iframe");
  iframes && iframes.length > 0 && Array.prototype.forEach.call(iframes, (iframe) => {
    const source = iframe.getAttribute("src"), allowAttr = iframe.getAttribute("allow");
    if (allowAttr && allowAttr.includes("autoplay")) {
      if (!source.includes("mediahub.unl.edu"))
        try {
          const url = new URL(iframe.getAttribute("src"));
          url.searchParams.has("autoplay") && (url.searchParams.delete("autoplay"), iframe.src = url.toString());
        } catch (error) {
          console.error(error);
        }
      document.addEventListener(`ModalOpenEvent_${modal.id}`, function() {
        const currentSource = iframe.getAttribute("src");
        if (currentSource.includes("mediahub.unl.edu"))
          iframe.contentWindow.postMessage("mh-play-video", "https://mediahub.unl.edu");
        else
          try {
            const url = new URL(currentSource);
            url.searchParams.set("autoplay", "1");
            const newSource = url.toString();
            currentSource !== newSource && (iframe.src = newSource);
          } catch (error) {
            console.error(error), iframe.src = source;
          }
      }, !1), document.addEventListener(`ModalCloseEvent_${modal.id}`, function() {
        let currentSource = iframe.getAttribute("src");
        if (currentSource.includes("mediahub.unl.edu"))
          iframe.contentWindow.postMessage("mh-reset-video", "https://mediahub.unl.edu");
        else
          try {
            const url = new URL(currentSource);
            url.searchParams.has("autoplay") && (url.searchParams.delete("autoplay"), currentSource = url.toString()), iframe.src = currentSource;
          } catch (error) {
            console.error(error), iframe.src = source;
          }
      }, !1);
    } else
      document.addEventListener(`ModalCloseEvent_${modal.id}`, function() {
        source.includes("mediahub.unl.edu") ? iframe.contentWindow.postMessage("mh-pause-video", "https://mediahub.unl.edu") : iframe.src = source;
      }, !1);
  });
}
__name(handleModalVideos, "handleModalVideos");
//# sourceMappingURL=modal.js.map
