let tocIframeSelector = "#toc iframe";
$("a#tabsSelector").click(function() {
  // Hide TOC when tabSelect is clicked
  if ($(tocIframeSelector).css("display") != "none")
    hideTOCbyZeroHeight($("a#topicSelector"));
  // Do the job
  $("#tabs").slideToggle("fast");
  if ($(this).hasClass("bgarrow_down_white"))
    $(this).addClass("bgarrow_up_white").removeClass("bgarrow_down_white");
  else 
    $(this).addClass("bgarrow_down_white").removeClass("bgarrow_up_white"); 
});

let firstLoad = true;
let tocFrameHeight = 0;
let tocHidden = true;
function hideTOCbyZeroHeight() {
  if (!tocHidden) {
    tocFrameHeight = $(tocIframeSelector).height();
    $(tocIframeSelector).animate({ height: 0 }, 500, function() {
      $(this).parent().css("height", "0");
    });
    tocHidden = true;
  }
  $(tocIframeSelector).css("margin-bottom", "0");
  $("a#topicSelector").addClass("bgarrow_down_white").removeClass("bgarrow_up_white");
}
function showTOCbyDefaultHeight() {
  $(tocIframeSelector).parent().css("height", "auto");
  $(tocIframeSelector).show("fast");
  $(tocIframeSelector).animate({ height: tocFrameHeight }, 500);
  $(tocIframeSelector).css("margin-bottom", "3em");
  tocHidden = false;
}
$("a#topicSelector").click(function() {
  // Hide tabs when topicSelect is clicked
  $("#tabs").hide("fast");
  $("a#tabsSelector").addClass("bgarrow_down_white").removeClass("bgarrow_up_white");
  // Do the job
  if ($(this).hasClass("bgarrow_down_white")) {
    if (firstLoad) {
      if (window.chrome)
        $(tocIframeSelector).css("display", "inline");
      $(tocIframeSelector).on("load", function(){
        $(tocIframeSelector).resize();
      });
      $(tocIframeSelector).show("fast", function() {
        $(this).attr( 'src', function ( i, val ) { return val; });
        $(tocIframeSelector).css("margin-bottom", "3em");
      });
      tocHidden = false;
    } else
      showTOCbyDefaultHeight();
    firstLoad = false;
    $(this).addClass("bgarrow_up_white").removeClass("bgarrow_down_white");
  } else
    hideTOCbyZeroHeight();
});

$("#desktop_view a").click(function(e) {
  $("body").addClass("desktop_mode");
  removeMaxWidthRules();
  $("meta[name='viewport']").attr("content", "width=1280px, initial-scale=1, maximum-scale=1");
  e.preventDefault();
});
function viewDesktopSite() { return false; }
function removeMaxWidthRules() { for(let i=0;i<document.styleSheets.length;i++){try{let ss=document.styleSheets[i];for(let j=0;j<ss.cssRules.length;j++){let rule=ss.cssRules[j];if(rule.media&&rule.media.mediaText.includes("max-width")){for(let k=0;k<rule.cssRules.length;k++){ss.deleteRule(j);}}}}catch(e){}} }

// Header animation
$(document).ready(function () {
  let previousScroll = 0;
  let startScroll = 800; // from which position from top
  let minHeight = 400; // minimum height of screen needed
  let flickTimeout = 200;
  let origMarginTop = $('main').css("padding-top");
  $(window).on('scroll', function () {
    clearTimeout();
    let headerHeight = $('header').outerHeight();
    let topHeight = $('#top:visible').outerHeight() ?? 0;
    let acceptableHeight = 0;
    let windowHeight = $(window).height();
    if (topHeight > 0)
      acceptableHeight = headerHeight + topHeight;
    let currentScroll = $(this).scrollTop();
    let canFixHeader = currentScroll > acceptableHeight && currentScroll < previousScroll && windowHeight >= minHeight;
    if (canFixHeader) {
      if (currentScroll > startScroll && !$('header').hasClass("fixed")) {
        setTimeout(function() {
          let newMarginPx = parseInt(origMarginTop) + headerHeight;
          $('header').addClass('fixed');
          $('main').css('padding-top', newMarginPx);
        }, flickTimeout);
      }
    } else {
      if ($('header').hasClass("fixed") || currentScroll == 0)
        setTimeout(function() {
          $('header').removeClass('fixed');
          $('main').css('padding-top', origMarginTop);
        }, flickTimeout);
    }
    previousScroll = currentScroll;
  });
});

