/*
   Responsável: Andre Vallier
   Data:        04/05/2005
   Objetivo:
         Garantir que o menu apresentado acompanhe a navegação realizada pelo usuário. Foram 
      realizadas alterações nos métodos da classe dTree: 
         - s
            Alterado para alterar o endereço atual. É enviado para o endereços as variáveis
         contidas no cookie
         - node
            Alterado para não realizar a alteração da url (href=#) para a localização
         do nódulo
         - setCookie, getCookie
            Estes métodos foram alterados para ao invez de trabalhar com cookie ele armazena
         informações em uma variável em top
         
   Obs.: ver início do código de menu-b.asp

   Responsável: Andre Vallier
   Data:        07/06/2005
   Objetivo:
        Possibilitar o acesso a um determinado nódulo a partir do nome informado na sua
      criação. Foram realizadas as seguintes alterações:
        - criação dos métodos arrayParent, openParent na classe Node
        - criação do método findNodeID, findNodeName nas classes dTree e dForest
      
*/

/*--------------------------------------------------|
| dTree 2.05 | www.destroydrop.com/javascripts/tree/|
|---------------------------------------------------|
| Copyright (c) 2002-2003 Geir Landrö               |
|                                                   |
| This script can be used freely as long as all     |
| copyright messages are intact.                    |
|                                                   |
| Updated: 17.04.2003                               |
|--------------------------------------------------*/

//definicao do endereco base do site
//var url_do_site = "http://10.32.17.15/site-dev/site-andima/";
//var url_do_site = "http://www.andima.rtm/site-andima/";
var url_do_site = "http://www.andima.com.br/";

// Node object
function Node(id, pid, name, url, title, target, icon, iconOpen, open) {
	this.id = id;
	this.pid = pid;
	this.name = name;
	this.url = url;
	this.title = title;
	this.target = target;
	this.icon = icon;
	this.iconOpen = iconOpen;
	this._io = open || false;  // no´ aberto
	this._is = false;          // no´ selecionado
	this._ls = false;          // ultimo nivel (folha)
	this._hc = false;          // nivel interno
	this._ai = 0;              // profundidade?
	this._p;
};

// array of parents
Node.prototype.arrayParent = function(pbTodos) {
    var arrayParent_aRet = new Array();
    var hN = this._p;
    while (String(hN) != "undefined")   {
        if (String(hN.name) != "undefined")    {
            arrayParent_aRet[arrayParent_aRet.length] = hN;
        }
        hN = hN._p;
    }
    return arrayParent_aRet;    
}

// open parents
Node.prototype.openParent = function() {
    var aParent = this.arrayParent();
    var str = "";

    // força abertura de árvore pelo fechamento das demais
    this.parentTree.parentForest.clickTreeRoot(this.parentTree.obj);
    
    // abre as nódulos anteriores
    for(i=aParent.length-1; i > -1; i--)   {
        if (str) str += ", ";
        str += aParent[i].name 
            +   "(" 
            +              aParent[i].id 
            +       ", " + aParent[i]._ai 
            +   ")"
        ;
        if (aParent[i]._ai > 0 && !aParent[i]._io) {
            str += "\nabriu: " + aParent[i].name + " -> " + aParent[i]._ai;
            this.parentTree.o(aParent[i]._ai);
        }
    }
    
    //  atualiza cookies
    this.parentTree.updateCookie();
    
    // apresenta trace
    //alert("Node.openParent\n" + "Total de nódulos:" + aParent.length + "\n" + str);
    
}

