<script>
  const urlParams = new URLSearchParams(window.location.search);
  const $QUERY = (urlParams.get('query') || '').trim().toLowerCase();

  function isQueryInElement(element) {
    const text = element.text().toLowerCase();
    return ($QUERY && text.indexOf($QUERY)) !== -1;
  }

  function isQueryInTitle() {
    return isQueryInElement($svjq('h1'));
  }

  function markElement(selector) {
    const element = $svjq(selector);
    $svjq(element).unmark({
      done: function() {
        $svjq(element).mark($QUERY);
      }
    });
    return element;
  }

  function openCollapsible(collapsibleElement) {
    const id = collapsibleElement.attr('id');
    envision.collapse(`#${id}`).then(function(c) {
      c[0].show();
    });
  }

  function scrollToElement(element) {
    const id = element.attr('id');
    if (id) window.location.hash = id;
  }

 function getCollapsiblesToOpen() {
    const collapsiblesToOpen = [];
    $svjq('.env-collapse').each(function() {
      const element = $svjq(this);
      if (isQueryInElement(element)) {
        collapsiblesToOpen.push(element);
      }
    });
    return collapsiblesToOpen;
  }

  window.svDocReady(function ready() {
    markElement('.pagecontent');
    var showCollapse = $metadata;
    if (showCollapse) {
      if (!isQueryInTitle()) {
        const collapsiblesToOpen = getCollapsiblesToOpen();
        collapsiblesToOpen.forEach(openCollapsible);
        if (collapsiblesToOpen.length > 0) {
          scrollToElement(collapsiblesToOpen[0]);
        }
      }
    }
  });
</script>
