/*
Script per gestire un treeView via jquery
*/

function TreeView() {

	var node;      //l'elemento che dovrà contenere la freccia
	var root;      //l'ul principale delll'albero
	var nodes;     //gli oggetti jquery corrispondenti ai nodi che hanno figli
	var uls;       //gli oggetti jquery corrispondenti alle liste di secondo livello
	var istance;   //mi serve per tenermi il riferimento negli eventi di jquery
	
	this.init = function init(node, root) {
		this.node = node;
		this.root = jQuery(root);
		
		this.nodes = this.root.find('li:has(ul)>'+this.node);
		this.uls = this.root.find('ul');
		
		this.closeTree();
		
		//apro l'albero fino all'elemento corrente
		this.parseTree();
		
		this.addArrows();
		this.eventHandler();
	}
	
	this.closeTree = function closeTree() {
		this.uls.hide();
	}
	
	this.addArrows = function addArrows() {
		this.nodes.addClass('closed');
	}
	
	this.eventHandler = function eventHandler() {
		istance = this;
		this.nodes.click(function() {
			jQuery(this).parent('li').find('>ul').slideToggle('fast');
			jQuery(this).parent('li').find('>'+istance.node).toggleClass('open');
			return false;
		});
	}
	
	//per aprire direttamente tutto l'albero
	this.showTree = function showTree() {
		this.uls.slideDown('fast');
		this.nodes.addClass('open');
	}
	
	//per chiudere tutto l'albero
	this.hideTree = function hideTree() {
		this.uls.slideUp('fast');
		this.nodes.removeClass('open');
	}
	
	//per aprire l'albero fino all'elemento "current"
	this.parseTree = function parseTree() {
		this.root.find('.current').parents('ul').show();
		this.root.find('ul:visible').parent('li').find('>'+this.node).addClass('open');
	}
}