let selected = null;

window.addEventListener("load", (event) => {
  document.querySelectorAll("a:not(:last-child)").forEach(function(el) {
      el.before(document.createElement("span"));
  });

  document.getElementById("menu").addEventListener("click", function(e) {
      if(e.target.nodeName == "A") {
          // Remove current active element
          if(selected) {
              selected.classList.remove("selected");
          }

          // Set new active element
          e.target.classList.add("selected");

          if(e.target.previousElementSibling) {
              e.target.previousElementSibling.classList.add("open");
          }

          // Set active to variable
          selected = e.target;
      }

      // Fold/unfold
      if(e.target.nodeName == "SPAN") {
          e.target.classList.toggle("open");
      }
  });
});

window.addEventListener("message", (event) => {
  let el = document.querySelector("a[href*=" + event.data.id + "]");

  if(!el) return;

  // Remove current active element
  if(selected) {
    selected.classList.remove("selected");
  }

  // Set new active element
  el.classList.add('selected');

  // Set active to variable
  selected = el;

  do {
      if(el.firstChild.nodeName == "SPAN" && !el.firstChild.classList.contains('open')) {
          el.firstChild.classList.add('open');
      }
  } while((el = el.parentNode.closest('li')) != null);
});