// Tree object
function dTree(objName, containerName, pForest) {
	this.config = {
		target          : null,
		folderLinks		: true,
		useSelection	: true,
		useCookies		: true,
		useLines		: true,
		useIcons		: true,
		useStatusText	: false,
		closeSameLevel 	: false,
		inOrder			: false,
		parentTree      : null
	}
	this.icon = {
		root			: url_do_site+'img/menu/base.gif',
		folder			: url_do_site+'img/menu/folder.gif',
		folderOpen	    : url_do_site+'img/menu/folderopen.gif',
		node			: url_do_site+'img/menu/page.gif',
		empty			: url_do_site+'img/menu/empty.gif',
		line			: url_do_site+'img/menu/line.gif',
		join			: url_do_site+'img/menu/join.gif',
		joinBottom	    : url_do_site+'img/menu/joinbottom.gif',
		plus			: url_do_site+'img/menu/plus.gif',
		plusBottom	    : url_do_site+'img/menu/plusbottom.gif',
		minus			: url_do_site+'img/menu/minus.gif',
		minusBottom	    : url_do_site+'img/menu/minusbottom.gif',
		nlPlus			: url_do_site+'img/menu/nolines_plus.gif',
		nlMinus			: url_do_site+'img/menu/nolines_minus.gif'
	};
	this.obj = objName;
	this.aNodes = [];
	this.aIndent = [];
	this.root = new Node(-1);
	this.selectedNode = null;
	this.selectedFound = false;
	this.completed = false;
	this.visible = true;
	
	// nome do div (ou um container qq) que contém a arvore
	if (String(containerName) != "undefined" && containerName != null)   {
	   this.parentContainer = containerName;
	}
	
	// ponteiro para o array de objetos trees pai	
	if (String(pForest) != "undefined" && pForest != null)   {
	   this.parentForest = pForest;
	   this.parentForest.add(this);
	}
};

// Adds a new node to the node array
dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) {
	this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
	this.aNodes[this.aNodes.length-1].parentTree = this;
};

// Open/close all nodes
dTree.prototype.openAll = function() {
	this.oAll(true);
};
dTree.prototype.closeAll = function(bCloseContainer) {
	this.oAll(false, bCloseContainer);
};

// Outputs the tree to the page
dTree.prototype.toString = function() {

	var str = '<div class="dtree">\n';
	this.visible = this.getVisible();

	// identifica o nódulo selecionado
	if (document.getElementById) {
		if (this.config.useCookies) {
         this.selectedNode = this.getSelected();
		}
		str += this.addNode(this.root);
	} else str += 'Browser not supported.';
	str += '</div>';
	if (!this.selectedFound) this.selectedNode = null;
	this.completed = true;
	
	if (this.visible)   {
	   this.parentForest.selectedTree = this.obj;	
	}
	else  {
	    if (String(top.fechandoNodulos).indexOf(this.obj+";") == -1) {
	        if (String(top.fechandoNodulos) == "undefined") top.fechandoNodulos = "";
	        top.fechandoNodulos += this.obj + ";";
            setTimeout(
                    ""
             	   +  "if (  String(" + this.obj + ")          != 'undefined'"
             	   +    " && String(" + this.obj + ".closeAll) != 'undefined'"
             	   +     ") {"
                   +     this.obj + ".closeAll();"
                   +  "}"
               ,  50
            );
        }
      
	}

	return str;
};

// Creates the tree structure
dTree.prototype.addNode = function(pNode) {
	var str = '';
	var n=0;
	if (this.config.inOrder) n = pNode._ai;
	for (n; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == pNode.id) {
			var cn = this.aNodes[n];
			cn._p = pNode;
			cn._ai = n;
			this.setCS(cn);
			if (!cn.target && this.config.target) cn.target = this.config.target;
			if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);
			if (!this.config.folderLinks && cn._hc) cn.url = null;
			if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {
					cn._is = true;
					this.selectedNode = n;
					this.selectedFound = true;
			}
			str += this.node(cn, n);
			if (cn._ls) break;
		}
	}
	return str;
};

