/**
 * @author leho@kraav.com
 * @version 0.1
 * @comment Thanks http://trac.edgewall.org/browser/trunk/trac/htdocs/js/trac.js
 */

function xpath(query, element) { // http://diveintogreasemonkey.org/patterns/match-attribute.html
    return document.evaluate(query, element, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
}

(function($) {
	$.fn.addId = function() {
	    return this.filter("*[class=widgettitle]").each (
	    	function() {
				this.id = "Sidebar-" + this.innerHTML.split(' ').join('');
			}
		);
	}
	
	$.fn.addAnchor = function(title) {
    	title = title || "Link here";
    	return this.filter("*[class=widgettitle]").each (
			function() {
      			$("<a class='anchor'> \u00B6</a>").attr("href", "#Sidebar-" + this.innerHTML.split(' ').join('')).attr("title", title).appendTo(this);
    		}
		);
	}
	
	$.fn.addSideNavBarLinks = function(title) {
		var sideNavBarSnapshot = xpath("//div[@id='sidebar-2']/ul", document.getElementsByTagName('body')[0]);
		var sideNavUl = sideNavBarSnapshot.snapshotItem(0);
		
		if (sideNavUl) {
			var widgetTitles = xpath("//div[@id='sidebar-1']//h2[@class='widgettitle']", document.getElementsByTagName('body')[0]);

			if (widgetTitles) {
				for (var ii = 0; ii < widgetTitles.snapshotLength; ii++) {
					thisWidget = widgetTitles.snapshotItem(ii);

					var h2 = document.createElement('h2');
						h2.setAttribute('class', 'widgettitle');
					var a = document.createElement('a');
						a.setAttribute('href', '#Sidebar-' + thisWidget.innerHTML);
						a.appendChild(document.createTextNode(thisWidget.innerHTML));
						h2.appendChild(a);
					var li = document.createElement('li');
						li.appendChild(h2);
						sideNavUl.appendChild(li);
				}
			}
		}
	}	
}
)(jQuery);

jQuery(document).ready (
	function($) {
		$("#sidebar-1").addSideNavBarLinks();
		$("#sidebar-1").find("h2").addId();
		$("#sidebar-1").find("h2").addAnchor();
	}
);