// Estrutura do array.
// ------------------
// [0] - valor do item
// [1] - nome do item
// [2] - nome checkbox
// [3] - link
// [4] - aberto ("S"-Aberto)
// [5] - array com a mesma estrutura

//    var itens_arvore = [['01', 'teste1', 'baseSelecionada', '', '', [['01', 'teste11', 'tipoSelecionado', '', '', [['02', 'teste12', 'tipoSelecionado', '', '']]], ['02', 'teste12', 'tipoSelecionado', '', '']]],
//                        ['02', 'teste2', 'baseSelecionado', '', '', [['01', 'teste21', 'tipoSelecionado', '', ''], ['02', 'teste22', 'tipoSelecionado', '', '']]],
//                        ['03', 'teste3', 'baseSelecionado', '', '', [['01', 'teste31', 'tipoSelecionado', '', '', []], ['02', 'teste32', 'tipoSelecionado', '', '']]]];

// Imagens (ARRAY conforme a sequencia abaixo.
// IMG_RAIZ          = "";
// IMG_EXPANDE_MAIS  = "img/mais.gif";
// IMG_EXPANDE_MENOS = "img/menos.gif";
// IMG_PASTA_FECHADA = "img/pastaLivroFechado.gif";
// IMG_PASTA_ABERTA  = "img/pastaLivroAberto.gif";
// IMG_FOLHA         = "img/documento.gif";
// IMG_VAZIO         = "img/vazio.gif";


