/**
 * niv_tree.js
 *
 * 2001-10-31
 *   Centrado de texto e icono en los elementos del arbol
 * 2001-10-30 v1.1
 *   Aņadidos metodos para borrar y mapeo id(interno)<-->label(externo)
 *   Aņadidos metodos para seleccionar un nodo
 *   Aņadido metodos para insertar nodos en un arbol (runtime)
 */
var _tree_id = 0;
var _tTrees = new Array();
 
function tree(layerName) {
	//alert ('tree('+layerName+')');
	this.id = 'Tree_' + _tree_id++;
	this.treeLayer = xbGetElementById(layerName);
	this.treeStyleObj = new xbStyle(this.treeLayer);
	this.foldersTree = new Array ();
	this.nodeLabelIdMap = new Array ();
	this.selectedNode = null;
	this.selectedColor = '#FFFFFF';
	this.selectRow = false;
	
	this.rootCount = 0;
	this.keepSubOpen = false;
	this.showLeafIcon = false;
	this.blankImg = "";
	this.nodeWidth = 16;
	this.nodeHeight = 16;
	
	this.treeWidth = 0;

	this.rootSeparatorImg = null;
	this.rootSeparatorBackground = null;
	this.rootSeparatorHeight = 0;
	this.rootSeparatorWidth = 0;

	this.linkStyle = null;
	this.noLinkStyle = null;

	this.timeOutId = 0;
	
	_tTrees[this.id] = this;
	
	//alert ('tree('+layerName+') [id = ' + this.id + ', layer = ' + this.treeLayer + ', style = ' + this.treeStyleObj + ']');
}

tree.prototype.addRoot = tree_AddRoot;
tree.prototype.setRootSeparatorImg = tree_SetRootSeparatorImg;
tree.prototype.setRootSeparatorBackground = tree_SetRootSeparatorBackground;

tree.prototype.drawTree = tree_DrawTree;
tree.prototype.redrawTree = tree_RedrawTree;
tree.prototype.initializeTree = tree_InitializeTree;
tree.prototype.redrawTree = tree_RedrawTree;
tree.prototype.removeNodeById = tree_RemoveNodeById;
tree.prototype.removeNodeByLabel = tree_RemoveNodeByLabel;
tree.prototype.selectNodeById = tree_SelectNodeById;
tree.prototype.selectNodeByLabel = tree_SelectNodeByLabel;
tree.prototype.insertNodeAfterLabel = tree_InsertNodeAfterLabel;
tree.prototype.openBranch = tree_OpenBranch;

/**
 *
 */
function tree_AddRoot(newRoot) {
	this.foldersTree[this.foldersTree.length] = newRoot;
	newRoot.tree = this;
	newRoot.id = this.id + "_" + this.rootCount++;
	newRoot.root = newRoot;
	
	return newRoot;
}

/**
 *
 */
function tree_SetRootSeparatorImg(img, width, height) {
	//alert('SetRootSeparatorImg');
	this.rootSeparatorImg = img;
	this.rootSeparatorWidth = width;
	this.rootSeparatorHeight = height;
}	

/**
 *
 */
function tree_SetRootSeparatorBackground(img, width, height) {
	this.rootSeparatorBackground = img;
	this.rootSeparatorImg = '<img src="' + this.blankImg + '" width="' + width + '" height="' + height + '" border="0" alt="">';
	this.rootSeparatorWidth = width;
	this.rootSeparatorHeight = height;
}	

/**
 *
 */
function tree_DrawTree() {
//alert("drawTree()");
	var nodeText = "";
	for (i = 0; i < this.foldersTree.length; i++) {
		nodeText += this.foldersTree[i].draw(0, 1, "");
		
		// aņadimos separadores entre nodos raiz
		if (this.rootSeparatorImg && (i < (this.foldersTree.length - 1))) {
			nodeText += '<table boder="0" cellspacing="0" cellpadding="0">';
			nodeText += '<tr>';
			nodeText += '<td align="left" valign="top"';
			if (this.rootSeparatorBackground) {
				nodeText += ' background="' + this.rootSeparatorBackground + '"';	
			}
			nodeText += '>' + this.rootSeparatorImg + '</td>';
			nodeText += '</tr>';
			nodeText += '</table>';
		}
	}
	return nodeText;
}