// Creates the node icon, url and text
dTree.prototype.node = function(node, nodeId) {
	var str = '<div class="dTreeNode">' + this.indent(node, nodeId);
	if (this.config.useIcons) {
		if (!node.icon) node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
		if (!node.iconOpen) node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
		if (this.root.id == node.pid) {
			node.icon = this.icon.root;
			node.iconOpen = this.icon.root;
		}
		str += '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />';
	}
	if (node.url) {
		str += 
		      "<a"
		   +     " id='s" + this.obj + nodeId + "'"
		   +     " class="
		   +           "'" 
		   +              (  (this.config.useSelection) 
		                     ? ((node._is ? "nodeSel" : "node")) 
		                     : "node"
		                  ) 
         +           "'"
		   //+     " href='" + node.url + "'"
		   +     " href='#'"
		;
		if (node.title) str += ' title="' + node.title + '"';
		if (node.target) str += ' target="' + node.target + '"';
		if (this.config.useStatusText) str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';
		if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))
			str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';
		str += '>';
	}
	else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)
		str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';
	str += node.name;
	if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>';
	str += '</div>';
	if (node._hc) {
//f?		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.visible && (this.root.id == node.pid || node._io)) ? 'block' : 'none') + ';">';
		str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">';
		str += this.addNode(node);
		str += '</div>';
	}
	this.aIndent.pop();
	return str;
};

// Adds the empty and line icons
dTree.prototype.indent = function(node, nodeId) {
	var str = '';
	if (this.root.id != node.pid) {
		for (var n=0; n<this.aIndent.length; n++)
			str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
		(node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);
		if (node._hc) {
			str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
			if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
			else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );
			str += '" alt="" /></a>';
		} else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
	}
	return str;
};

// Checks if a node has any children and if it is the last sibling
dTree.prototype.setCS = function(node) {
	var lastId;
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id) node._hc = true;
		if (this.aNodes[n].pid == node.pid) lastId = this.aNodes[n].id;
	}
	if (lastId==node.id) node._ls = true;
};

// Returns the selected node
dTree.prototype.getSelected = function() {
	var sn = this.getCookie('cs' + this.obj);
	return (sn) ? sn : null;
};

// Highlights the selected node
dTree.prototype.s = function(id) {
	if (!this.config.useSelection) return;
	var cn = this.aNodes[id];
	if (cn._hc && !this.config.folderLinks) return;
	if (this.selectedNode != id) {
		if (this.selectedNode || this.selectedNode==0) {
			eOld = document.getElementById("s" + this.obj + this.selectedNode);
			if (eOld && String(eOld) != "undefined")
			    eOld.className = "node";
		}
		eNew = document.getElementById("s" + this.obj + id);
		eNew.className = "nodeSel";
		this.selectedNode = id;
		if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);
	}
	
	// Resp.: Andre Vallier
	// Dta.:  04/05/2005
	//  direciona para a página solicitada (ver explicações no início do fonte)
	if (cn.url) {
	   //sCookie = String(document.cookie);
	   if (String(top.dadosCookie) == "undefined") top.dadosCookie = "";
	   sUrl    = cn.url;
	   sCookie = String(top.dadosCookie);
	   sCookie = sCookie.replace(/\ /g, "");

	   // define o método de execução
	   if (cn.url.indexOf("get:") == 0) {
	      sUrl    = cn.url.substring(4);
	      sCookie = "";
	      document.cookieForm.method = "get";
	   }

	   // define a url e dados do cookie
	   document.cookieForm.action = sUrl;
	   document.cookieForm.cookieDados.value = sCookie;

	   // força o processamento após um tempo
	   window.setTimeout("cookieFormSubmit('" + sUrl + "', '" + sCookie + "');", 500);
	}
	
};

// Toggle Open or close
dTree.prototype.o = function(id) {
	var cn = this.aNodes[id];
	this.nodeStatus(!cn._io, id, cn._ls);
	cn._io = !cn._io;
	if (this.config.closeSameLevel) this.closeLevel(cn);
	if (this.config.useCookies) this.updateCookie();
	if (String(this.parentForest) != "undefined") this.parentForest.closeAllTrees(true, this.obj);
};

