/*
    Copyright (c) 2001 Geir Landrö (drop@destroydrop.com)
    JavaScript Tree - www.destroydrop.com/hugi/javascript/tree/
    Version 0.96

    This script can be used freely as long as all copyright messages are intact.

    Adaptado por Consist para Consist Content Manager
*/

// Push and pop not implemented in IE(crap! don´t know about NS though)
if (!Array.prototype.push)
{
    function array_push()
    {
        for (var i = 0; i < arguments.length; i++)
            this[this.length] = arguments[i]
        return this.length
    }
    Array.prototype.push = array_push
}

if (!Array.prototype.pop)
{
    function array_pop()
    {
        lastElement = this[this.length - 1]
        this.length = Math.max(this.length - 1,0)
        return lastElement
    }
    Array.prototype.pop = array_pop
}

function Canal(codigo, padre, desc, link, destino, destino2, imgCanal,nivel)
{
    this.codigo = codigo
    this.padre = padre
    this.desc = desc
    this.link = link
    this.destino = destino
    this.destino2 = destino2
    this.imgCanal = imgCanal
    this.nivel = nivel

    // Beto: mantenimiento de referencias
	
	// Las mismas tienen sentido solo cuando el canal forma parte del arbol
	// Algunos canales pueden no tener padre
	// Los canales pueden no tener hijos

	this.refsAreInitialized = false;    // Indica si el las referencias a canales padre e hijos estan inicializadas
	this.parentRef = null;              // Referencia directa al (posible) canal padre
    this.childrenRefs = null;           // Referencias directas a los (posibles) canales hijos

    // Fin agregado
}

// Loads all icons that are used in the tree
function preloadIcons()
{
    this.icons[0] = new Image()
    this.icons[0].src = this.imgPlus
    this.icons[1] = new Image()
    this.icons[1].src = this.imgPlusBottom
    this.icons[2] = new Image()
    this.icons[2].src = this.imgMinus
    this.icons[3] = new Image()
    this.icons[3].src = this.imgMinusBottom
    this.icons[4] = new Image()
    this.icons[4].src = this.imgFolder
    this.icons[5] = new Image()
    this.icons[5].src = this.imgFolderOpen
}

// Create the tree
function Arbol(nombre, array, raiz, div, abiertos)
{
    // Funciones
    this.preloadIcons = preloadIcons
    this.getArrayId = getArrayId
    this.setOpenNodes = setOpenNodes
    this.isNodeOpen = isNodeOpen
    this.hasChildNode = hasChildNode
    this.lastSibling = lastSibling
    this.addNodes = addNodes                      // Beto: Se cambio el nombre original (addNode)
    this.removeOpenNodes = removeOpenNodes

    // Constantes
    this.leyenda = "" // "Abrir o cerrar nodo"
    this.baseImg = "/pub2/PublicNew/arbolTop/img"
    this.imgBase1 = this.baseImg + "/base1.gif"
    this.imgEmpty = this.baseImg + "/empty.gif"
    this.imgFolder = this.baseImg + "/folder.gif"
    this.imgFolderOpen = this.baseImg + "/folderopen.gif"
    this.imgJoin = this.baseImg + "/join.gif"
    this.imgJoinBottom = this.baseImg + "/joinbottom.gif"
    this.imgLine = this.baseImg + "/line.gif"
    this.imgMinus = this.baseImg + "/minus.gif"
    this.imgMinusBottom = this.baseImg + "/minusbottom.gif"
    this.imgPage = this.baseImg + "/page.gif"
    this.imgPlus = this.baseImg + "/plus.gif"
    this.imgPlusBottom = this.baseImg + "/plusbottom.gif"

    // Atributos
    this.nombre = nombre
    this.recursedNodes = new Array()
    this.icons = new Array(6)
    this.nodes = array
    this.div = div
    this.cadena = new Array()    // Beto: se reemplazo por un array, para eliminar problemas de
	                             //       performance en al concatenacion de strings
   
    // Constructor
    if (abiertos != null)
	{
        this.openNodes = abiertos
	}
    else
        this.openNodes = new Array()

    this.preloadIcons()
    //this.cadena.push("<img src='" + this.imgBase1 + "' align='absbottom' alt=''/>" + raiz + "<br/>")

    // Beto: inicializacion de referencias

    // Recorre el arreglo de nodos (en base al codigo de canal) buscando el padre de cada uno de ellos.
	// Si existe el padre, inicializa la referencia al mismo. Ademas, si el padre no tiene inicializada
	// las referencias a sus hijos, crea el arreglo de los mismos. Finalmante, se agrega a dicho arreglo.
	// Es posible que el nodo en cuestion no tenga padre.

	// Si el nodo ya esta inicializado, no se realiza ninguna operacion.

    for (var i = 0; i < this.nodes.length; i++)
	   if (!this.nodes[i].refsAreInitialized)
        {
			var isSet = false
			var k = 0;
			while (!isSet && k < this.nodes.length)
			 if (this.nodes[i].padre == this.nodes[k].codigo) {
				this.nodes[i].parentRef = this.nodes[k]

				if (this.nodes[k].childrenRefs == null)
				   this.nodes[k].childrenRefs = new Array()
				this.nodes[k].childrenRefs.push(this.nodes[i])

				   isSet = true;
			   }
			   else
				  k++

			this.nodes[i].refsAreInitialized = true
		}

   // Fin agregado

   // Beto: crear un arreglo de canales sin padre para iniciar
   // el proceso recursivo de armado del arbol

   var orphanNodes = new Array()
   for (var i = 0; i < this.nodes.length; i++)
      if (this.nodes[i].parentRef == null)
	    {
        orphanNodes.push(this.nodes[i])
        }
		
   // Fin agregado

   this.addNodes(orphanNodes) 
   this.div.innerHTML = this.cadena.join("")
}

