// $Id$
/**
 * @file
 * TOC builder for advanced_help pages
 *  
 * @copyright Ouest Systèmes Informatiques (OSInet)
 *
 * @license Licensed under the General Public License version 2 and later.
 */

/**
 * Build a TOC div from the Hn elements in a given context
 * 
 * Extract the H[1-7] list in DOM order manually: with jQuery < 1.4,
 * neither $('h1, h2...') nor .add() return in DOM order, hence the use
 * of filter() on a * selector instead.
 * 
 * @return jQuery
 *   A list of the headings in the page
 */
function ahTocBuildToc() {

  var context = $('div.advanced-help-topic');
  var elements = $('*', context).filter(function (index) {
    return ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7'].indexOf(this.nodeName) != -1;
  });

  /**
   * Only build the toc if there 2 headings or more in the page
   */
  if (elements.length <= 1) {
    return;
  }

  // Build the headings list
  var list = "<ul>\n";
  elements.each(function() {
    list += '<li class="' + this.nodeName.toLowerCase() + '">'
        + $(this).text() + "</li>\n";
  })
  list += "</ul>\n";

  // Avoid creating multiple TOCs if this function is called several times
  $('div.ah-toc', context).remove(); 
  
  // @TODO use a theme function
  context.prepend('<div class="ah-toc"><center>Contents</center></div>');
  $('div.ah-toc').append(list);
  return elements;
}

$(ahTocBuildToc);