/*******************************************************
 *      Set of methods reperesents tree hierarchy structure.
 *******************************************************/
// adds a child to current parent
function addChild(child){
	this.childs[this.childs.length++] = child;
}

// adds a child to specified parent
function addChildToParent(parentid, child) {
	var par = this.lookup(parentid);

	if (par != null) {
		par.addChild(child);
	}
}

// return all childs belonged to parent
function getChilds() {
	var res = new Array();

	for (i in this.childs) {
		res[i] = this.childs[i];
	}

	/*for (i in this.childs)
	{
			res = res.concat(this.childs[i].getChilds());
	}*/

	return res;
}

// lookup item starting from current parent
// return an item or null if not found
function lookup(trid) {
	if (this.trid == trid) {
		return this;
	}

	for (var i in this.childs) {
		var res = this.childs[i].lookup(trid);

		if (res != null) {
			return res;
		}
	}

	return null;
}

// constructor for tree item. takes an item id
// which should exists in document hierarchy
// inistate - boolean flag, false if item should be initially collapsed
function rowtree(trid, inistate) {
	this.trid = trid;
	this.isopen = true;
	this.inistate = inistate;
	this.childs = new Array(0);
	this.lookup = lookup;
	this.addChild = addChild;
	this.addChildToParent = addChildToParent;
	this.getChilds = getChilds;
}

var root = new rowtree('root', true);

function manageItem(rowid, forcestate) {
	var foundrow = root.lookup(rowid);

	if (foundrow != null) {
		var collapse = forcestate == null ? foundrow.isopen : !forcestate;
		var arr = foundrow.getChilds();

		for (var i in arr) {
			document.getElementById((arr[i].trid)).style.display = collapse ? "none" : "";
			manageItem(arr[i].trid, false);
		}

		foundrow.isopen = !collapse;

		if(document.images['menuItemState' + rowid] != null) {
			document.images['menuItemState' + rowid].src = collapse ? "/images/pointer.gif" : "/images/pointer_expanded.gif";
			document.images['menuItemState' + rowid].alt = collapse ? "expand" : "collapse";
		}
	}
}

function setupTree(id) {
	var arr = root.getChilds();

	// set inistate for items
	for (var i in arr) {
		manageItem(arr[i].trid, false);
	}
}

function openNode(id) {
	var path = new Array(0);
	var arr = root.getChilds();

	if(findNode(arr, path, id)) {
		for(var i = path.length - 1; i >= 0; i--) {
			manageItem(path[i].trid, true);
		}
	}
}

function findNode(nodes, path, id) {
	for(var i = 0; i < nodes.length; i++) {
		if(nodes[i].trid == id) {
			path[path.length] = nodes[i];
			return true;
		}

		if(findNode(nodes[i].childs, path, id)) {
			path[path.length] = nodes[i];
			return true;
		}
	}

	return false;
}