/* Table of contents generator */
/* Rob Walker */
/* Requires jquery 1.6.4 */

/* Auto generates a table of contents from specified TOC elements. */
/* anchors are added to the toc elements, named sequentially 0,1,2 .. n */

function initTOC(){
  contentsList = '';
  /* Specify the elements to list in the toc */
  $('h2, h3').each(function(index){
  	if (!skipEntry($(this))) {
  	    // Put the named anchor before the page element.
		$(this).before($('<a></a>').attr('name', index).attr('class', 'bookmark'));
		
		// The list itself is being built as a string so that it can be added to the dom all at one time.
		contentsList += '<li><a href="#'+ (index++) +'" >'+ cleanTOC($(this).text()) +'</a></li>';
		}
  	});
  /* Create an unordered list to be the TOC. */
  /* If there is no content for the TOC don't make the TOC. */
  if (contentsList != '') {
	  $('#main_content').append(toc = $('<ul id="toc" class="image_border"></ul>').html("<h2>Table of Contents</h2>" + contentsList +
	  '<span class="top_open"></span><span class="top_right_open"></span><span class="right_open"></span><span class="bottom_right_open"></span><span class="bottom_open"></span><span class="bottom_left_open"></span><span class="left_open"></span><span class="top_left_open"></span>'
	  )); // span elements are used for the graphic border on the TOC
  }
}

function cleanTOC (tocText) {
/* Remove specified text from the toc text to minimize */
/* the length of the toc entries */
  if (typeof tocText === 'string'){
    /* Remove the following words from the toc listing. */
    /* Note: colon is removed greedily and may need to be end of word only. */
    var pattern = new RegExp('(:|\\bwestfall\\b|\\bmodel\\b|\\b2800\\b|\\b2900\\b)', 'ig');
	return tocText.replace(pattern, '');
  }
  else {return null};
}

function skipEntry (tocElement) {
/* Specify a list of strings which will NOT be entered into the TOC */
/* Also elements with class "noTOC" will not be entered into the TOC */
	var elementClass = $(tocElement).attr('class');
    if (elementClass && elementClass.indexOf('noTOC') != -1) {return true;}

	tocText = $(tocElement).text();
	if (typeof tocText === 'string'){
		/* Skip the following strings. */
		var skipList = ['table of contents'];
		if ($.inArray(tocText.toString().toLowerCase(), skipList) > -1) {
			return true;
		}
		else {return false;}
	  }
	  else {return false}; // A non-string was passed, don't make an entry from it.
}

