var Subnav = new Class({
	initialize: function(element) {
		this.bookmarks = $(document.body).getElement('div.bookmarks');
		this.anchor = $(document.body).getElement('a.bookmark');
		
		// Check query
		if (window.location.toString().test('#')==true) {
			var target = window.location.toString().split('#')[1];
			this.anchor.setStyles({'display': 'block', 'top': $(document.body).getElement('*[name='+target+']').getCoordinates().top.toInt()+16});
			new Fx.Scroll(window).start(0, $(document.body).getElement('*[name='+target+']').getCoordinates().top.toInt());
		}
		
		// Bookmarks events
		this.anchor.addEvent('mouseover', function() {
			subnav.bookmarks.setStyles({'display': 'block', 'top': this.getCoordinates().top});
		});
		
		this.bookmarks.addEvent('mouseleave', function() {
			this.setStyles({'display': 'none', 'top': this.getCoordinates().top});
		});
		
		// Subnav
		$each($(document.body).getElement('div.subnav').getElements('a'), function(item, index){
			// Add event to the anchor
			item.addEvent('click', function(e) {
				e.stop();
				// Hide div
				subnav.bookmarks.setStyle('display', 'none');
				// Set target
				target = item.get('href').substr(1);
				target = $(document.body).getElement('div.content').getElement('a[name='+target+']');
				target = target.getCoordinates().top.toInt();
				// Move window
				new Fx.Scroll(window).start(0, target);
				// Create new bookmar anchor
				subnav.anchor.setStyles({'display': 'block', 'top': target+16});
			});
		});
		
		// Bookmark window
		$each(this.bookmarks.getElements('a'), function(item, index){
			// Add event to the anchor
			item.addEvent('click', function(e) {
				e.stop();
				// Hide div
				subnav.bookmarks.setStyle('display', 'none');
				// Set target
				if (index==0) target = 0;
				else {
					target = item.get('href').substr(1);
					target = $(document.body).getElement('div.content').getElement('a[name='+target+']');
					target = target.getCoordinates().top.toInt();
				}
				// Move window
				new Fx.Scroll(window).start(0, target);
				// Create new bookmar anchor
				subnav.anchor.setStyles({'display': (index==0 ? 'none' : 'block'), 'top': target+16});
			});
		});
	}
});

var subnav;
window.addEvent('domready', function() { subnav = new Subnav(); })
