// Self-collapsing elements, like FAQs and inline Applications
// by Lost Boys - www.lostboys.nl

Drawers = function() {
	var self = this;
	var els = getElementsByAttributeValue("class", "drawer-collection", document.getElementById("content"));
	this.collections = new Array();
	for(var i = 0; i < els.length; i++) {
		this.collections[this.collections.length] = new DrawerCollection(els[i]);
	}	
}

Drawers.prototype.closeAllCollections = function() {
	for(var i = 0; i < this.collections.length; i++) this.collections[i].closeAll();
}

DrawerCollection = function(obj) {
	var self = this;
	var hash = document.location.hash;
	this.multipleActive = obj.className.match("multiple");
	this.items = getElementsByAttributeValue("class", "drawer-item", obj);
	for(var i = 0; i < this.items.length; i++) {
		// event for every item
		EventListener.addEvent(this.items[i], "click", function(e) {
			return self.toggleItem(this, e);				
		});
		this.items[i].toggle = function() {
			return self.toggleItem(this);	
		}

		var stat = this.items[i].getAttribute('ns:sitestat');
		// create an anchor and append if none present, to make the switch focusable
		var drawerSwitch = getElementsByAttributeValue("class", "drawer-switch", this.items[i])[0];
		if(drawerSwitch.tagName.toLowerCase() != "a" && drawerSwitch.getElementsByTagName("a").length == 0) {
			var anch = document.createElement("a");
			var href = (this.items[i].id) ? this.items[i].id : "";
			if(stat) { anch.setAttribute('ns:sitestat', stat); }
			anch.href = "#" + href;
			anch.innerHTML = drawerSwitch.innerHTML;
			drawerSwitch.innerHTML = "";
			drawerSwitch.appendChild(anch);
		}
		if(this.items[i].id == hash.substring(1)) addClass(this.items[i], "opened");
	}
}

DrawerCollection.prototype.toggleItem = function(obj, e) {
	this.object = obj;
	if(e) var target = EventListener.getTarget(e);
	if(
	   	!e
		||
	   	target.className.match("drawer-switch")
		||
	   	target.parentNode.className.match("drawer-switch")
	   	||
		target.parentNode.parentNode.className.match("drawer-switch")
	) {
		if(this.object.className.match("opened")) {
			removeClass(this.object, "opened");
			if(e) return EventListener.cancelEvent(e);
		} else {
			if(!this.multipleActive) this.closeAll();
			addClass(this.object, "opened");
			if(e) return EventListener.preventDefault(e);
		}
	}
}

DrawerCollection.prototype.closeAll = function() {
	for(var i = 0; i < this.items.length; i++) {
		removeClass(this.items[i], "opened");
	}
}

EventListener.addEvent(window, "load", function() {
	window.drawers = new Drawers();
} );
