﻿function $(id){return document.getElementById(id);}

function treeMenu(varID, treeID, treeName, treePath, initExpand, autoclose){
    var _tree = $(treeID);
    var _name = treeName;
    var _path = typeof(treePath)=='undefined' ? '' : treePath;
    var _autoclose = typeof(autoclose)=='undefined' ? true : autoclose;
    var _lastNodeID = null;

    this._showhide = function(objID, pstr){
    	var submenu = $(_name+'_s_'+objID);
    	if (submenu==null) return;
    	submenu.style.display = submenu.style.display=='none' ? '' : 'none'; this._expand_ico(objID, submenu.style.display=='');
    	if (!_autoclose) return;
    	if ((','+pstr+',').indexOf(','+_lastNodeID+',')>=0) return;
    	if (_lastNodeID!=null){
    		submenu = $(_name+'_s_'+_lastNodeID);
    		if (submenu){ submenu.style.display = 'none'; this._expand_ico(_lastNodeID); }
    	}
    	if (_lastNodeID==objID) _lastNodeID = null;
    	else _lastNodeID = objID;
    }

    this._expand = function(id){
        var submenu = $(_name+'_s_'+id);
    	if (submenu==null) return;
    	submenu.style.display = '';
    	_lastNodeID = id;
    }

    this._onclick = function(ref){
        return function(){eval(varID)._showhide(ref[0],ref[1]);}
    }
    
    this._expand_ico = function(id,show){
	    var ico = $('ico_'+id);
	    if (ico){
	        ico.src = show ? ico.src.replace('tree_close', 'tree_open') : ico.src.replace('tree_open', 'tree_close');
	    }
    }

    var lis = _tree.getElementsByTagName('li');
    var iniT = typeof(initExpand);
    if (_path!='') iniT = '';
    var cnt = 0;
    for (var i=0; i<lis.length; i++){
        var ref = lis[i].getAttribute('ref');
        if (ref==null) continue;
        ref = ref.split('|');
        if (ref.length<2) {ref.push('')}
        lis[i].onclick = this._onclick(ref);
        if (iniT=='number'){
            cnt++;
            if (initExpand==cnt){ this._expand(ref[0]); this._expand_ico(ref[0], true); initExpand = -1;}
        }
        if (iniT=='string'){
            var at = lis[i].getElementsByTagName('a')[0].innerText;
            if (initExpand==at){ this._expand(ref[0]); this._expand_ico(ref[0], true); initExpand = '';}
        }
    }

	var ppath = _path.split(',');
	if (_path!='') _lastNodeID = ppath[0];
	for(var i=0; i<ppath.length; i++){
		var submenu = $(_name+'_s_'+ppath[i]);
		if(submenu){ submenu.style.display=''; this._expand_ico(ppath[i], true); }
	}
}