function Arvore(nome, itens, imagens) {
	var IMG_RAIZ          = 0;
	var IMG_EXPANDE_MAIS  = 1;
	var IMG_EXPANDE_MENOS = 2;
	var IMG_PASTA_FECHADA = 3;
	var IMG_PASTA_ABERTA  = 4;
	var IMG_FOLHA         = 5;
	var IMG_VAZIO         = 6;
		
	var nomeArvore = nome;
	var itensArvore = itens;
	var imagensArvore = imagens;
	
	var expandeArvore = false;

    if (imagensArvore[IMG_EXPANDE_MAIS] == "" && imagensArvore[IMG_EXPANDE_MENOS] == "") 
    	expandeArvore = true;

    var i = 0;
    var sequencial = 0;
	var html = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr><td valign=\"top\" align=\"left\">";
    
    for (i = 0; i < itensArvore.length; i++) {
        _criaItem(itensArvore[i], 0, sequencial++, "", "");
    }
    
    html += "</td></tr></table>";


	this.getNome = function () {
		return nomeArvore;
	}


	this.getHTML = function () {
		return html;
	}

	
	this.mudaCheckbox = function (id, ligado) {
	    var checkbox = document.getElementById("_ck_" + nomeArvore + "_" + id);
		checkbox.checked = ligado;
		_verificaCheckbox(id);
	}

	    
	this.expande_onclick = function (id) {
	    var subItens = document.getElementById("_dv_" + nomeArvore + "_" + id);
	    var imgEx = document.getElementById("_img_ex_" + nomeArvore + "_" + id);
	    var imgPt = document.getElementById("_img_pt_" + nomeArvore + "_" + id);
	    var situacao = "";
	    
	    if (subItens.style.display == "none") {
	        subItens.style.display = "block";
	        if (imgEx)
	            imgEx.src = imagensArvore[IMG_EXPANDE_MENOS];
	        
	        if (imgPt)    
	            imgPt.src = imagensArvore[IMG_PASTA_ABERTA];
	        situacao = "A"; 
	    }
	    else {
	        subItens.style.display = "none";
	        if (imgEx)
	            imgEx.src = imagensArvore[IMG_EXPANDE_MAIS];
	        
	        if (imgPt)    
	            imgPt.src = imagensArvore[IMG_PASTA_FECHADA];
	        situacao = "F"; 
	    }
	    
	    if (eval("typeof(" + nomeArvore + "_expande_onclick)") != "undefined") 
	        eval(nomeArvore + "_expande_onclick(this, situacao, id);");
	}       

	    
	this.pasta_onclick = function (id) {
		this.expande_onclick(id);
		    
	    if (eval("typeof(" + nomeArvore + "_pasta_onclick)") != "undefined") 
	        eval(nomeArvore + "_pasta_onclick(this, situacao, id);");
	}

	        
	this.item_onclick = function (id, valor) {
	    if (eval("typeof(" + nomeArvore + "_item_onclick)") != "undefined") 
	        eval(nomeArvore + "_item_onclick(this, id, valor);");
	}       

	
	this.checkbox_onclick = function (id, valor) {
		_verificaCheckbox(id);

	    if (eval("typeof(" + nomeArvore + "_checkbox_onclick)") != "undefined") 
	        eval(nomeArvore + "_checkbox_onclick(this, id, valor);");
	}

	
	function _verificaCheckbox(id) {
	    var checkbox = document.getElementById('_ck_' + nomeArvore + "_" + id);
	    var idParente = id;
	    var chkParente;
	    var pos = 0;
	
	    _verificaFilhos(id, checkbox.checked)
	                
	    while ((pos = idParente.lastIndexOf('_')) > 0) {
	        idParente = idParente.substr(0, pos);
	        chkParente = document.getElementById('_ck_' + nomeArvore + "_" + idParente);
	        
	        if (chkParente) {
	            if (checkbox.checked) 
	                chkParente.checked = checkbox.checked;
	            else {
	                if (!_temFilhosSelecionado(idParente))
	                    chkParente.checked = false;
	            } 
	        }
	    }
	}

	    
	function _verificaFilhos(id, checked) {
	    var chk;
	    var i = 0;
	    
	    while (i > -1) {
	        idFilho = id + "_" + (i++);
	        chk = document.getElementById('_ck_' + nomeArvore + "_" + idFilho);
	        
	        if (!chk) 
	            break;
	        else {
	            chk.checked = checked; 
	            _verificaFilhos(idFilho, checked);
	        }
	    } 
	}

	
	function _temFilhosSelecionado(id) {
	    var temChecked = false;
	    var chk;
	    var i = 0;
	    
	    while (i > -1) {
	        chk = document.getElementById('_ck_' + nomeArvore + "_" + id + "_" + (i++));
	        
	        if (!chk) 
	            i = -1;
	        else {
	            if (chk.checked) 
	                temChecked = true;
	        }
	    } 
	    
	    return temChecked;        
	}

	    
	function _criaItem(item, nivel, sequencial, idParente, valor) {
	    var valorItem = item[0];
	    var nomeItem = item[1];
	    var nomeCheckboxItem = item[2];
	    var linkItem = item[3];
	    var aberto = item[4];
	        
	    var valorAtual = ""; 
	    var temSubItens = false;
	    var subItens = null;
	    var nivelAtual = nivel + 1;
	    var idAtual = idParente + "_" + sequencial;
	    var sequencialAtual = 0;
	    var expande = false;
		var imagemExpande;
		var imagemPasta;
    	var mostra;
			
	    var i = 0;
	
		if (typeof(item[5]) != "undefined") {
		    if (item[5].length > 0) {
		        temSubItens = true;
		        subItens = item[5];
		    }
	    }
	    
	    if (expandeArvore) 
	    	expande = true;
		else {
			if (aberto == "S") 
				expande = true;
		}
				        
	    if (nivel > 0)
	        valorAtual = valorItem;
	    else
	        valorAtual = valorItem;
	                
	    html += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>";
	
	    if (nivelAtual > 0) {
	        for (i = 1; i < nivelAtual; i++) 
	            html += "<td valign=\"top\"><img src=\"" + imagensArvore[IMG_VAZIO] + "\" border=\"0\" align=\"absbottom\"></td>";
	    } 

		if (expande) {
			imagemExpande = imagensArvore[IMG_EXPANDE_MENOS];
			imagemPasta = imagensArvore[IMG_PASTA_ABERTA];
	    }
		else {
			imagemExpande = imagensArvore[IMG_EXPANDE_MAIS];
			imagemPasta = imagensArvore[IMG_PASTA_FECHADA];
		}
	 		
		if (temSubItens) {
	        if (imagemExpande != "") {
		        html += "<td valign=\"top\">";
		        html += "<img id=\"_img_ex_" + nomeArvore + "_" + idAtual + "\" src=\"" + imagemExpande + "\" onclick=\"javascript:arvores.get('" + nomeArvore + "').expande_onclick('" + idAtual + "');\" border=\"0\" align=\"absbottom\">";
		        html += "</td>";
	        }
	
	        if (imagemPasta != "") {
	            html += "<td valign=\"top\">";
	            html += "<img id=\"_img_pt_" + nomeArvore + "_" + idAtual + "\" src=\"" + imagemPasta + "\" onclick=\"javascript:arvores.get('" + nomeArvore + "').pasta_onclick('" + idAtual + "');\" border=\"0\" align=\"absbottom\">";
	            html += "</td>";
	        }		     
	    }
		else {
	        if (imagemExpande != "") {
		        html += "<td valign=\"top\">";
		        html += "<img src=\"" + imagensArvore[IMG_VAZIO] + "\" border=\"0\" align=\"absbottom\">";
		        html += "</td>";
	        }
	        
		    if (imagensArvore[IMG_FOLHA] != "") {
	            html += "<td valign=\"top\">";
	            html += "<img src=\"" + imagensArvore[IMG_FOLHA] + "\" border=\"0\" align=\"absbottom\">";
	            html += "</td>";
	        }
	        else {
		        if (imagemPasta != "") {
			        html += "<td valign=\"top\">";
			        html += "<img src=\"" + imagensArvore[IMG_VAZIO] + "\" border=\"0\" align=\"absbottom\">";
			        html += "</td>";
		        }
	        }
	    }
			    		
		html += "<td valign=\"top\">";
			
		if (nomeCheckboxItem != "")

			html += "<input type=\"checkbox\" id=\"_ck_" + nomeArvore + "_" + idAtual + "\" name=\"" + nomeCheckboxItem + "\" onclick=\"javascript:arvores.get('" + nomeArvore + "').checkbox_onclick('" + idAtual + "', '" + valorAtual + "'); atualizaGrid();\" value=\"" + valorAtual + "\">";
	            
	    html += "</td>";
		html += "<td align=\"left\">";
			
		if (linkItem == "") 
			html += nomeItem;
		else
	        html += "<a href=\"" + linkItem + "\" style=\"text-decoration: none\">" + nomeItem + "</a>";
			
	    html += "</td></tr></table>";
	    
	    if (temSubItens) {  
			if (expande) 
				mostra = "block";
		    else
		    	mostra = "none";
		    	
			html += "<div id=\"_dv_" + nomeArvore + "_" + idAtual + "\" style=\"display: " + mostra + "\">";
	        
	        for (i = 0; i < subItens.length; i++) {
	            _criaItem(subItens[i], nivelAtual, sequencialAtual++, idAtual, valorAtual);
	        }
	
	        html += "</div>";
	    } 
	}
} 


function Arvores() {
	var arvores = new Array();
	
	this.adiciona = function(arvore) {
		var i = _indiceArvore(arvore.getNome());
		
		if (i > -1) {
			arvores[i][1] = arvore;
		}
		else {
			var item = new Array(2);
			item[0] = arvore.getNome();
			item[1] = arvore;
			arvores.push(item);
		}
	}

	
	this.get = function(nome) {
		var i = _indiceArvore(nome);
		var item = null;
		
		if (i > -1) {
			item = arvores[i][1];
		}
		
		return item;
	}
	
	
	function _indiceArvore(nome) {
		var i = 0;
		
		for (i = 0; i < arvores.length; i++) {
			if (arvores[i][0] == nome) 
				break;
		}
		
		if (i == arvores.length) {
			i = -1;
		}
	
		return i;		
	}
}