function tree_RedrawTree() {
	var txt = this.drawTree();
	this.treeStyleObj.setInnerHTML(txt);
	// alert ('redrawTree() '+this.id+'\n'+txt);
	
	//document.forms["FRM"].TXT.value = txt;
}

/**
 *
 */
function tree_InitializeTree() {
	this.redrawTree();
}
/**
 *
 */
function tree_RemoveNodeById(id) {
	//alert("removeNodeById(" + id +")");
	for (i = 0; i < this.foldersTree.length; i++) {
		if (this.foldersTree[i].removeNodeById(id)) {
			break;
		}
	}

	timeOutId = setTimeout('redrawTree(\'' + this.id + '\')',100);
}

/**
 *
 */
function tree_RemoveNodeByLabel(label) {
	var id = this.nodeLabelIdMap[label];
	//alert("removeNodeByLabel(" + label +") id = " + id);
	
	this.removeNodeById(id);
}

/**
 *
 */
function tree_SelectNodeById(id) {
	//alert("selectNodeById(" + id +")");
	for (i = 0; i < this.foldersTree.length; i++) {
		if (this.foldersTree[i].selectNodeById(id)) {
			break;
		}
	}

	timeOutId = setTimeout('redrawTree(\'' + this.id + '\')',100);
}

/**
 *
 */
function tree_SelectNodeByLabel(label) {
	var id  = this.nodeLabelIdMap[label];
	this.selectNodeById(id);
	
}

/**
 * Metodos para insertado de un nuevo nodo en un arbol ya construido
 */
function tree_InsertNodeAfterLabel(parentLabel, insertPos, node) {
	//alert("insertNodeAfterLabel(" + parentLabel + ", " + insertPos + ", " + node +")");
	
	var parentId = this.nodeLabelIdMap[parentLabel];
	//alert (parentId);
	if (parentId) {
		for (i = 0; i < this.foldersTree.length; i++) {
			if (this.foldersTree[i].insertNodeAfterId(parentId, insertPos, node)) {
				break;
			}
		}
	}
	timeOutId = setTimeout('redrawTree(\'' + this.id + '\')',100);
}

/**
 *
 */
function tree_OpenBranch(branchName) {
	for (i = 0; i < this.foldersTree.length; i++) {
		if (this.foldersTree[i].clickOnFolder(branchName)) {
			break;
		}
	}

	timeOutId = setTimeout('redrawTree(\'' + this.id + '\')',100);
}

/******************************************************************************
 * Nodo rama.
 *
 *
 */
function folderNode(name, tooltip, link, targerFrame, icon, nodeImg, lastNodeImg, vertLineImg, plusImg, lastPlusImg, minusImg, lastMinusImg) {
	this.tree = null;
	this.id = null;
	this.label = null;
	this.name = name;
	this.link = link;
	if (tooltip) 
		this.tooltip = tooltip
	else	
		this.tooltip = name;
	this.targetFrame = targerFrame;
	this.icon = icon;
	this.selected = false;
	
	this.isAllwaysOpen = false;
	this.isAllwaysPlus = false;
	
	this.items = new Array ();
	this.itemCount = 0;
	this.isFolderOpen = false;
	
	this.nodeImg = nodeImg;
	this.lastNodeImg = lastNodeImg;
	this.vertLineImg = vertLineImg;
	this.plusImg = plusImg;
	this.lastPlusImg = lastPlusImg;
	this.minusImg = minusImg;
	this.lastMinusImg = lastMinusImg;
	
	this.leafImg = null;
	this.lastLeafImg = null;
}

folderNode.prototype.draw = drawFolder;
folderNode.prototype.insertChild = insertChild;
folderNode.prototype.appendChild = appendChild;
folderNode.prototype.clickOnFolder = clickOnFolderRec;
folderNode.prototype.closeFolders = closeFolders;
folderNode.prototype.removeNodeById = removeFolderNodeById;
folderNode.prototype.insertNodeAfterId = insertNodeAfterId;
folderNode.prototype.selectNodeById = selectFolderNodeById;
folderNode.prototype.isFolder = function() { return true; };
folderNode.prototype.setLabel = setNodeLabel;
/**
 *
 */