// Returns the position of a node in the array
function getArrayId(node)
{
    for (i = 0; i < this.nodes.length; i++)
    {
        if (this.nodes[i].codigo == node)
            return i
    }
}

// Puts in array nodes that will be open
function setOpenNodes(openNode)
{
    for (var i = 0; i < this.nodes.length; i++)
    {
        var codigo = this.nodes[i].codigo
        var padre = this.nodes[i].padre
        if (codigo == openNode)
        {
            this.openNodes.push(codigo)
            //this.openNodes.push(padre)
            this.setOpenNodes(padre)
        }
    }
}

function removeOpenNodes(openNode)
{
    var nuevo = new Array()
    for (var i = 0; i < this.openNodes.length; i++)
    {
        if (this.openNodes[i] != openNode)
        {
            nuevo.push(this.openNodes[i])
        }
    }
    this.openNodes = nuevo
}

// Checks if a node is open
function isNodeOpen(node)
{
    for (i = 0; i < this.openNodes.length; i++)
    {
        if (this.openNodes[i] == node)
            return true
    }
    return false
}

// Checks if a node has any children
function hasChildNode(parentNode)
{
    for (i = 0; i < this.nodes.length; i++)
    {
        if (this.nodes[i].padre == parentNode)
            return true
    }
    return false
}

// Checks if a node is the last sibling
function lastSibling (node, parentNode)
{
    var lastChild = 0
    for (i = 0; i < this.nodes.length; i++)
    {
        var codigo = this.nodes[i].codigo
        var padre = this.nodes[i].padre
        if (padre == parentNode)
            lastChild = codigo
    }
    if (lastChild == node)
        return true
    else
        return false
}

// Adds a new node in the tree
function addNodesOld(parentNodes)  // POR COLUMNAS



// Beto: Se cambio el nombre original (addNode)
//       parentNodes representa todos los nodos sin padre o todos los hijos de un mismo padre