// Enable responsive search
$('#search_toolbar a').on('click', function(e) {
  if ($('#search_toolbar').hasClass("shown")) return;
  e.preventDefault();
  $('html, body').animate({ scrollTop: 0 }, 200, function() {
  if ($('#top').css("display") == "none")
    $('#top').slideToggle(500, function() {
      if ($(this).is(':visible'))
        $(this).css('display', 'flex');
    });
  });
});

// Expanders in content
//  a.dropdown-toggle
$("#topicText").on("click", "a.dropdown-toggle", function(e) {
  var state = $( this ).attr("data-state");
  if (state == "0") state = "1"; else state = "0";
  $( this ).attr("data-state", state);
  var element = $( this ).attr("id").replace("_LINK", "");
  var elementIcon = $( this ).attr("id").replace("_LINK", "_ICON");
  $( "#" + element ).slideToggle("fast");
  $( "#" + elementIcon ).attr("src", $( this ).attr("data-src" + state));
  $( "#" + elementIcon ).attr("alt", "state" + state);
  adjustFooterPosition();
});
//  img.dropdown-toggle-icon
$("#topicText").on("click", "img.dropdown-toggle-icon", function(e) {
  var imgSrc = "";
  var state = 0;
  var element = $( this ).attr("id").replace("_ICON", "");
  var elementLink = $( this ).attr("id").replace("_ICON", "_LINK");
  var currentState = $( "#" + elementLink ).attr("data-state");
  if (currentState == 0) {
    imgSrc = $( "#" + elementLink ).attr("data-src1");
    state = 1;
  } else {
    imgSrc = $( "#" + elementLink ).attr("data-src0");
    state = 0;
  }
  $( this ).attr("alt", "state" + state);
  $( this ).attr("src", imgSrc);
  $( "#" + element ).slideToggle("fast");
  $( "#" + elementLink ).attr("data-state", state);
  adjustFooterPosition();
});

$(document).on('keyup',function(event) {
  if (event.keyCode == 27) { // ESC handler
    $("#languagemenu").hide("fast");
    $("#versionSelector").hide("fast");
    if ($("#lightbox")) hideLightBox();
  }
});

// If clicked on lightbox, delete it
function hideLightBox() {
  if ($("#lightbox"))
    $("#lightbox").animate({opacity: 0}, 200, function() {$(this).remove();});
  $("#offlineSearch").css("height", "6ex");
}
$("body").on("click", "#lightbox", function(e) { hideLightBox(); });

// Close lngselectbox and verselectbox if clicked with mouse outside
let mouse_is_inside_top = false;
let mouse_is_inside_header = false;
$('#top').hover(function(){
  mouse_is_inside_top=true;
}, function(){
  mouse_is_inside_top=false; 
});
$('header').hover(function(){
  mouse_is_inside_header=true;
}, function(){ 
  mouse_is_inside_header=false;
});
$("body").mouseup(function(){
  if(!mouse_is_inside_header) $("#languagemenu").hide("fast");
  if(!mouse_is_inside_top) $("#versionSelector").hide("fast"); 
});
$(document).on('keyup',function(event) {
  if (event.keyCode == 27) { // ESC handler
    $("#languagemenu").hide("fast");
    $("#versionSelector").hide("fast");
    $("#pdfDownloadOptions").hide("fast");
  }
});

