const $iframe = $("#toc iframe", parent.document);
if ($iframe.length > 0 && typeof $iframe.iframeResize === "function") {
  $iframe.iframeResize({ license: '1jy4dww5qzv-s54r73oxcn-v59f4kfgfz' });
}

const $html = $("html", document);
const $tocLinks = $("#toc a", document);
const isDarkMode = $html.hasClass("dark");
const tocDirection = $html.attr("dir");

let footerAdjustTimeout = null;
function adjustFooterPositionDebounced() {
  if (footerAdjustTimeout) clearTimeout(footerAdjustTimeout);
  footerAdjustTimeout = setTimeout(function() {
    if (typeof parent.adjustFooterPosition === "function")
      parent.adjustFooterPosition();
  }, 80);
}

function toggleList($list, duration) {
  if (!$list || !$list.length) return;
  if (duration === 0) {
    $list.show();
    adjustFooterPositionDebounced();
    return;
  }
  $list.stop(true, true).slideToggle(duration, function() {
    adjustFooterPositionDebounced();
  });
}

let tocChildsBGcolor = "#f4f5f4";
let tocCurrentBGcolor = "#00a3d9";
let tocCurrentBGcolorBorder = "#c4c7c4";
let tocCurrentItemColor = "#ffffff";
let tocBGcolor = "#fff";
let tocBorderColor = "#424d56";
let tocItemColor = "#3a3a3a";
if (isDarkMode) {
  tocChildsBGcolor = "#2a2a2a";
  tocCurrentBGcolor = "#0081c2";
  tocCurrentBGcolorBorder = "#84919a";
  tocCurrentItemColor = "#fff";
  tocBGcolor = "#121212";
  tocBorderColor = "#a7a7a7";
  tocItemColor = "#f0f0f0";
}


function setBGandExpand(currentElement, initialLoad, event) {
  const slideTimeout = initialLoad ? 0 : 400;
  const currentLi = currentElement.parent("li");
  let rootLi = currentLi;
  let parentElementA = currentLi.find("a");
  let parentElementU = currentLi.children("ul").first();

  currentLi.parents("li").each(function() {
    rootLi = $(this);
    const $ancestorAnchor = $(this).children("a").first();
    const $ancestorList = $(this).children("ul").first();
    if ($ancestorList.length && $ancestorList.css("display") == "none")
      toggleList($ancestorList, slideTimeout);
    if ($ancestorAnchor.hasClass(arrowDown))
      $ancestorAnchor.addClass(arrowUp).removeClass(arrowDown);
  });

  if (rootLi && rootLi.length)
    parentElementA = rootLi.find("a");
  // Arrow clicked or chapter w/o text?
  let arrowClicked = false;
  let arrowSize = 28;
  if (window.innerWidth > 480) arrowSize = 42;
  const href = currentElement.attr("href") || "";
  const currentOffset = currentElement.offset() || { left: 0 };
  const currentLeft = currentOffset.left;
  const currentWidth = currentElement.outerWidth() || 0;
  if (event && tocDirection == "rtl" && currentLeft + arrowSize > event.pageX)
    arrowClicked = true;
  if (event && tocDirection != "rtl" && currentLeft + currentWidth - arrowSize < event.pageX)
    arrowClicked = true;
  if (href.includes("void(0)"))
    arrowClicked = true;
  // Background
  parentElementA.css("background-color", tocChildsBGcolor);
  if (currentElement.next("ul").length || !currentElement.hasClass("heading1"))
    parentElementA.css("border-color", tocCurrentBGcolorBorder);
  if (!arrowClicked) {
    currentElement.css("background-color", tocCurrentBGcolor);
    currentElement.css("color", tocCurrentItemColor);
    currentElement.addClass("selected");
  }
  // When clicked, set up arrow
  if (currentElement.hasClass(arrowDown))
    currentElement.addClass(arrowUp).removeClass(arrowDown);
  // When clicked or topic is active, set up arrow for the grandparent topic
  if (parentElementA.first().hasClass(arrowDown))
    parentElementA.first().addClass(arrowUp).removeClass(arrowDown);
  if (!arrowClicked && parentElementU.css("display") == "none") {
    toggleList(parentElementU, slideTimeout);
    // Change arrow for active subtree
    currentElement.addClass(arrowUp).removeClass(arrowDown);
    // Gray background for current+child topics
    currentElement.css("background-color", tocChildsBGcolor);
  }
  // Expand childs when clicked on arrow
  if (arrowClicked && parentElementU.css("display") == "none") {
    toggleList(parentElementU, slideTimeout);
    currentElement.addClass(arrowUp).removeClass(arrowDown);
    reload = false; // do not reload topic
    currentElement.css("background-color", tocChildsBGcolor);
  }
  // Hide when 2 times clicked on the same arrow on same topic
  else if (arrowClicked && parentElementU.css("display") == "block") {
    toggleList(parentElementU, 1000);
    currentElement.addClass(arrowDown).removeClass(arrowUp);
    reload = false;
  }
  if (arrowClicked && latestCurrentElement) {
    latestCurrentElement.css("background-color", tocCurrentBGcolor);
    latestCurrentElement.css("color", tocCurrentItemColor);
    latestCurrentElement.addClass("selected");
  }
  topicName = href;
  if (reload) {
    lastTopicName = topicName;
    latestCurrentElement = currentElement;
  }
}