function drawFolder(level, isLastNode, leftSide, idc) {
	//alert ("drawFolder:" + this.name);
	var nodeText = '<table border="0" cellspacing="0" cellpadding="0"';
	if (this.tree.treeWidth) {
		nodeText += ' width="' + this.tree.treeWidth + '"';
	}
	if ((this == this.tree.selectedNode) && this.tree.selectRow && this.tree.selectedColor)
		nodeText += ' bgcolor="' + this.tree.selectedColor + '"';
	else
	  {
		if (flag)
	 {
	   flag = false;
	   nodeText += ' bgcolor="#edf1f5"';
	   // #EDF1E5
	 }
	 else
	 {
	   flag = true;
	   nodeText += ' bgcolor="#f6f9ff"';
	 }
	 };
	nodeText += '>';
	if ((this == this.tree.selectedNode) && this.tree.selectRow && this.tree.selectedColor)
		nodeText += Separador;
	nodeText += '<tr>';
	nodeText += leftSide;

	if (level > 0) {
		if (isLastNode) { //the last 'brother' in the children array
			leftSide += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top"><img src="' + this.tree.blankImg + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '"></td>';
		} else {
			leftSide += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top" background="' + this.vertLineImg + '"><img src="' + this.vertLineImg + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '"></td>';
		}
	}

	// Cuando el nodo raiz tiene definido un icono y siempre esta abierto colocamos el icono en vez del +
	if ((this == this.root) && (this.isAllwaysOpen)) {
		//alert (this.id);
	// Cuando es un nodo normal y tiene hijos o siempre esta abierto colocamos el +
	} else {
		if (level > 0) {
			if (isLastNode) { //the last 'brother' in the children array
				nodeText += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top"><img src="' + this.lastNodeImg + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '"></td>';
			} else {
				nodeText += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top" background="' + this.vertLineImg + '"><img src="' + this.nodeImg + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '"></td>';
			}
		}
		
		if ((this.items.length > 0) || this.root.isAllwaysPlus) {
			nodeText += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top"'
			if (this.isFolderOpen) {
				nodeText += ' background="' + this.vertLineImg + '"';
			}
			nodeText += '>';
			if ((this.items.length > 0) && !this.isAllwaysOpen) {
				nodeText += '<a href="javascript:openBranch(\'' + this.tree.id + '\', \'' + this.id + '\')" target="_self">';
			}	
			nodeText += '<img src=';
			if (this.isFolderOpen) {
				nodeText += '"' + (isLastNode?this.lastMinusImg:this.minusImg) + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '" border="0">';
			} else {
				nodeText += '"' + (isLastNode?this.lastPlusImg:this.plusImg) + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '" border="0">';
			}
			
			if ((this.items.length > 0) && !this.isAllwaysOpen) {
				nodeText += '</a>';
			}
			nodeText += '</td>';
		} else if ((this.items.length == 0) || this.tree.showLeafIcon) {
			nodeText += '<td width="' + this.tree.nodeWidth + '" align="left" valign="top"><img src="' + (isLastNode?this.lastLeafImg:this.leafImg) + '" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '" border="0"></td>';
		}
	}

	if (this.icon) {
		nodeText += '<td width="' + this.tree.nodeWidth + '"  align="left" valign="top"';
		if (this.link) {
			nodeText += '<a href="'+this.link+'"';
			if (this.targetFrame) {
				nodeText += ' target="' + this.targetFrame + '"';
			}
			nodeText += '>';
		}

		nodeText += '<img src="' + this.icon + '" alt="" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '" border="0">';
		if (this.link) {
			nodeText += '</a>';
		}
		nodeText += '</td>';
	}
	
	nodeText += '<td align="left" valign="top"';
	if (this.selected && this.tree.selectedColor) {
		nodeText += ' bgcolor="' + this.tree.selectedColor + '"';
	}
	if (this.link) {
		if (this.tree.linkStyle) { // Estilo de celda
			nodeText += ' class="' + this.tree.linkStyle + '"';	
		}
		nodeText += '><a href="'+this.link+'"';
		if (this.targetFrame) {
			nodeText += ' target="' + this.targetFrame + '"';
		}
		if (this.tree.linkStyle) { // Estilo de enlace
			nodeText += ' class="' + this.tree.linkStyle + '"';	
		}
	} else {
		if (this.tree.noLinkStyle) {
			nodeText += ' class="' + this.tree.noLinkStyle + '"';	
		}
	}
	nodeText += '><acronym title="';
	nodeText += this.tooltip;
	nodeText += '">';
	nodeText += this.name;
	nodeText += '</acronym>';

	if (this.link) {
		nodeText += '</a>';
	}
	nodeText += '</td></tr>';
	if ((this == this.tree.selectedNode) && this.tree.selectRow && this.tree.selectedColor)
		nodeText += Separador;
	nodeText += '</table>';
	//alert ("Folder Drawed:" +this.items.length + "- " + this.isFolderOpen);
	//there are sub-nodes and the folder is open
	if ((this.items.length) > 0 && (this.isFolderOpen || this.isAllwaysOpen))	{
		var i;
		for (i = 0; i < this.items.length; i++) {
			if (i == (this.items.length-1)) {
				nodeText += this.items[i].draw(level+1, true, leftSide,i);
			} else {
				nodeText += this.items[i].draw(level+1, false, leftSide,i);
			}
		}
	}
	
	//alert (nodeText);
	
	return nodeText;
}

