/*
 *
 * Turn a plain table of contents into a collapsible/expandable
 * browser interface.
 *
 * Uses the jQuery JavaScript library
 *
 * Based closely on code from
 * http://homework.nwsnet.de/news/view/31-turn-nested-lists-into-a-collapsible-tree-with-jquery
 *
 */
// Execute this after the site is loaded.
$(document).ready(function() {
  /*
   * Find list items representing super-sections and add to them
   * links that can expand/collapse the sub-structure.
   */
  $("li").not(".untitled").children("ul.toc").each(function(i) {
    // Find this list's parent list item.
    var parent_li = $(this).parent("li");

    // Style the list item as collapsible, starting in the contracted
    // state.
    parent_li.addClass("contracted");

    // Temporarily remove the list from the parent list item, wrap the
    // remaining text in an anchor, then reattach it.
    var sub_ul = $(this).remove();
    parent_li.prepend("<a><img src='/tm/plus.gif'></a> ").find("a:first-child").click(function() {
      if (parent_li.hasClass("contracted")) {
        parent_li.removeClass("contracted");
        parent_li.addClass("expanded");
        $(this).find("img").attr("src", "/tm/minus.gif").attr("alt", "Collapse section: ");
      } else {
        parent_li.removeClass("expanded");
        parent_li.addClass("contracted");
        $(this).find("img").attr("src", "/tm/plus.gif").attr("alt", "Expand section: ");
      }
      // Make the anchor toggle the sub-structure display.
      sub_ul.toggle();
    });

    parent_li.append(sub_ul);
  });
  // Hide all lists except the outermost, or those which are
  // children of an untitled item.

  $('ul.toc ul.toc').not($("li.untitled > ul")).hide();
});