// Always target parent frame
$tocLinks.attr("target", "_top");
// Predefined global variables
let topicToReload = "index.html";
let level1Topic = true; 
let validTopicName = false;
// Arrow color
let arrowUp = "bgarrow_up";     let arrowUpWhite = "bgarrow_up_white"; 
let arrowDown = "bgarrow_down"; let arrowDownWhite = "bgarrow_down_white";
if (isDarkMode) {
  arrowUp = "bgarrow_up_white";  
  arrowDown = "bgarrow_down_white";
}

// Always hidden, expanded only by click on a specific subtree
$("#toc ul", document).css("display", "none");

// Add arrows to topics with <ul>
$("#toc span", document).filter("[ondblclick]").parent().addClass(arrowDown);

// Set initial topic name based on current parent URL
let lastTopicName = "";
let urlParent = parent.location;
let topicName = urlParent.pathname.substring(urlParent.pathname.lastIndexOf('/')+1);
let queryStringPosition = urlParent.href.indexOf("?");
if (urlParent.href.includes("?")) {
  let topicForceToLoad = urlParent.href.substring(queryStringPosition+1);
  if (/^[a-zA-Z0-9._-]+\.html$/.test(topicForceToLoad))
    topicName = topicForceToLoad;
}
if (topicName.length < 5) topicName = "index.html"; // Default is index.html (documentROOT)

let reload = false;
let latestCurrentElement = null;
$tocLinks.first().css("border-top", "1px solid " + tocBorderColor);
$tocLinks.each(function() {
  if ($( this ).attr("href") == topicName)
    setBGandExpand($( this ), true);
});

function resetTocStyles() {
  $tocLinks.css({
    "background-color": tocBGcolor,
    "border-color": tocBorderColor,
    "color": tocItemColor
  }).removeClass("selected");
}


