/**
 * Install notebook handlers on all notebook divs
 */
installNotebookHandlers = function()
{
	var notebookElements;
	notebookElements = document.getElementsByClassName('notebook');

	for (var i = 0; i < notebookElements.length; i++)
	{
		/* Only div.notebook elements should be taken into account */
		if (notebookElements[i].nodeName != 'div' && notebookElements[i].nodeName != 'DIV')
			continue;

		notebookDiv = notebookElements[i];

		/* Install on-click handler on each tab */
		tabs = Element.immediateDescendants(notebookDiv.getElementsByClassName('notebook-tabs')[0]);
		tabs.each(
			function(tab)
			{
				if (tab.addEventListener) {
					tab.firstChild.onclick = notebookTabOnClickHandler;	/* Firefox handler */
				}
				else {
					tab.attachEvent('onclick', notebookTabOnClickHandler);	/* IE handler */
				}
			}
		);
	}
}

/**
 * Handle click events on notebook tabs.
 */
notebookTabOnClickHandler = function(ev)
{
	/* Find out position of clicked tab */	
	if (!ev) var ev = window.event;

	if (ev.target) {
		tab_idx = $(ev.target).parentNode.previousSiblings().length;
		notebookDiv = ev.target.parentNode.parentNode.parentNode;
	} else {
		tab_idx = $(ev.srcElement).parentNode.previousSiblings().length;
		notebookDiv = ev.srcElement.parentNode.parentNode.parentNode;
	}

	/* Set correct styles on all tabs */

	tabs = Element.immediateDescendants(notebookDiv.getElementsByClassName('notebook-tabs')[0]);
	tabs.each(
		function(tab)
		{
			tab.removeClassName('notebook-tab-active');
		}
	);
	if (ev.target)
		$(ev.target).parentNode.addClassName('notebook-tab-active');
	else
		$(ev.srcElement).parentNode.addClassName('notebook-tab-active');

	/* Iterate over pages */
	pages = Element.immediateDescendants(notebookDiv.getElementsByClassName('notebook-pages')[0]);
	pages.each (function (page)
	{
		var page_idx = page.previousSiblings().length;

		if (page_idx == tab_idx) {
			//Element.show(page);
			page.addClassName('notebook-page-active');
		} else {
			//Element.hide(page);
			page.removeClassName('notebook-page-active');
		}
	});

	/* Do not follow hyperlink */

	return false;
}


/* Install handlers when the page is loaded. */
window.onload.actions.push(installNotebookHandlers);
