var ContentTable = function () {
	// Get the anchor from the ul(list)
	$each($(document.body).getElement('ul.bookmarks').getElements('a'), function(item){
		// Add event to the anchor
		item.addEvent('click', function(e) {
			e.stop();
			var scroll = item.get('href').replace('#', '');
			new Fx.Scroll(window).toElement($(document.body).getElement('a[name='+scroll+']'));
		});
		
	});
};

// Navigate through the Table of Contents
var Scroller = new Class({
	current: 0,
	initialize: function() {
		// Get Elements
		var elements = $(document.body).getElement('div.layout-b').getChildren();
		// Check if sub bookmarks exists
		var bookmarks = $(document.body).getElement('ul.bookmarks');
		var sub = false;
		$each(bookmarks.getChildren(), function(item){ 
			if ($chk(item.getElement('ul'))) sub = true; 
		});
		// Process each Elements
		var step = 0;
		var header = '';
		$each(elements, function(item){
			if (item.get('tag')=='h4'||(sub&&item.get('tag')=='h5')) { step++; header = item; }
			if (step>0) {
				var currentStep = step;
				var currentHeader = header;
				item.addEvent('mouseover', function(e){
					if (!$chk($(e.target).get('href'))) scroller.show(currentStep, currentHeader);
				});
				item.addEvent('mouseout', function(){ scroller.hide(currentStep); });
				item.addEvent('click', function(e){
					if (!$chk($(e.target).get('href'))) new Fx.Scroll(window).toTop();
				});
			}
		});
		// Create arrow
		this.arrow = new Element('img', {
			'src': '/images/icons/bullet_top.gif', 
			'width': 16, 
			'height': 16,
			'styles': {'position': 'absolute', 'top': 0, 'left': -8, 'opacity': '0'}
		}).inject($(document.body).getElement('div.layout-b'), 'top');
		// Create Fx
		this.myfx = new Fx.Tween(this.arrow, {property: 'opacity', link: 'cancel', duration: 450});
	},
	show: function(item, header) {
		if (this.current==item) { this.myfx.start(1); }
		else {
			var top = header.getPosition($(document.body).getElement('div.layout-b')).y;
			this.arrow.setStyles({'opacity': 0, 'display': 'block', 'top': (top+2)});
			this.myfx.start(1);
			this.current = item;
		}
	},
	hide: function(item) { this.myfx.start(0); }
});

var scroller;
window.addEvent('domready', function() {
	// Table of Contents
	if ($chk($(document.body).getElement('ul.bookmarks'))) ContentTable.run();
	// Navigation through the Table of Contents
	if ($chk($(document.body).getElement('ul.bookmarks'))) scroller = new Scroller;
});