// local
Event.observe(window, 'load', function() {
	new PageNav('pagenav', 'sn-', 'subnav', 'li');
}, false);


// generic
PageNav = Class.create({

	initialize: function(containerId, contentPrefix, contentId, contentTag) {
		this.container = $(containerId);
		this.content = $(contentId);

		this.getElement(contentPrefix);

		if (this.container) {
			if (this.container.empty()) {
				if (this.item) {
					this.getPrevious();
					this.getNext();
					this.writeLinks();
				}
			}
		}
	},

	getElement: function(contentPrefix) {
		var id = document.body.id;
		if (id) this.item = $(contentPrefix+id);
	},

	getPrevious: function() {
		this.previous = this.item.previous('li');

		var first = this.item.parentNode.previousSibling;
		while (first && (!first.tagName || first.tagName.toLowerCase() != 'h2')) first = first.previousSibling;
		if (!this.previous && first) this.previous = first;

		if (this.previous) {
			this.previous = $(this.previous);
			this.previous = this.writeWrappers(this.previous);
			this.previous.className += ' previous';
		}
	},

	getNext: function() {
		this.next = this.item.next('li');

		if (this.next) {
			this.next = $(this.next);
			this.next = this.writeWrappers(this.next);
			this.next.className += ' next';
		}
	},

	writeWrappers: function(node) {
		var clone = $(node.down('a').cloneNode(true));
		clone.addClassName('arrow');

		var wrapper = Builder.node('div', [clone]);

		return wrapper;
	},

	writeLinks: function() {
		if (this.previous && this.previous.nodeType == 1) this.container.appendChild(this.previous);
		if (this.next && this.next.nodeType == 1) this.container.appendChild(this.next);
	}

});