{


    // Recorre el vector de nodos padres
			 var col = Math.round((parentNodes.length / 7))
			col = col + 1
    for (var i = 0; i < parentNodes.length; i++)  
    {
			
		resto = ((i+1) % col)	

        var codigo = parentNodes[i].codigo
        var padre = parentNodes[i].padre
        var desc = parentNodes[i].desc
        var link = parentNodes[i].link
        var destino = parentNodes[i].destino
        var destino2 = parentNodes[i].destino2
        var imgCanal = parentNodes[i].imgCanal


		var ls = parentNodes.length -1 == i               // Es el ultimo hijo ?

		var hcn = parentNodes[i].childrenRefs != null     // Tiene hijos ?

		
		var ino = this.isNodeOpen(codigo)                 

		
		
		// put in array line & empty icons
		if (ls)
			this.recursedNodes.push(false)
		else
			this.recursedNodes.push(true)


		if ( padre!="")
		{	
				//	this.cadena.push("<pre>")
			this.cadena.push("<td height='14' >")
			this.cadena.push("<a   href='" + link + "' target='" + destino + "'>")	
		}


		// Write out node name
		if (hcn)
			var style = "style='font-weight: bold'"
		else
			var style = ""

		if ( padre!="")
		{			
			this.cadena.push("<span class='linksmenuprincipal' " + style + " >" + desc + "</span>")
			this.cadena.push("</a>")
			this.cadena.push("</td>")	

			if ((i!=0) && (resto==0))
			{
			  this.cadena.push("</tr>")
			  this.cadena.push("<tr>")
			}

		}

		// If node has children write out divs and go deeper
		if (hcn)
		{
			if (!ino)
				var style = "style='display: none'"

			this.cadena.push("<div class='linksmenuprincipal' id='" + this.nombre + "." + codigo + ".div' " + style + " >")			
			this.cadena.push("<table width='616' border='0' cellspacing='0' cellpadding='0'>")
			

			if ((i==0) || (resto==0))
			{
			  this.cadena.push("<tr>")
			}
			this.addNodes(parentNodes[i].childrenRefs)   // Beto: Se cambio la invocacion original
				
			if (i==(parentNodes.length - 1))
			{
				if ((i==0) || (resto==0))
				{
				  this.cadena.push("</tr>")
				}
			}			
				
			this.cadena.push("</table>")
			this.cadena.push("</div>")			       

		}
         
		// remove last line or empty icon
		this.recursedNodes.pop()

    }
}
//
// Opens or closes a node
function oc(nombre, node, bottom, estado, array)
{
    var arbol = eval(nombre)
    var theDiv = document.getElementById(nombre + "." + node + ".div")
    var theJoin = document.getElementById(nombre + "." + node + ".join")

    

    if (theDiv.style.display == 'none')
		{
        theDiv.style.display = ''
        arbol.setOpenNodes(node)
    }
    else
    {
        theDiv.style.display = 'none'
        arbol.removeOpenNodes(node)
    }

}

function cargaIFrame(strTarget, strHref)
{
	window.parent.document.getElementById(strTarget).src = strHref;
}

function cambiar(destino, destino2, link, imgCanal, codigo)
{
	if (destino != "null")
	{
	    var imagenCargada="imag" + codigo;
		var img=document.getElementById(imagenCargada); 

		//img.src=imgCanal;
	
		window.parent.document.getElementById(destino).src = link;

		if(img.complete && window.parent.document.getElementById(destino2))
	      {
	  
	  	  window.parent.document.getElementById(destino2).src = imgCanal;
		  }
		else
			if(window.parent.document.getElementById(destino2)) 
			{
				 window.parent.document.getElementById(destino2).src = "/pub2/PublicNew/img/pix_trans.gif";
			}
	}
}

function handOver(obj)
{
	obj.style.cursor = "hand";
}



