$(document).ready(function() {TreeHandler.init()});


/* Tree configuration
------------------------------------------------*/
TreeHandlerConfiguration = {
	TREE_CLASS:"tree"
}


/* Tree handler
------------------------------------------------*/
TreeHandler = {
	trees:[],
	
	init:function() {
		$("." + TreeHandlerConfiguration.TREE_CLASS).each(
			function() {
				TreeHandler.trees.push(new Tree(this));
			}
		);
	}
}


/* Tree class
------------------------------------------------*/
function Tree(node) {
	this.node = node;
	this.init();
}

Tree.prototype.init = function() {
	var self = this;
	$("li>ul", this.node).each(function() {
		var toggleBtn = $("<span class=\"toggle\"></span>");
			toggleBtn.click(function(e){self.toggle(e)});
		$(this.parentNode).prepend(toggleBtn);
		$(this.parentNode).addClass("closed");
	});
}

Tree.prototype.toggle = function(e) {
	var node = e.target;
	var parent = node.parentNode;
	if ($(parent).hasClass("closed")) {
		this.open(parent);
	}
	else {
		this.close(parent);
	}
}

Tree.prototype.open = function(node) {
	$(node).removeClass("closed");
	$(node).addClass("open");
}

Tree.prototype.close = function(node) {
	$(node).removeClass("open");
	$(node).addClass("closed");
}