// Funciones para la creación de árboles javascript
// Creadas con DOM

// A continuación se configuran las imágenes para abrir o cerrar los nodos
var DIR_IMAGES = "img/arbol/";
var IMAGEN_CERRADO = DIR_IMAGES + "flecha1.gif";
var IMAGEN_ABIERTO = DIR_IMAGES + "flecha1a.gif";
var IMAGEN_TRANS = DIR_IMAGES + "trans[5].gif";

var imgCerrado = new Image();
imgCerrado.src = IMAGEN_CERRADO;
var imgAbierto = new Image();
imgAbierto.src = IMAGEN_ABIERTO;

var arboles = new Array;

var ancho_indentado = 18;

//-----------------------------------------------------------------
// Constructor de arbol
//-----------------------------------------------------------------
//
// Descripción
//  Esta función encapsula las propiedades básicas del árbol
//
// Parámetros
//   nombreArbol - nombre del árbol
//-----------------------------------------------------------------
function arbol(nombreArbol) {

    this.raiz = null;
    this.nodos = new Array;     //array for all nodos in the tree

    arboles[nombreArbol] = this;
}

//-----------------------------------------------------------------
// Método arbol.creaRaiz()
//-----------------------------------------------------------------
// Descripción
//  Este método crea la raíz del árbol. La raíz es vacía (es sólo para
//  contener a los otros nodos)
//
// Parámetros
//  nombreArbol (string) - Nombre del arbol.
//-----------------------------------------------------------------
arbol.prototype.creaRaiz = function(nombreArbol) {

    this.raiz = new nodoArbol("","");

    // Se le asigna un id al nodo para identificarlo
    this.raiz.id = nombreArbol;

    // Se añade al array de nodos
    this.nodos[nombreArbol] = this.raiz;

    // Se pone como abierto
    this.raiz.abierto = true;

    return this.raiz;
}

//-----------------------------------------------------------------
// Método arbol.construyeDOM()
//-----------------------------------------------------------------
// Descripción
//  Esta función construye el DOM.
//-----------------------------------------------------------------
arbol.prototype.construyeDOM = function(elementoPadre, nombreArbol) {

    //Anyade la raiz al documento y luego se llama recursivamente
    this.raiz.anyadeDOM(elementoPadre, nombreArbol);
}

//-----------------------------------------------------------------
// Método arbol.cerrojo()
//-----------------------------------------------------------------
// Descripción
//  Realiza la abertura/cierre de los hijos de un nodo del árbol
//
// Parámetros
//  idNodo (string) - el identificador del nodo que se abre/cierra.
//-----------------------------------------------------------------
arbol.prototype.cerrojo = function(idNodo) {

    // obtenemos el nodo del conjunto
    var nodo = this.nodos[idNodo];

    // se abre o cierra según corresponda
    if (nodo.abierto)
        nodo.cierra();
    else
        nodo.abre();
}


arbol.prototype.cierraTodo = function() {
    for (var i=0; i < this.raiz.nodosHijos.length; i++)
		this.raiz.nodosHijos[i].cierraTodo();
}

nodoArbol.prototype.cierraTodo = function() {
    for (var i=0; i < this.nodosHijos.length; i++)
		this.nodosHijos[i].cierraTodo();
	if (this.nodosHijos.length !=0) this.cierra();
}

/*Esta funcion despliega totalmente el arbol pintado.*/

arbol.prototype.abreTodo = function() {
    for (var i=0; i < this.raiz.nodosHijos.length; i++)
		this.raiz.nodosHijos[i].abreTodo();
}

nodoArbol.prototype.abreTodo = function() {
    for (var i=0; i < this.nodosHijos.length; i++)
		this.nodosHijos[i].abreTodo();
	if (this.nodosHijos.length !=0) this.abre();
}


//-----------------------------------------------------------------
// Constructor de nodoArbol
//-----------------------------------------------------------------
// Descripción
//  Este objeto contiene la información de los distintos nodos
//
// Parámetros
//  icono (string) - icono del nodo
//  texto (string) - texto (HTML) del nodo
//-----------------------------------------------------------------
function nodoArbol(icono, pk, texto,nivel) {

    this.icono = icono;
    this.texto = texto;
    this.pk=pk;
    this.nivel=nivel;

    this.indentado = 0;                // indentación

    this.abierto = true;

    this.nodosHijos = new Array;    // nodos hijos
}

//-----------------------------------------------------------------
// Método nodoArbol.anyadeHijo()
//-----------------------------------------------------------------
// Descripción
//  Añade un hijo al nodo.
//
// Parámetros
//  icono (string) - icono del nodo.
//  texto (string) - texto del nodo.
//  nombre (string) - nombre del árbol. Necesario para permitir varios árboles
//  				  por página.
//
// Devuelve
//  El nodoArbol creado.
//-----------------------------------------------------------------
nodoArbol.prototype.anyadeHijo = function (icono, pk, texto, nombre,nivel) {

    var nodo = new nodoArbol(icono,pk,texto,nivel);

    // le asignamos un id
    nodo.id = this.id + "_" + this.nodosHijos.length;

    // le asignamos la indentación (nivel siguiente al actual)
    nodo.indentado = this.indentado + 1;

    // lo añadimos al array de hijos
    this.nodosHijos[this.nodosHijos.length] = nodo;

    // lo añadimos al array de nodos
    arboles[nombre].nodos[nodo.id] = nodo;

    return nodo;
}

