/**
 * @param id string id kontenera
 */
jslt.TreeView = function(id, clickHandler){
	this.clickHandler = clickHandler;
	this.lastClickedNode = null
	this.hideFirstLevel=false
	this.TreeView = function(id){
		this.decorate($("#"+id+" > *")[0], 1)
	}
	this.decorate = function(list, level){
		list.className = "jslt-tv-list jslt-tv-list-l" + level
		for (var i = 0; i < list.childNodes.length; i++) {
			list.childNodes[i].className = "jslt-tv-el jslt-tv-el-l" + level
			list.childNodes[i].refTV = this
			list.childNodes[i].level = level
			list.childNodes[i].nodeSelected = false
			$(list.childNodes[i]).bind('click', function(e){
				this.refTV.evNodeClick(this)
				return false;
			})
			if (list.childNodes[i].childNodes.length == 2) {// have a & ul
				list.childNodes[i].childNodes[1].style.display = "none"
				this.decorate(list.childNodes[i].childNodes[1], level + 1)
			}
		}
	}
	this.evNodeClick = function(node){
		//console.log(node.childNodes[0])
		if (this.lastClickedNode != null) {
			this.walk(this.lastClickedNode, false)
		}
		this.lastClickedNode = null
		this.lastClickedNode = node
		this.walk(this.lastClickedNode, true)
		this.clickHandler.apply(this, [node])
	}
	this.unsign = function(){
		this.unsigning = true
		if (this.lastClickedNode != null) {
			this.walk(this.lastClickedNode, false)
		}
		this.unsigning = false
	}
	this.walk = function(lastNode, showing){
		//zawiera podmenu
		if (lastNode.childNodes.length == 2) {
			lastNode.childNodes[1].style.display = showing ? "block" : "none"
		}
		var pNode = lastNode
		while (true) {
			var nn = pNode.nodeName.toLowerCase()
			if (nn == "ul" || nn == "li") {
				if (nn == "li") {
					this.changeClass(pNode, showing)
				}
				else if (nn == "ul") {
					if(!this.hideFirstLevel && !showing){
						if(pNode.parentNode.nodeName.toLowerCase()=='li'){
							pNode.style.display = "none"
						}
					}else{
						pNode.style.display = showing ? "block" : "none"
					}
				}
			}
			else {
				break;
			}
			pNode = pNode.parentNode
		}
	}
	this.changeClass = function(node, actB){
		if (actB) {
			node.className += " jslt-tv-el-act-l" + node.level
		}
		else {
			var ar = node.className.split(" ")
			var popped = ar.pop()
			if (ar.length >= 2) {
				node.className = ar.join(" ")
			}
			if (/jslt-tv-el-.*/.test(popped)) {

			}

		}
	}
	this.TreeView(id)
};

