/*##############################################################################
#    ____________________________________________________________________
#   /                                                                    \
#  |               ____  __      ___          _____  /     ___    ___     |
#  |     ____       /  \/  \  ' /   \      / /      /__   /   \  /   \    |
#  |    / _  \     /   /   / / /    /  ___/  \__   /     /____/ /    /    |
#  |   / |_  /    /   /   / / /    / /   /      \ /     /      /____/     |
#  |   \____/    /   /    \/_/    /  \__/  _____/ \__/  \___/ /           |
#  |                                                         /            |
#  |                                                                      |
#  |   Copyright (c) 1999-2007                        MindStep SCOP SARL  |
#  |   Herve Masson                                                       |
#  |                                                                      |
#  |      www.mindstep.com                              www.mjslib.com    |
#  |   info-oss@mindstep.com                           mjslib@mjslib.com  |
#   \____________________________________________________________________/
#
#  Version: $Id: toc.js 3416 2007-08-06 16:52:31Z herve $
#
#  [This product is distributed under a BSD-like license]
#  
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#  
#     1. Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#  
#     2. Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in
#        the documentation and/or other materials provided with the
#        distribution. 
#  
#  THIS SOFTWARE IS PROVIDED BY THE MINDSTEP CORP PROJECT ``AS IS'' AND
#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
#  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MINDSTEP CORP OR CONTRIBUTORS
#  BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
#  OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
#  OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
#  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
#  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
#  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#  
#  The views and conclusions contained in the software and documentation
#  are those of the authors and should not be interpreted as representing
#  official policies, either expressed or implied, of MindStep Corp.
#  
##############################################################################*/

var gTOC_typeName     = "toc";
var gTOC_instances    = [];
var gTOC_levels       = { H1:1, H2:2, H3:3, H4:4, H5:5, H6:6 };
var gTOC_backLinkText = "";
var gTOC_headings     = null;


//--------------------------------------------------------------------------------
//
//	Parses [part of] the document, and generates TOC content
//
//	1. search for every H? tag within the document tree (or a sub-tree)
//	2. insert a copy of every <Hx>...</Hx> section from within the TOC element
//
//	Note: we need to split the processing in 2 phases: constructing TOCs instances,
//	and then altering the document with new TOC contents. This is because we do
//	not want the generated TOC to be part of another TOC!
//
//--------------------------------------------------------------------------------

function _mjs_tocCreateHref(h)
{
	var id=mjs_allocateElementID(h);
	return "#"+id;
}

function _mjs_displayTocs()
{
	for(var i=0;i<gTOC_instances.length;i++)
	{
		var toc=gTOC_instances[i];
		var where=toc['where'];
		var id=mjs_allocateElementID(where);

		LOGTRACE("attach toc content to tag %s id=%s",where.tagName,id);
		where.appendChild(toc['content']);

		// Insert backlinks to the TOC (if not already done)
		if(gTOC_backLinkText != "")
		{
			var headings=toc['headings'];

			for(var j=0;j<headings.length;j++)
			{
				var h=headings[j];
				if(!mjs_valued(mjs_attr(h,"mjstoclink")))
				{
					h.innerHTML += sprintf(" <a href='%s'>%s</a>",_mjs_tocCreateHref(where),gTOC_backLinkText);
					// Mark this backlink "processed"
					mjs_setAttr(h,"mjstoclink","done");
				}
			}
		}
	}
}

//--------------------------------------------------------------------------------
//
//	Searches for SPAN elements having the proper mjstype, and create TOC content
//	for everyone.
//
//--------------------------------------------------------------------------------

function mjs_tocInitialize()
{
	var list=mjs_lookupTypedElements(gTOC_typeName);
	for(var i=list.length-1;i>=0;i--)
	{
		mjs_createToc(list[i]);
	}
	_mjs_displayTocs();
}

mjs_registerModule("toc",mjs_tocInitialize);

//--------------------------------------------------------------------------------
//
//	Public javascript API 
//
//--------------------------------------------------------------------------------

function mjs_setTocBackLinkText(text)
{
	old=gTOC_backLinkText;
	gTOC_backLinkText=text;
	return old;
}

function mjs_createToc(tocEl,rootEl)
{
	if(!mjs_valued(gTOC_headings))
	{
		gTOC_headings=mjs_lookupTags(rootEl,"h1","h2","h3","h4","h5","h6");
	}

	if(gTOC_headings.length==0)
	{
		LOGERROR("Cannot create TOC - no H? tags were found");
		return false;
	}

	var level=0;
	var html="";

	// Insert a copy of heading texts in the TOC element
	for(var i=0;i<gTOC_headings.length;i++)
	{
		var h=gTOC_headings[i];
		var title=h.innerHTML;
		var nextLevel=gTOC_levels[h.tagName];

		if(nextLevel>level)
		{
			for(var j=level;j<nextLevel;j++)
			{
				html += "<ul>\n";
			}
		}
		else
		{
			for(var j=level;j>nextLevel;j--)
			{
				html += "</ul>\n";
			}
		}
		html += "<li>" + "<a href='" + _mjs_tocCreateHref(h) + "'>" + title + "</a></li>\n";
		level = nextLevel;
	}
	for(var j=level;j>0;j--)
	{
		html += "</ul>\n";
	}

	var toc=document.createElement('span');
	toc.innerHTML=html;
	gTOC_instances.push({ where: tocEl, root: rootEl, content: toc, headings: gTOC_headings });
	return true;
}