// DivScroll and mobileTable for tables
window.setMobileTable = function(selector) {
  const tableEl = selector;
  $(tableEl).addClass("Table_small_mobile");
  const thEls = tableEl.querySelectorAll("thead > tr > th");
  const tdLabels = Array.from(thEls).map(el => el.innerText);
  tableEl.querySelectorAll("tbody > tr").forEach( tr => {
    Array.from(tr.children).forEach( 
      (td, ndx) =>  $(td).each(function() {
        $(this).attr("label", tdLabels[ndx]);
        if ($(this).children().length >= 2)
          $(this).wrapInner("<div class='flex-mobile-td'></div>");
      })
    );
  });
}
function adjustTablesForMobile() {
  // Scrolling big tables
  if ($("#topicText table.Table_big"))
    $("#topicText table.Table_big").wrap("<div class='mobileTableBig'></div>"); 
  if ($("#topicText table.Table_code"))
    $("#topicText table.Table_code").wrap("<div class='mobileTableBig'></div>");
  // Add scroll to top for each big table
  $('.mobileTableBig').each(function (index) {
    let $thisMobileTable = $(this);
    if ($thisMobileTable.height() > 400) {
      let $fakeScrollInner = $('<div>').css({
        width: $thisMobileTable[0].scrollWidth + 'px',
        height: '1px'
      });
      let uniqueScrollClass = 'scroll-top-' + index;
      $thisMobileTable.before('<div class="scroll-top '+uniqueScrollClass+'"></div>');
      $("."+uniqueScrollClass).append($fakeScrollInner);
      $("."+uniqueScrollClass).on('scroll', function () {
        $thisMobileTable.scrollLeft($("."+uniqueScrollClass).scrollLeft());
      });
      $thisMobileTable.on('scroll', function () {
        $("."+uniqueScrollClass).scrollLeft($thisMobileTable.scrollLeft());
      });
    }
  });
  // Default tables
  if ($("#topicText table.Table_small")) {
    $("#topicText table.Table_small").each(function() {
      setMobileTable(this);
    });
    $('#topicText table.Table_small').each(function() {
      if ($(this).height() > 800) {
        $(this).addClass('longTable');
      }
    });
  }
}
adjustTablesForMobile();

// Sorting of tables
function sortTables() {
  $('#topicText table.Table_small th, #topicText table.Table_big th').hover(function(e){
    if ($(this).parents('table').find("tr").length < 12)
      return;
    $(this).css("cursor", "pointer");
  });
  $('#topicText table.Table_small th, #topicText table.Table_big th').click(function(e){
    if ($(this).parents('table').find("tr").length < 12)
      return;
    if (!$(this).has('span.sort_arrow').length)
      $(this).find("span.f_Head_row").append('<span class="sort_arrow"></span>');
    let table = $(this).parents('table').eq(0);
    let rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
    this.asc = !this.asc;
    if (!this.asc){rows = rows.reverse()}
    rows.forEach(row => table.append(row));
    setTableThIcon(this, this.asc);
  });
}
function comparer(index) {
  return function(a, b) {
    let valA = getCellValue(a, index), valB = getCellValue(b, index)
    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
  }
}
function getCellValue(row, index) {
  let tdVal = $(row).children('td').eq(index);
  if (tdVal.attr("sortValue"))
    return tdVal.attr("sortValue");
  else
    return tdVal.text();
}
function setTableThIcon(element, inverse) {
  let iconSpan = $(element).find('span.sort_arrow');
  if (inverse)
    $(iconSpan).removeClass().addClass('sort-column-asc').addClass('sort_arrow').html(" &#8593; "); // arrow up
  else
    $(iconSpan).removeClass().addClass('sort-column-desc').addClass('sort_arrow').html(" &#8595; "); // arrow down 
  $(element).siblings().find('span.sort_arrow').each(function (i, obj) {
    $(obj).removeClass().addClass('sort_arrow').html("");
  });
}
sortTables();

function adjustImagesForMobile() {
  $('#topicText img').each(function() {
    if (($(this).attr("width") > 0 && $(this).attr("width") <= 48) || $(this).width() <= 48)
      $(this).addClass('icon');
  });
}
adjustImagesForMobile();

