// Copyright 2015 Google Inc. All Rights Reserved.

// Simple tree menu. The active branch and its immediate children are visible.
// Requires a companion _menu_.css and _menu_.html generated by
// `gcloud meta generate-help-docs --html-dir=DIRECTORY`.

var menu_hover_delay = 500;
var selected = 1;

function menu_navigate(id, click) {

  var path = id.split("_");
  if (click || selected > path.length) {
    selected = path.length;
  }

  // Mark all visible elements hidden.
  var visible = document.getElementsByClassName("visible");
  // Traverse in reverse order because visible changes each iteration.
  for (var i = visible.length - 1; i >= 0; --i) {
    visible[i].className = "hidden";
  }

  // Mark elements on path visible.
  var id = "";
  var next = path[0];
  var element = undefined;
  for (var i = 1; i <= path.length; ++i) {
    id = next;
    if (i < path.length) {
      next += "_" + path[i];
    } else {
      next = '__';
    }
    element = document.getElementById(id);
    element.className = "visible";
    if (i >= selected) {
      group = element.getElementsByTagName("ul");
      if (group.length) {
        var children = group[0];
        var child = children.getElementsByTagName("li");
        for (var j = 0; j < child.length; ++j) {
          if (child[j].parentNode == children) {
            child[j].className = "visible";
          }
          if (child[j].id == next) {
            break;
          }
        }
      }
    }
  }
}

function menu_select(id) {
  // Reset the navigation breadcrumbs.
  menu_navigate(id, true);
  // Load the man page in the main section.
  parent.main.location.href = id + ".html";
}

function disable_propagation(event) {
  if (event.stopPropagation) {
    event.stopPropagation();
  } else if(window.event) {
    window.event.cancelBubble = true;
  }
}

function navigate(href) {
  menu_navigate(href.split("/").pop().split(".")[0], true);
}

function select(event, id) {
  disable_propagation(event);
  menu_select(id);
}

var hover_timeout;

function hover(event, id) {
  disable_propagation(event);
  hover_timeout = setTimeout(
      function() { menu_navigate(id, false); }, menu_hover_delay);
}

window.onload = function() {
  var items = document.getElementsByTagName("li");
  for (var i = items.length - 1; i >= 0; --i) {
    items[i].onmouseover = function(event) { hover(event, this.id); }
    items[i].onmouseout = function() { clearTimeout(hover_timeout); }
  }
}
