/**
 * Link Tree Class
 * This class is a node that contains links to any number of other nodes.
 * @author Sean Hayes
 */
function LinkTree(title, url, newWindow, useFacebox, header) {
	this.branches = new Array();
	this.isLeaf = true;
	this.title = title;
	this.level = 0;
	this.url = url;
	this.header = header;
	if(newWindow == null)
		this.newWindow = false;
	else
		this.newWindow = newWindow;
		
	if(useFacebox == null)
		this.useFacebox = false;
	else
		this.useFacebox = useFacebox;
		
	var self = this;
	
	this.add = function(branch) {
	   this.branches[this.branches.length] = branch;
	   this.isLeaf = false;
	   branch.setLevel(this.level + 1);
	}
	
	this.write = function() {
		var treeString = '';
		var numBranches = this.branches.length;
		for (var i=0;i <numBranches;i++)
			treeString += this.branches[i].write();
		document.write(treeString);
	}
	
	this.clicked = function() {
		// Clear out previous children
		var divEl;
		for(var i = self.getLevel() + 1; (divEl = document.getElementById('level' + i)) != null; ++i) {
			divEl.innerHTML = "";
		}
		
		// Perform action
		if(self.isLeaf) {
			self.goToURL();
		}
		else {
			self.listChildren();
		}
	}
	
	this.goToURL = function() {
		if (url == null)
			return;
		
		if(this.useFacebox) {
			jQuery.facebox({ ajax: self.url });
		}			
		else if(newWindow) {
			window.open(url.substring(url.indexOf(",") + 1, url.length), 
				url.substring(0, url.indexOf(",")));
		}
		else {
			location.href = self.url;
		}
	}
	
	this.setLevel = function(level) {
		this.level = level;
		for(var i in this.branches)
			this.branches[i].setLevel(level + 1);
	}
	
	this.getLevel = function() {
		return this.level;
	}
	
	this.getTitle = function() {
		return this.title;
	}
	
	this.listChildren = function() {
		var levelDiv = document.getElementById('level' + (self.level + 1));
		levelDiv.style.visibility='visible';
		
		for(var branch in this.branches) {
			var divEl = document.createElement('div');
			divEl.innerHTML = self.branches[branch].getTitle();
			divEl.onmousedown = function() {setSelect(this);};
			divEl.onclick = self.branches[branch].clicked;
			levelDiv.appendChild(divEl);
		}
		
		var headerDiv = document.getElementById('treeheader');
		if(self.header != null)
			headerDiv.innerHTML = self.header;
		else
			headerDiv.innerHTML = '';
	}
}

function setSelect( el )
{
	// Mark Selected
	// Get all children of node
	var sib = el.parentNode.childNodes;
	
	// Loop through the children
	for( var c = 0; c < sib.length; ++c )
		sib[c].className = '';
		
	el.className = "selected";
	return el.innerHTML;
}

function expandHelper( x, id )
{
	var element = document.getElementById( id );
	
	element.style.height = element.offsetHeight + 1 + "px";
	if( element.offsetHeight >= x )
	{
		element.style.height = x + "px";
		return;
	}
	else
		setTimeout("expandHelper('" + x + "','" + id + "')",10);
}