/**
 *
 */
function insertChild(child, position) {
	//alert('insertChild('+child+', '+position+')');
	
	child.tree = this.tree;
	child.id = this.id + "_" + this.itemCount++;
	child.parent = this;
	child.root = this.root;
	this.items[position] = child;
	
	
	// Inicializamos las imagenes de estructura
	if(!child.nodeImg) {
		child.nodeImg = this.nodeImg;
	}
	if(!child.lastNodeImg) {
		child.lastNodeImg = this.lastNodeImg;
	}
	if(!child.vertLineImg) {
		child.vertLineImg = this.vertLineImg;
	}
	if(!child.plusImg) {
		child.plusImg = this.plusImg;
	}
	if(!child.lastPlusImg) {
		child.lastPlusImg = this.lastPlusImg;
	}
	if(!child.minusImg) {
		child.minusImg = this.minusImg;
	}
	if(!child.lastMinusImg) {
		child.lastMinusImg = this.lastMinusImg;
	}

	if(!child.leafImg) {
		child.leafImg = this.leafImg;
	}
	if(!child.lastLeafImg) {
		child.lastLeafImg = this.lastLeafImg;
	}
	
	return child
}

/**
 *
 */
function appendChild(child){
	return this.insertChild (child, this.items.length);
}

/**
 *
 */
function removeFolderNodeById(id) {
	//alert("removeFolderNodeById (" + id + ")");

    if (this.id == id) {
		if (this.selected) {
			this.selected = false;
			this.tree.selectedNode = null;
		}
		return true;
	} else {
		if (id.indexOf(this.id) == 0) {
			var i;
			for (i = 0; i < this.items.length; i++) {
				if (this.items[i].isFolder()) {
					if (this.items[i].removeNodeById(id)) {
						this.items.splice(i, 1);
						if (this.items.length == 0) {
							this.isFolderOpen = false;
						}
						return false;
					}
				}
			}
		}
	}
	return false;
}

/**
 *
 */
function closeFolders() {
    var i = 0;
	if (!this.tree.keepSubOpen) {
	    for (i = 0; i < this.items.length; i++) {
			if (this.items[i].isFolder()) {
			    this.items[i].closeFolders();
			}
		}
	}
    this.isFolderOpen = false;
}

/**
 *
 */
function setNodeLabel (label) {
	//alert('setNodeLabel ('+label+') [this.id = '+this.id+', this.tree = '+this.tree+']');
	this.label = label;
	this.tree.nodeLabelIdMap[label] = this.id;
}
/**
 *
 */
function clickOnFolderRec(id) {
	//alert(this.name + " [" + this.isFolderOpen + "] - " + folderName);
    if (this.id == id) {
		if (this.isFolderOpen) {
			this.closeFolders()
			return true;
		} else {
			//alert ("Folder Clicked:" + this.name);
			this.isFolderOpen = true;
			return true;
		}
	} else {
		if (id.indexOf(this.id) == 0) {
			var i;
	      	for (i = 0; i < this.items.length; i++) {
				if (this.items[i].isFolder()) {
	    	      	if (this.items[i].clickOnFolder(id)) {
						return true;
					}
				}
			}
		}
	}
	return false;
}

/**
 *
 */
function selectFolderNodeById(id) {
	//alert("selectNodeAfterId(" + id +")");

    if (this.id == id) {
		if (this.tree.selectedNode) {
			this.tree.selectedNode.selected = false;
		}
		this.selected = true;
		this.tree.selectedNode = this;
		this.isFolderOpen = true;
		return true;
	} else {
		if (id.indexOf(this.id) == 0) {
			var i;
			for (i = 0; i < this.items.length; i++) {
				if (this.items[i].selectNodeById(id)) {
					this.isFolderOpen = true;
					return true;
				}
			}
		}
	}
	return false;
}

