// Expand/Collapse swapper...
ExpandCollapse = Class.create();
ExpandCollapse.prototype = {
	initialize: function(label, content, container) {
		// get the labels and contents
		this.lablesClass = label;
		this.lables = document.getElementsByClassName(label);
		this.contentClass = content;
		this.content = document.getElementsByClassName(content);

		// hide/show the lables and content
		for (var i=0; i<this.lables.length; i++) {
			this.lables[i].index = i;
			this.content[i].index = i;
			if (!Element.hasClassName(this.content[i], 'active')) { this.content[i].style.display = 'none' };
			Event.observe(this.lables[i], 'click', this.showhide.bind(this), false);
		}

		// get all the anchors
		var links = $(container).getElementsByTagName('a');
		var url = document.location.toString();
		url = url.substring(0, url.indexOf('#'));
		for (var i=0; i<links.length; i++) {
			var href = links[i].href;
			if (href.indexOf('#')>0 && href.indexOf(url)==0) {
				Event.observe(links[i], 'click', this.gotoanchor.bindAsEventListener(this, href, content));
			}
		}

		// add the hasjs class to faciliate styles
		Element.addClassName(container, 'hasjs');
	},

	showhide: function(ev, options) {
		if (ev) {
			// stop the default action
			Event.stop(ev);
	
			// find the clicked link
			if(!ev) { ev = window.event; }
			var clicked = (window.event) ? window.event.srcElement : ev.target;
			while (!clicked.className || Element.hasClassName(clicked, this.contentClass)) clicked = clicked.parentNode;
		} else if (options) {
			clicked = this.lables[options.index];
			var anchor = options.anchor;
			var after = function() {
				document.location.hash = this;
			}.bindAsEventListener(anchor);
		}

		// swap the clicked link class
		if (Element.hasClassName(clicked, 'closed')) {
			Element.removeClassName(clicked, 'closed');
		} else {
			Element.addClassName(clicked, 'closed');
		}

		// do the expand/collapse effect
		Effect.toggle(this.content[clicked.index], 'blind', {duration:.3, afterFinish:after});
	},

	gotoanchor: function(evt, url, parentClass) {
		var options = {};

		url = url.substring(url.indexOf('#')+1, url.length)
		var target = $(url);
		console.log(target);
		var parent = target.parentNode;
		while (!parent.tagName || !Element.hasClassName(parent, parentClass)) parent = parent.parentNode;

		if (Element.getStyle(parent, 'display') != 'block') {
			Event.stop(evt);
			options.anchor = url;
			options.index = parent.index;
			this.showhide(null, options);
		}
	}
}

Event.observe(window, 'load', function() { new ExpandCollapse('expandable', 'expandcontent', 'content'); }, false);