// Open or close all nodes
dTree.prototype.oAll = function(status, bCloseContainer) {
if (String(top.fazDebug) != "undefined")  {
}
   if (String(bCloseContainer) == "undefined") {
      bCloseContainer = true;
   }   

	this.setVisible(status);
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
			this.nodeStatus(status, n, this.aNodes[n]._ls)
			this.aNodes[n]._io = status;
		}
	}

   if (bCloseContainer && String(this.parentContainer) != "undefined") this.oParent(status);
	if (this.config.useCookies) this.updateCookie();	
};

// Open or close the parent container - (novo)
dTree.prototype.oParent = function(status) {
   
   if (String(this.parentContainer) != "undefined") {
      mobj = Dhtml_obtemLayer(this.parentContainer, document); 	      
      if (status) Dhtml_mostraLayer(this.parentContainer, document);
      else  Dhtml_escondeLayer(this.parentContainer, document);
      this.setVisible(status);
   }
}

// Opens the tree to a specific node
dTree.prototype.openTo = function(nId, bSelect, bFirst) {
	if (!bFirst) {
		for (var n=0; n<this.aNodes.length; n++) {
			if (this.aNodes[n].id == nId) {
				nId=n;
				break;
			}
		}
	}
	var cn=this.aNodes[nId];
	if (cn.pid==this.root.id || !cn._p) return;
	cn._io = true;
	cn._is = bSelect;
	if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls);
	if (this.completed && bSelect) this.s(cn._ai);
	else if (bSelect) this._sn=cn._ai;
	this.openTo(cn._p._ai, false, true);
};

// Closes all nodes on the same level as certain node
dTree.prototype.closeLevel = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) {
			this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);
		}
	}
}

// Open all nodes of the level - novo
dTree.prototype.openLevel = function(iLevel) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == iLevel && this.aNodes[n]._hc) {
			this.aNodes[n]._is = true;
		}
	}
	
	// se necessario, abre o container
	if (iLevel == 0) {
	   this.oParent(true);
	}

}

// Closes all children of a node
dTree.prototype.closeAllChildren = function(node) {
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
			if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
			this.aNodes[n]._io = false;
			this.closeAllChildren(this.aNodes[n]);		
		}
	}
}

// Change the status of a node(open or closed)
dTree.prototype.nodeStatus = function(status, id, bottom) {

   // identifica os objetos a serem manipulados
	eDiv	= document.getElementById('d' + this.obj + id);
	eJoin	= document.getElementById('j' + this.obj + id);
	if (this.config.useIcons) {
		eIcon	= document.getElementById('i' + this.obj + id);
		eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;
	}

   // mostra ou esconde o objeto
	eDiv.style.display = (status) ? 'block' : 'none';

   // redefine a imagem de maximização/minimização da opção
   window.setTimeout(
            "eJoin = document.getElementById('j" + this.obj + id + "');"
         +  "eJoin.src = " 
         +     "'"
         +     (  (this.config.useLines)
                  ?  (status)
                     ?  (bottom) 
                        ?  this.icon.minusBottom
                        :  this.icon.minus
                     :  (bottom) 
                        ?  this.icon.plusBottom
                        :  this.icon.plus
                  :  (status) 
                     ?  this.icon.nlMinus
                     :  this.icon.nlPlus
               )
         +     "'"
         +  ";"
   //      +  "alert(eJoin.src);"
      ,  200
   );

};


// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function() {
	var now = new Date();
	var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);

	if (String(this.parentForest) != "undefined")   {
	   this.setCookie('tv'+this.parentForest.obj, 'cookieValue', yesterday);
	}

	this.setCookie('co'+this.obj, 'cookieValue', yesterday);
	this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
	
};

// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {

	// identifica dados do cookie
	//sDadosCookie = document.cookie;
	if (String(top.dadosCookie) == "undefined") top.dadosCookie = "";

   // adiciona cookie
	document.cookie =
		escape(cookieName) + '=' + escape(cookieValue)
		+ (expires ? '; expires=' + expires.toGMTString() : '')
		+ (path ? '; path=' + path : '')
		+ (domain ? '; domain=' + domain : '')
		+ (secure ? '; secure' : '')
	;
	
	// remove repetição de variável
	sDadosRemover = "";
	var posName = sDadosCookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
	   top.dadosCookie = top.dadosCookie.replace(escape(cookieName) + "=" + escape(this.getCookie(cookieName)) + "; ", "");
	   top.dadosCookie = top.dadosCookie.replace(escape(cookieName) + "=" + escape(this.getCookie(cookieName)) + "\n", "");
	   top.dadosCookie = top.dadosCookie.replace(escape(cookieName) + "=" + escape(this.getCookie(cookieName)) + ";",  "");
	}

	// armazena dados no cookie
   if (cookieValue != "" && cookieValue != "cookieValue")   {
	   if (top.dadosCookie != "") top.dadosCookie += "; ";
      top.dadosCookie += escape(cookieName) + '=' + escape(cookieValue);
   }

   // realiza debug
   if (false)
   alert(
         "setCookie - fim"
      
      +  "\n"
      +  "\n" + "cookie"
      +  "\n" + top.dadosCookie
   
      +  "\n"
      +  "\n"
      +  escape(cookieName) + ' = ' + escape(cookieValue)
   );

};

// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function(cookieName) {
	
	// inicializa retorno
	var cookieValue = '';
	
	// identifica dados contidos do cookie
	//sDadosCookie = document.cookie;
	if (String(top.dadosCookie) == "undefined") top.dadosCookie = "";
	sDadosCookie = top.dadosCookie;
	
	// identifica o valor caso seja encontrado o cookie solicitado
	var posName = sDadosCookie.indexOf(escape(cookieName) + '=');
	if (posName != -1) {
		var posValue = posName + (escape(cookieName) + '=').length;
		var endPos = sDadosCookie.indexOf(';', posValue);
		if (endPos != -1) cookieValue = unescape(sDadosCookie.substring(posValue, endPos));
		else cookieValue = unescape(sDadosCookie.substring(posValue));
	}

   // realiza debug
   if (false)
   alert(
         "getCookie"
      +  "\n"
      +  "\n" + "cookie"
      +  "\n" + sDadosCookie
      +  "\n"
      +  "\ngetCookie( '" + escape(cookieName) + "' )"
      +  "\n" + cookieValue
   );
	
	// retorna
	return (cookieValue);
	
};

// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function() {
	var str = '';
	for (var n=0; n<this.aNodes.length; n++) {
		if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
			if (str) str += '.';
			str += this.aNodes[n].id;
		}
	}

	// altera dados de cookie de um subgrupamento de opções
	this.setCookie('co' + this.obj, str);
	
	// se os nódulos estiverem em um agrupamento principal, define o agrupamento ativo
	if (  String(this.parentContainer) != "undefined"
	   && this.visible
	   )   {
      this.setCookie('tv' + this.parentForest.obj, this.obj);
      this.parentForest.selectedTree = this.obj;
	}
	
};

// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function(id) {
	var aOpen = this.getCookie('co' + this.obj).split('.');
	for (var n=0; n<aOpen.length; n++)
		if (aOpen[n] == id) return true;
	return false;
};

// Returns if tree is visible
dTree.prototype.getVisible = function() {   
   var tv = this.visible;
   if (this.config.useCookies && String(this.parentForest) != "undefined")   {   
      var tAux = this.getCookie('tv' + this.parentForest.obj);
      return (tAux ? ((tAux == this.obj) ? true : false) : tv);
	}
	return tv;
};

// Turns tree visible
dTree.prototype.setVisible = function(status) {   
   var tv = this.obj;   
   this.visible = status;
   //alert('passando ' + this.obj  + ' para ' + status);
   //alert('selected Tree: ' + this.parentForest.selectedTree);
   if (this.config.useCookies && String(this.parentForest) != "undefined")   {
      
      // if closing, only change the status of selected tree
      if (status || this.parentForest.selectedTree == null || this.parentForest.selectedTree == this.obj) {
         this.setCookie('tv' + this.parentForest.obj, (status ? tv : ""));
         this.parentForest.selectedTree = (status) ? this.obj : "";
      }
   }
}

