if ( typeof Widget == "undefined" ) {
   Widget = {};
};

Widget.TableOfContentGenerator = function(tag, baseElemId) {
   this.tag        = tag;
   this.baseElemId = baseElemId;
   this.anchorCount = 0;
   this.generate();
};

Widget.TableOfContentGenerator.VERSION = '0.02';

proto = Widget.TableOfContentGenerator.prototype;

proto.generate = function() {
   var list = this.collect();
   var output = '<div id="table-of-content" class="table-of-content"><ul>';
   for (var i=0; i < list.length; i++) {
      output +=
         '<li><a href="' + list[i].link + '" onclick="' + list[i].onclick + '" >' + list[i].title + "</a></li>\n";
   }
   output += "</ul></div>\n";
   document.write(output);
};

proto.collect = function() {
   var baseElem = document.getElementById(this.baseElemId);
   var anchors  = baseElem.getElementsByTagName(this.tag);
   var list = [];
   for (var i = 0; i < anchors.length ; i++ ) {
      var title = this.getNodeTextOrLink(anchors[i]);
      var anchorName = this.genAnchorName(title);
      this.insertAnchor(anchors[i], anchorName);
      if(typeof(title) == 'object') {
         list.push({ "title": title.innerHTML , "link": title.getAttribute("href") });
      } else {
         list.push({ "title": title , "link": "#" + anchorName, "onclick": "new Effect.ScrollTo('" + anchorName + "'); return false" });
      }
   }
   return list;
}

proto.getNodeTextOrLink = function(elem) {
   var childs = elem.childNodes;
   if ( childs.length > 1 ) { return this.getNodeText(elem) }
   if (!( childs[0].nodeType == 1 && childs[0].nodeName == "A")) {
      return this.getNodeText(elem);
   } 
   return childs[0];
}

proto.getNodeText = function(elem) {
    var strNodeText = '';
    var xmlChildNodes = elem.childNodes;
    for( var i = 0; i < xmlChildNodes.length; i++ )
    {
        if( xmlChildNodes[ i ].nodeType == 3 )    // text node
            strNodeText += xmlChildNodes[ i ].data;
        else
            strNodeText += this.getNodeText( xmlChildNodes[ i ], true );
    }
    return strNodeText;
}

proto.insertAnchor = function(elem, anchorName) {
   var parent = elem.parentNode;
   var aElem  = document.createElement("a");
   aElem.name = anchorName;
   aElem.id   = anchorName;
   parent.insertBefore(aElem, elem);
}

proto.genAnchorName = function(title) {
   title = "toc-anchor";
   title += (this.anchorCount++);
   return title;
}

/*
var tocgen = new Widget.TableOfContentGenerator("h1","content");

tocgen.generate();

*/