if (history.pushState) {
  function hmLoadTopic(arr) {
    const fadeTimeout = 300;
    $('h1.p_Heading1', parent.document).html($(arr['hmHeader']).contents()).stop(true, true).hide().fadeIn(fadeTimeout);
    $('#topicText', parent.document).stop(true, true).hide().html(arr['hmBody']).fadeIn(fadeTimeout, function() {
      adjustFooterPositionDebounced();
      parent.adjustTablesForMobile();
      parent.sortTables();
      parent.adjustImagesForMobile();
      parent.adjustRTLFloatImages();
      parent.extLinks();
      parent.copyCode();
      $('#topicControls .hoverBox', parent.document).hide("fast");
      
      if (typeof parent.anchorHeading === 'function') { parent.anchorHeading(); }
      
      
      
      
      if (typeof parent.initIframeResizer === 'function') { parent.initIframeResizer(); }
      
      
    });
    if (arr['hmPrevLink'].length > 5) {
      $('a.previous', parent.document).attr("href", arr['hmPrevLink']);
      $('a.previous', parent.document).removeClass("hidden");
    } else 
      $('a.previous', parent.document).addClass("hidden");
    if (arr['hmNextLink'].length > 5) {
      $('a.next', parent.document).attr("href", arr['hmNextLink']);
      $('a.next', parent.document).removeClass("hidden");
    } else
      $('a.next', parent.document).addClass("hidden");
    if ($("#breadcrumbs")) {
      let finalBreadcrumb = arr['hmTitle'];
      if (arr['hmBreadCrumbs'].length > 0)
        finalBreadcrumb = arr['hmBreadCrumbs'] + " &gt; " + finalBreadcrumb;
      $('#breadcrumbs span', parent.document).stop(true, true).hide().html(finalBreadcrumb).fadeIn(fadeTimeout);
    }
  }
  parent.hmLoadTopic = hmLoadTopic;
  $tocLinks.click(function(event) {
    const $clicked = $(this);
    const clickedHref = $clicked.attr("href") || "";
    // Reset background
    resetTocStyles();
    // Set global variables to current clicked topic
    topicToReload = clickedHref.substring(0, clickedHref.lastIndexOf("."));
    level1Topic = $clicked.hasClass("heading1");
    // Detect layout
    let ifMobileLayout = $("#main", parent.document).css("flex-direction") == "column";
    // Change TOC title
    if (ifMobileLayout)
      $("a#topicSelector", parent.document).text($clicked.text()); 
    // Hide lngselectbar and verselectbar if opened
    $("#languagemenu", parent.document).hide("fast");
    $("#versionSelector", parent.document).hide("fast");
    // If the same topic is clicked, do not reload
    reload = false;
    if (lastTopicName != clickedHref)
      reload = true;
    // Set background and expand particular topics + detect if still able to reload
    setBGandExpand($clicked, false, event);
    // New page
    let newurl = parent.location.protocol + "//" + parent.location.host + parent.location.pathname + '?' + clickedHref;
    let newurlGA = parent.location.pathname.substring(0, parent.location.pathname.lastIndexOf('/')) + '/' + clickedHref;
    let newtitle = $clicked.find("span").text() + " | ESET PROTECT On-Prem | ESET Online Help";
    validTopicName = /^[a-zA-Z0-9._-]+\.html$/.test(clickedHref);
    parent.document.title = newtitle;
    // Load new page and if failed, reload whole page
    if (reload && validTopicName) {
      let reloadHrefEl = $clicked;
      let reloadYmdh = new Date().toISOString().slice(0, 13).replace(/[-T]/g, '');
      // Append loading cursor if page load time is too high
      let reloadTimeout = setTimeout(function() {
        reloadHrefEl.css("cursor", "wait");
      }, 500);
      $.ajax({
        url: "jstopics/" + clickedHref.replace("html", "js") + "?v=" + reloadYmdh,
        dataType: "script",
        cache: true,
        success: function() {
          clearTimeout(reloadTimeout);
          setTimeout(function() {
            $(reloadHrefEl).css("cursor", "pointer");
          }, 250);
        },
        error: function(jqxhr, settings, exception) {
          parent.location.href = newurlGA;
        }
      });
      // If a valid page, push new history
      parent.history.pushState({path:newurl, title:newtitle}, newtitle, newurl);
    }
    // Scroll top if you are below topic heading
    let Theading1 = $("#content h1:first", parent.document);
    let scrollTopOffset = 0;
    if (reload) setTimeout(function () {
      let tocFrameSelector = $("#toc iframe", parent.document); 
      let $parentScroll = $('html, body', parent.document);
      // "Hide" TOC if mobile layout
      if (ifMobileLayout) {
        parent.tocFrameHeight = tocFrameSelector.height();
        parent.hideTOCbyZeroHeight();
        // Scroll to Header1 for mobile skin
        $parentScroll.stop(true, true).animate({ scrollTop: Theading1.offset().top - tocFrameSelector.height() - 20 }, 500);
      } else {
        if (Theading1.offset().top + scrollTopOffset < $(parent.document).scrollTop())
          $parentScroll.stop(true, true).animate({ scrollTop: Theading1.offset().top - 5 }, 500);
      }
    }, 400);

    // Disable local TOC hyperlinks only
    if (!(clickedHref.startsWith("http://") || clickedHref.startsWith("https://")))
      event.preventDefault();
  });
}
