//  Time-stamp: "2005-05-23 23:17:13 ADT" 
// sburke@cpan.org
// Generate a ToC for Pod::Simple::HTML-generated documents
//  (probably easily adaptable to anything)

var class_for;
class_for = class_for ||
   {h1:"xh1", h2:"xh2", h3:"xh3", h4:"xh4", h5:"xh5", h6:"xh6"};

function toc_gen () {

  var verytop = document.getElementsByName('___top');
  if(!(verytop && verytop.length)) throw "Can't find top";
  verytop = verytop[0];
  var body = verytop.parentNode;
  if(body.tagName.toLowerCase() != "body")
   throw("What, a's parentNode is " + body);

  var div = document.getElementById('tocwrap') || make_tocwrap(body, verytop);
  
  var c = body.childNodes;
  var headings_found = 0;

  // Iterate over headings:

  for(var i = 0; i < c.length; i++) {
    var classy = class_for[ (c[i].tagName || '').toLowerCase() ];
    if(!classy) continue;
    var h = c[i];
    var aname = h.name || get_name_under(h);
    if(!aname) continue;
    ++headings_found;
    note_heading(div, h, aname, classy + " xh");
  }
  if(!headings_found) throw "No headings found?!";
  return;
}

function make_tocwrap (body, verytop) {
  var div = document.createElement('div');
  div.setAttribute( "id",    "tocwrap" );
  body.insertBefore( div, verytop.nextSibling );

  var p = document.createElement('p');
  p  .setAttribute( "class", "toc_intro" );
  p  .appendChild( document.createTextNode( "Table of Contents" ));
  div.appendChild(p);
  return div;
}

function note_heading (div,h,aname,classy) {
  var p = document.createElement('p');
  p.setAttribute( "class", classy );
  var a = document.createElement('a'); 
  a.setAttribute( 'href', "#" + encodeURI(aname));

  a  .appendChild( document.createTextNode( h.textContent ));
  p  .appendChild(a);
  div.appendChild(p);
  return;
}


function get_name_under (n) { // gets the first name=XX attribute under here.
  var c = n.childNodes;
  for(var i = 0; i < c.length; i++) {
    if(c[i].nodeType != document.ELEMENT_NODE) continue;
    var a = c[i].name || get_anchor_in(c[i]) || undefined;
    if(a) return a;
  }
  return undefined;
}

class_for.h1 = 0;
toc_gen();