//-----------------------------------------------------------------
// Método nodoArbol.anyadeDOM(nombre)
//-----------------------------------------------------------------
// Descripción
//  Se añaden elementos DOM a otro padre
//
// Parámetros
//  objDOMParent (HTMLElement) - Elemento DOM padre.
//  nombreArbol (string) - nombre del árbol. Necesario para permitir
//						   varios árboles por página
//
//-----------------------------------------------------------------
nodoArbol.prototype.anyadeDOM = function (objDOMParent, nombreArbol) {

    // se crea una capa para el nodo
    var nodoDiv = document.createElement("div");

    // se añade al padre
    objDOMParent.appendChild(nodoDiv);

    // se crea el buffer para la salida del HTML desde javascript
    var d = new documentoJavaScript;

    // comienzo de la tabla
    d.println("<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>");

    // no hay indentación para la raíz
    if (this.indentado > 1) {
        d.print("<td width=\"");
        d.print(this.indentado * ancho_indentado);
        d.print("\">&nbsp;</td>");
    }

    // la raíz no se abre/cierra (siempre abierta y, en este caso, no presente)
    if (this.indentado > 0) {

        d.print("<td align=\"left\">");

        // si tiene hijos se pone la imagen de abrir/cerrar
        if (this.nodosHijos.length > 0) {
            d.print("<a href=\"javascript:arboles['"+nombreArbol+"'].cerrojo('");
            d.print(this.id);
            d.print("')\"><img src=\"");
            d.print(this.abierto ? imgAbierto.src : imgCerrado.src);
            d.print("\" border=\"0\" alt=\"abre-cierra\" hspace=\"0\" id=\"");
            d.print("imgPM_" + this.id);
            d.print("\" /></a>");
        }

        d.print("</td>");
    }

// No dibujamos el nodo padre. Si se quisiera dibujar habrá que cambiar este
// if, así como la función de creación de la raíz.
if (this.indentado != 0)
{
    if(this.nivel== '1' || this.nodosHijos.length > 0)
      d.print("<td width=\"6\" align=\"left\">" + "<img hspace=\"0\" src=\"" + this.IMAGEN_TRANS + "\" id=\"icon_" + this.id + "\" border=\"0\" align=\"absmiddle\" width=\"6\" heigth=\"2\" /></td>");
    else
      d.print("<td width=\"6\" align=\"left\">" + "<img hspace=\"0\" src=\"" + this.icono + "\" id=\"icon_" + this.id + "\" border=\"0\" align=\"absmiddle\" /></td>");


    d.print("<td align=\"left\" nowrap=\"nowrap\">" + "<font id=\"fontValoresDatos\">" + this.texto + "</font></td>");
    d.println("</tr></table>");
}
    // metemos el HTML en la capa
    nodoDiv.innerHTML = d;

    // creamos la capa para los hijos
	if (this.nodosHijos.length > 0)
	{
		var objChildnodosLayer = document.createElement("div");
		objChildnodosLayer.setAttribute("id", "divChildren_" + this.id);
		objChildnodosLayer.style.position = "relative";
		objChildnodosLayer.style.display = (this.abierto ? "block" : "none");
		nodoDiv.appendChild(objChildnodosLayer);
	}
    // llamada recursiva a los hijos
    for (var i=0; i < this.nodosHijos.length; i++)
        this.nodosHijos[i].anyadeDOM(objChildnodosLayer, nombreArbol);
}

//-----------------------------------------------------------------
// Método nodoArbol.cierra()
//-----------------------------------------------------------------
//
// Descripción
//  Este método cierra y oculta los nodos hijo de un nodo.
//-----------------------------------------------------------------
nodoArbol.prototype.cierra = function () {

    // Comprobacion de que no está ya cerrado (caso imposible)
    if (!this.abierto) {
//         throw "Nodo ya cerrado"
    } else {
        this.abierto = false;

        // Cambiamos la imagen a la de abierto
        document.images["imgPM_" + this.id].src = imgCerrado.src;

		// Ocultamos los hijos
        document.getElementById("divChildren_" + this.id).style.display = "none";
    }
}


//-----------------------------------------------------------------
// Método nodoArbol.abre()
//-----------------------------------------------------------------
//
// Descripción
//  Este método abre y muestra los nodos hijo de un nodo.
//-----------------------------------------------------------------
nodoArbol.prototype.abre = function () {

    // Comprobacion de que no está ya abierto (caso imposible)
    if (this.abierto) {
//        throw "Nodo ya abierto"
    } else {
        this.abierto = true;

        // Cambiamos la imagen a la de cerrado
        document.images["imgPM_" + this.id].src = imgAbierto.src;

        // Mostramos los hijos
        document.getElementById("divChildren_" + this.id).style.display = "block";
    }
}

// Nos permite escribir en la pantalla desde javascript
function documentoJavaScript() {
	this.text = new Array();		//array to store the string
	this.print = function (str) { this.text[this.text.length] = str; }
	this.println = function (str) { this.text[this.text.length] = str + "\n"; }
	this.toString = function () { return this.text.join(""); }
	this.limpia = function () { delete this.text; this.text = null; this.text = new Array; }
}


function selectIcon(id){
        //alert("icon_"+id);
        //alert('seleecionando');
        document.images["icon_"+id].src = "./img/arbol/enl_carpeta_selec.gif";
}

arbol.prototype.deschequeaIconos = function() {
    for (var i=0; i < this.raiz.nodosHijos.length; i++)
		this.raiz.nodosHijos[i].deschequeaIconos();
}

nodoArbol.prototype.deschequeaIconos = function() {
    //alert(this.id);
    document.images["icon_"+this.id].src = this.icono;
    for (var i=0; i < this.nodosHijos.length; i++)
          this.nodosHijos[i].deschequeaIconos();
}