function adjustFooterPosition() {
  let currentBodyHeight = $("body").height();
  if ($("footer").css("position") == "fixed")
    currentBodyHeight += $("footer").height();
  if (currentBodyHeight < $(window).height()) {
    $("footer")
      .css("position", "fixed")
      .css("width", "100%")
      .css("bottom", "0px");
  } else {
    $("footer")
      .css("position", "static")
      .css("width", "auto")
      .css("bottom", "initial");
  }
}
$( window ).resize(function() { adjustFooterPosition(); });
$( window ).scroll(function() { adjustFooterPosition(); });
$( window ).ready(function()  { adjustFooterPosition(); });
adjustFooterPosition();
setTimeout(function(){ adjustFooterPosition(); }, 2500);

// Offline search highlight
function findGetParameter(t){let e=null;for(const r of location.search.substring(1).split("&")){const[n,o]=r.split("=");if(n===t){e=decodeURIComponent(o.replace(/\+/g," "));break}}return e}
let zoomH = findGetParameter("zoom_highlightsub");
if (zoomH && zoomH.length >= 3) {
  $.getScript( "js/jquery.mark.min.js" ).done(function( script, textStatus ) { $("#topicText").mark(zoomH); });
}

// Catch and animate specific anchors like "topic.html#anchor"
$("#topicText").on("click", "a[href*=\\#]", function(e) {
  let filename = location.pathname.substring(location.pathname.lastIndexOf('/')+1);
  let queryStringPositon = location.href.indexOf("?");
  if (queryStringPositon > -1) {
    filename = location.href.substring(queryStringPositon+1);
    filename = filename.substr(0, filename.lastIndexOf(".")) + ".html";
  }
  let dest = $(this).attr('href');
  let destTopicName = dest.substring(0, dest.lastIndexOf('#'));
  let destAnchor = dest.substring(dest.lastIndexOf('#'));
  if (filename != destTopicName)
    return;
  if ($(destAnchor)) {
    e.preventDefault();
    $('html,body').animate({ scrollTop: $(destAnchor).offset().top - 30 }, 'slow');
  }
});

// RTL floating images
function adjustRTLFloatImages() {
  $("html[dir='rtl'] #topicText img").each(function() {
    if ($(this).css("float") == "left") {
      $(this).css("float", "right");
      if ($(this).css("margin-right") != "0px") {
        $(this).css("margin-left", $(this).css("margin-right"));
        $(this).css("margin-right", "0");
      }
      }
  });
}
adjustRTLFloatImages();

// External links - icon addition
function extLinks() {
  // exclude RTL
  if ($("html").attr("dir") == "rtl");
  else { 
    var extLinkValid = true;
    $("#topicText a.weblink").each(function() {
      extLinkValid = true;
      // except current host
      if ($(this).attr("href").includes(location.hostname))
        extLinkValid = false;
      // except relative links
      if ($(this).attr("href").includes("http://") || $(this).attr("href").includes("https://"));
      else
        extLinkValid = false;
      if (extLinkValid)
        $(this).addClass('extLinkImg');
    });
  }
}
extLinks();

// Copy Table_Code contents to clipboard and replace 
function copyCodeToClipboard(copyIcon, tdElement) {
  const textToCopy = tdElement.text().replace(/\u00A0/g, ' ');
  navigator.clipboard.writeText(textToCopy)
    .then(() => {
      fadeCopyIcon(copyIcon);
    });
}
function fadeCopyIcon(copyIcon) {
  $(copyIcon).addClass("copied");
  $(copyIcon).addClass("s-fading");
  $(copyIcon).css("display", "inline-block");
  $(copyIcon).fadeOut(2000, function() {
    $(copyIcon).removeClass("copied");
    $(copyIcon).removeClass("s-fading");
    if ($(copyIcon).is(':hover'))
      $(copyIcon).fadeIn(200);
    else
      $(copyIcon).css("display", "none");
  });
}
const copyCodeStr = document.currentScript.getAttribute("data-str_copy_clipboard").replace(/<[^>]*>/g,'') ?? '';
function copyCode() {
  $("#topicText td.Table_code").each(function() {
    $(this).css("position", "relative");
    $(this).find("p").css("padding-right", "20px");
    $(this).prepend('<a href="javascript:copyThisCode()" class="codeURL"></a>');
    $(this).find("a.codeURL").attr("title", copyCodeStr); 
  });
  $("#topicText td.Table_code").hover(
    function() {
      $(this).find("a.codeURL").css("display", "inline-block");
    }, function() {
      if (!$(this).find("a.codeURL").hasClass("s-fading"))
        $(this).find("a.codeURL").css("display", "none");
    });
  $("#topicText").on("click", "a.codeURL", function(e) {
    copyCodeToClipboard($(this), $(this).parent());
    e.preventDefault();
    return false;
  });
}
function copyThisCode() {
  return false;
}
copyCode();