// If Push and pop is not implemented by the browser
if (!Array.prototype.push) {
	Array.prototype.push = function array_push() {
		for(var i=0;i<arguments.length;i++)
			this[this.length]=arguments[i];
		return this.length;
	}
};
if (!Array.prototype.pop) {
	Array.prototype.pop = function array_pop() {
		lastElement = this[this.length-1];
		this.length = Math.max(this.length-1,0);
		return lastElement;
	}
};

// Find node by ID
dTree.prototype.findNodeID = function(pID) {   
    for (this.iFindNode=0; this.iFindNode < this.aNodes.length; this.iFindNode++) {
        if (this.aNodes[this.iFindNode].id == pID) {
            return this.aNodes[this.iFindNode];
        }
    }
    return null;
}

// Find node by name
dTree.prototype.findNodeName = function(psName) {   
    for (this.iFindNode=0; this.iFindNode<this.aNodes.length; this.iFindNode++) {
        if (this.aNodes[this.iFindNode].name == psName) {
            return this.aNodes[this.iFindNode];
        }
    }
    return null;
}

// dForest object (array of trees)
function dForest(objName) {
	this.obj = objName;
	this.aTrees = [];
	this.selectedTree = null;
};

// Adds a new tree to the tree array
dForest.prototype.add = function(pTree) {
	this.aTrees[this.aTrees.length] = pTree;
};

// Return the tree by its name
dForest.prototype.getTree = function(pTreeName) {
   for (var n=0; n<this.aTrees.length; n++) {
      if (this.aTrees[n].obj == pTreeName)   {
         return (this.aTrees[n]);
      }
   }
   return null;
};

// Open or Close the first level of dTree
// (closing the others non selected)
dForest.prototype.clickTreeRoot = function(pTreeName) {
   
   var tree = this.getTree(pTreeName);
   
   //if (tree.visible) {
   if (false && tree.getVisible())   {
      tree.closeAll(true);
   }
   else  {
      // abre o agrupamento de opções solicitado
      tree.openLevel(0);
      
      // close others dTrees
      this.closeAllTrees(true, pTreeName);
   }   
};

// Close all trees (except pTreeName, if used)
dForest.prototype.closeAllTrees = function(bCloseContainer,pTreeName) {   
   var tree = null;
   
   // test treeName
   if (String(pTreeName) != "undefined") {
      tree = this.getTree(pTreeName);
   }
	for (var n=0; n<this.aTrees.length; n++) {
	   if (tree != null && this.aTrees[n].obj == tree.obj) {
	      continue;
	   }
	   this.aTrees[n].closeAll(bCloseContainer);
   }

};

// Open all trees
dForest.prototype.openAllTrees = function() {   
	for (var n=0; n<this.aTrees.length; n++) {
	   this.aTrees[n].openAll();
   }
};

// Find node by ID
dForest.prototype.findNodeID = function(pID, pbTree) {
    for (this.iFindNode=0; this.iFindNode < this.aTrees.length; this.iFindNode++) {
        hRet = this.aTrees[this.iFindNode].findNodeID(pID);
        if (hRet != null) {
            if (String(pbTree) == "true") 
                return this.aTrees[this.iFindNode];
            else
                return hRet;
        }
    }
    return null;
};

// Find node by name
dForest.prototype.findNodeName = function(psName, pbTree) {
    for (this.iFindNode=0; this.iFindNode < this.aTrees.length; this.iFindNode++) {
        hRet = this.aTrees[this.iFindNode].findNodeName(psName);
        if (hRet != null) {
            if (String(pbTree) == "true") 
                return this.aTrees[this.iFindNode];
            else
                return hRet;
        }
    }
    return null;
};
