/* just a tree handler by theo.van.eijndhoven@chello.nl */

function Tree(name)
{

	this.name = name;
	this.children = null;
	this.parent = null;
	this.userData = null;
	
	this.addNode = addNode;
	this.addChild = addChild;
	this.locateNode = locateNode;
	this.treeWalk = treeWalk;

}

function addNode(parentName, nodeName)
{
	var node = null;
	if ( parentNode = this.locateNode(parentName) )
	{
		node = new Tree(nodeName);
		node.parent=parentNode;	
		parentNode.addChild(node);
	}
	else
		alert("parent [" + parentName + "] not found.");
	
	return node;
}

function addChild(node)
{
	if ( this.children == null ) this.children = new Array();
	this.children[this.children.length] = node;
}

function locateNode(nodeName)
{
	var node;
	var foundNode;

	if ( this.name == nodeName ) return this;
	if ( this.children == null ) return null;
	
	for ( var n = 0; n < this.children.length; n++ )
	{
		node = this.children[n];
		if ( foundNode = node.locateNode(nodeName) )
			return foundNode;
	}
	return null;
}

/* treeWalk takes the visitor to every node,
   it passes the node, and its depth to the visitor.accept() method,
   for the visitor to do something with the node
   It is a 'inverted implementation' of the design pattern, which
   maybe looks a bit like an iterator. (I didn't like the idea that
   my nodes need to know which visitor to grant access, which is what the "experts"
   wrote to be the nature of the visitor design pattern */
   
function treeWalk(visitor, depth, callLevel)
{
	if ( callLevel == null ) callLevel = 0;
	if ( depth > -1 && callLevel > depth ) return;
	
	visitor.accept(this, callLevel);
	if ( this.children == null ) return;
	
	var level = callLevel+1;
	for ( var n = 0; n < this.children.length; n++ )
	{
		node = this.children[n];	
		node.treeWalk(visitor, depth, level);
	}
}