/**
 *
 */
function insertNodeAfterId(parentId, insertPos, node) {
	//alert("insertNodeAfterId(" + parentId + ", " + previousId + ", " + node +")");

    if (this.id == parentId) {
		if (insertPos == -1) {
			insertPos = this.items.length;
		}
		
		var i;
		for (i = this.items.length; i > insertPos; i--) {
			this.items[i] = this.items[i-1];
		}
		this.insertChild(node, insertPos);
		this.isFolderOpen = true;
		return true;
	} else {
		if (parentId.indexOf(this.id) == 0) {
			var i;
			for (i = 0; i < this.items.length; i++) {
				if (this.items[i].isFolder()) {
					if (this.items[i].insertNodeAfterId(parentId, insertPos, node)) {
						return true;
					}
				}
			}
		}
	}
	return false;
}

/******************************************************************************
 * Nodo hoja.
 *
 *
 */
function leafNode(name, link, targerFrame, icon) {
	this.tree = null;
	this.id = null;
	this.label = null;
	this.name = name
	this.link = link;
	this.targetFrame = targerFrame;
	this.icon = icon;
	this.selected = false;
}
leafNode.prototype.draw = drawLeaf;
leafNode.prototype.removeNodeById = removeLeafNodeById;
leafNode.prototype.selectNodeById = selectLeafNodeById;
leafNode.prototype.isFolder = function() { return false; };
leafNode.prototype.setLabel = setNodeLabel;


/**
 *
 */
function drawLeaf(level, lastNode, leftSide) {
	var nodeText = "<table border=0 cellspacing=0 cellpadding=0>";
	nodeText += "<tr><td valign = middle nowrap>";

	nodeText += leftSide;

	if (level > 0) {
		if (lastNode) { //the last 'brother' in the children array
			nodeText += "<img src='" + this.lastNodeImg + "' width=" + this.tree.nodeWidth + " height=" + this.tree.nodeHeight + ">";
			leftSide += "<img src='" + this.tree.blankImg + "' width=" + this.tree.nodeWidth + " height=" + this.tree.nodeHeight + ">";
		} else {
			nodeText += "<img src='" + this.nodeImg + "' width=" + this.tree.nodeWidth + " height=" + this.tree.nodeHeight + ">";
			leftSide += "<img src='" + this.vertLineImg + "' width=" + this.tree.nodeWidth + " height=" + this.tree.nodeHeight + ">";
		}
	}

	nodeText += '<a href="' + this.link + '"';
	if (this.targetFrame) {
		nodeText += ' target="' + this.targetFrame + '"';
	}
	nodeText += '><img src="' + this.icon + '" alt="" width="' + this.tree.nodeWidth + '" height="' + this.tree.nodeHeight + '" border=0></a></td>';
	nodeText += '<td nowrap';
	if (this.selected) {
		nodeText += ' bgcolor="' + this.tree.selectedColor + '"';
	}
	nodeText += '>';
	
	nodeText += '<a name="' + this.id + '"></a>';
	
	nodeText +='<a href="' + this.link +'"';
	if (this.targetFrame) {
		nodeText += ' target="' + this.targetFrame + '"';
	}
	nodeText += '>' + this.name + '</a>';
	
	nodeText += '</td></tr>';
	nodeText += '</table>';
	return nodeText

}

/**
 *
 */
 function selectLeafNodeById(id) {
	//alert("selectLeafNodeById (" + id + ")");

    if (this.id == id) {
		if (this.tree.selectedNode) {
			this.tree.selectedNode.selected = false;
		}
		this.selected = true;
		this.tree.selectedNode = this;
		return true;
	}
	
	return false;
}

/**
 *
 */
function removeLeafNodeById(id) {
	//alert("removeLeafNodeById (" + id + ")");

    if (this.id == id) {
		if (this.selected) {
			this.selected = false;
			this.root.selectedNode = null;
		}
		return true;
	}
	
	return false;
}
/******************************************************************************
 *
 * 
 */
 
function redrawTree(treeId) {
	//alert('redrawTree(' + treeId + ')');
	_tTrees[treeId].redrawTree();
}
function openBranch(treeId, branchName) {
	//alert("openBranch(" + branchName +")");
	_tTrees[treeId].openBranch(branchName);
}