// PDF toolbar
$("a#pdfDownloadIcon").on("click", function(e) {
  e.preventDefault();
  $("#pdfDownloadOptions").slideToggle("500");
  let pd_queryStringPositon = location.href.indexOf("?");
  if (pd_queryStringPositon > -1) {
    let pd_topicForceToLoad = location.href.substring(pd_queryStringPositon+1);
    pd_topicForceToLoad = pd_topicForceToLoad.substring(0, pd_topicForceToLoad.lastIndexOf(".")) + ".html";
    if (pd_topicForceToLoad.match("^[a-zA-Z0-9._-]+\.html$"))
      $("#pdfDownloadOptions a:first").attr("href", $("#pdfDownloadOptions a:first").attr("href").replace(/topic=[a-zA-Z0-9._-]+/, "topic="+pd_topicForceToLoad));
  }
  $("#pdfDownloadOptions a:first").attr("href", $("#pdfDownloadOptions a:first").attr("href").replace(".html", ""));
  hideTopicControlBox($("#pdfDownloadOptions"));
});
function downloadPDFtoolbar(e) {return true;}

// Share current URL
$("a#shareButton").on("click", function(e) {
  e.preventDefault();
  $("#shareButtons").slideToggle("500");
  hideTopicControlBox($("#shareButtons"));
});
$("a#shareButtonUrlCopy").on("click", function(e) {
  e.preventDefault();
  navigator.clipboard.writeText(get_sh_currentLocation())
    .then(() => {
      fadeCopyIcon($(this).find("span"));
    });
});
$("a#shareButtonUrlCopy").hover(
  function() {
    $(this).find("span.codeURL").css("display", "inline-block");
  }, function() {
  if (!$(this).find("span.codeURL").hasClass("s-fading"))
    $(this).find("span.codeURL").css("display", "none");
});
$("a#shareButtonEmail").on("click", function(e) {
  e.preventDefault();
  let mailtoLink = "mailto:?subject=" + $(this).text() + "&body=" + get_sh_currentLocation();
  location.href = mailtoLink;
});

function get_sh_currentLocation() {
  let sh_currentLocation = location.pathname;
  let sh_queryStringPositon = location.href.indexOf("?");
  if (sh_queryStringPositon > -1) {
    let sh_topicForceToLoad = location.href.substring(sh_queryStringPositon+1);
    sh_topicForceToLoad = sh_topicForceToLoad.substring(0, sh_topicForceToLoad.lastIndexOf(".")) + ".html";
    if (sh_topicForceToLoad.match("^[a-zA-Z0-9._-]+\.html$"))
      sh_currentLocation = location.pathname.substring(0, location.pathname.lastIndexOf("/")) + "/" + sh_topicForceToLoad;
  }
  sh_currentLocation = "https://" + location.hostname + sh_currentLocation;
  return sh_currentLocation;
}
let topicControlBoxTimeout;
function hideTopicControlBox(elemToHide) {
  clearTimeout(topicControlBoxTimeout);
  topicControlBoxTimeout = setTimeout(function() {
    elemToHide.hide("fast");
  }, 10000);
}
function shareUrl(e) {return true;}
function shareUrlCopy(e) {return true;}
function shareUrlEmail(e) {return true;}

// Event resize
$( window ).resize(function() {
  adjustFooterPosition();
});

// Handling back/forward button
window.onpopstate = function(event) {
  window.location = document.location;
};

// Dummy
function HMTrackTopiclink(e) {return true;}