// Adds a new node in the tree
function addNodes(parentNodes)   // POR FILAS
{
   // Recorre el vector de nodos padres
   // var col = Math.round((parentNodes.length / 7))
   // col = col + 1

// calcula a largura das colunas - ctlgm - 19/03/2007 -  inicio

	var maiorTitulo = 0;
    	for (var i = 0; i < parentNodes.length; i++)  
	{
		if (parentNodes[i].desc.length > maiorTitulo)
			maiorTitulo = parentNodes[i].desc.length;	
	}
	var largura = 616;
	if (parentNodes[0].padre == "Univ" || parentNodes[0].padre == "Corp" || parentNodes[0].padre == "rhnet")
		largura = 154; 
//	this.cadena.push(location.href);
//	largura = document.body.width;
	var maiorTamTitulo = (maiorTitulo) * 8  // Mult. numero de caracteres pelo tamamnho deles, definido no arbolTop.css
	var qtdColunas = Math.round(largura / maiorTamTitulo);
	var itensPorColuna = Math.round(parentNodes.length / qtdColunas + 0.5);
	if ((parentNodes.length) <= (itensPorColuna * (qtdColunas-1)))
		qtdColunas = qtdColunas - 1;
	var tamCelula = largura / qtdColunas; 
//		this.cadena.push("<font size='1'>" + largura + " - " + maiorTitulo + " - " + maiorTamTitulo + " -  " + qtdColunas + " - " + itensPorColuna + "</font>");	

// calcula a largura das colunas - ctlgm - 19/03/2007 -  fim 

	this.cadena.push("<table cellpadding='0' cellspacing='0' valign='top' border='0'>")
    this.cadena.push("<tr>")
	this.cadena.push("<td valign='top'>")
	this.cadena.push("<table width='" + tamCelula + "' cellpadding='0' cellspacing='0' valign='top' border='0'>")
    var j = 0;
    for (var i = 0; i < parentNodes.length; i++)  
    {
        j = j + 1; 
        if (j > itensPorColuna)
        {
        j = 1; 
		this.cadena.push("</table>")
		this.cadena.push("</td>")
        this.cadena.push("<td valign='top' />")
		this.cadena.push("<table width='" + tamCelula  + "'cellpadding='0' cellspacing='0' valign='top' border='0'>")

        }

		this.cadena.push("<tr>")
		this.cadena.push("<td height='14'>")
			
		//resto = ((i+1) % col)	
		resto = parentNodes.length - i

        var codigo = parentNodes[i].codigo
        var padre = parentNodes[i].padre
        var desc = parentNodes[i].desc
        var link = parentNodes[i].link
        var destino = parentNodes[i].destino
        var destino2 = parentNodes[i].destino2
        var imgCanal = parentNodes[i].imgCanal
		var nivel = parentNodes[i].nivel

		var ls = parentNodes.length -1 == i               // Es el ultimo hijo ?

		var hcn = parentNodes[i].childrenRefs != null     // Tiene hijos ?

		
		var ino = this.isNodeOpen(codigo)                 

		
		
		// put in array line & empty icons
		if (ls)
			this.recursedNodes.push(false)
		else
			this.recursedNodes.push(true)


		if ( padre!="")
		{	
				//	this.cadena.push("<pre>")
		//	this.cadena.push("<td height='14' >")
//		    if (i>=itensPorColuna)
//		    {
//				this.cadena.push("<img src='/pub2/PublicNew/img/pix_trans.gif' width='10' height='1' />")
//		    }
			this.cadena.push("<a   href='" + link + "' target='" + destino + "'>")	
		}


		// Write out node name
		if (hcn)
			var style = "style='font-weight: bold'"
		else
			var style = ""
	
		if ( padre!="")
		{	
			this.cadena.push("<span class='linksmenuprincipal' " + style + " >" + desc + "</span>")
			this.cadena.push("</a>")
			this.cadena.push("</td>")	

			//if ((i!=0) && (resto==0))
			//{
			  this.cadena.push("</tr>")
			  this.cadena.push("<tr>")
			//}

		}


		// If node has children write out divs and go deeper
		if (nivel == 1)
		{
		if (hcn)
		{
			if (!ino)
				var style = "style='display: none'"

			this.cadena.push("<div class='linksmenuprincipal' id='" + this.nombre + "." + codigo + ".div' " + style + " >")			
			this.cadena.push("<table width='100' border='0' cellspacing='0' cellpadding='0'>")
			

			if ((i==0) || (resto==0))
			{
			  this.cadena.push("<tr>")
			}
			this.addNodes(parentNodes[i].childrenRefs)   // Beto: Se cambio la invocacion original
				
			if (i==(parentNodes.length - 1))
			{
				if ((i==0) || (resto==0))
				{
				  this.cadena.push("</tr>")
				}
			}			
				
			this.cadena.push("</table>")
			this.cadena.push("</div>")			       

		}
		}
         
		// remove last line or empty icon
		this.recursedNodes.pop()

    }

			this.cadena.push("</table>")
			this.cadena.push("</td>")	

}

