// Config.js должен быть прочитан ПЕРЕД этим файлом. Там определяется stuff_href
// Загрузка config.js находится в admin/main.html 

var imgFolder = stuff_href + '/images/admin';

// Node object constructor
function Node(id, pid, title, img){
        this.id          = 'n'+id;
        this.parent_id   = 'n'+pid;
        this.title       = title;
        this.img         = img ? img : 'folder';
        this.is_opened   = false;
        this.is_selected = false;
        this.lastSibling = true;
        this.children    = [];
        this.parent      = null;
}

// Tree object constructor
function dTree(objName){
        this.arrNodes           = [];
        this.htmlOutput         = '';
        this.rootNodes      = [];
        this.selectedNode       = null;
        this.instanceName       = objName;

        // Adds a new node to the node array
        this.add = function(id, pid, title, img) {
                this.arrNodes['n'+id] = new Node(id, pid, title, img);
        }

        // Вывод дерева
        this.draw = function() {
                this.parseTree();
                this.buildTree(this.rootNodes, 1);
                document.writeln(this.htmlOutput);
        }

        // увязывание между собою узлов дерева
        this.parseTree = function() {
                var node, parent;
                for (var node_id in this.arrNodes) {
                        node = this.arrNodes[node_id];
                        if (this.arrNodes[node.parent_id] != null) {
                                // этот узел имеет родителя
                                parent = this.arrNodes[node.parent_id];
                                if (!parent) continue;
                                node.parent = parent;
                                parent.children[parent.children.length]=node;
                                if (parent.children.length > 1) parent.children[parent.children.length-2].lastSibling = false;
                        } else {
                                // этот узел НЕ имеет родителя - это корневой узел
                                this.rootNodes[this.rootNodes.length] = node;
                                if (this.rootNodes.length > 1) this.rootNodes[this.rootNodes.length-2].lastSibling = false;
                        }
                }
                // из кук берем id раскрытых нодов и id выбранного нода
                var selectedNode = this.getCookie('cs' + this.instanceName);
                if (this.arrNodes[selectedNode] != null) this.arrNodes[selectedNode].is_selected = true;

                var openedNodes = this.getCookie('co' + this.instanceName).split(',');
                for (var id in openedNodes) {
                        if (this.arrNodes[openedNodes[id]] == null) continue;
                        this.arrNodes[openedNodes[id]].is_opened = true;
                }
        }
        
        // Построение HTML кода дерева
        this.buildTree = function(nodes, level) {
                for (var i=0,cls='treenode',node=null; i<nodes.length; i++,cls='treenode') {
                        node = nodes[i];
                        for (var l=1, tmp='', parent=node.parent; l<level; l++, parent=parent.parent) {
                                tmp='<img src='+imgFolder+'/empty.gif align=absmiddle>'+tmp;
                        }
                        this.htmlOutput += tmp;

                        if (node.children.length) cls+=node.is_opened?'_minus':'_plus';
                        this.htmlOutput+='<span id='+node.id+' class='+cls+' onclick="'+this.instanceName+'.OnOff(this)">';
                        this.htmlOutput+='<img class=nodeimg src='+imgFolder+'/'+node.img+'.gif align=absmiddle height=14></span>';
                        this.htmlOutput+='<span id=i'+node.id+' class=treeitem_'+(node.is_selected?'active':'inactive')+' onclick="'+this.instanceName+'.Sel(this)">'+node.title+'</span><br>\n';
                        
                        if (node.children.length) {
                                this.htmlOutput+='\n<div id=s'+node.id+' style="display:'+(node.is_opened?'block':'none')+'">';
                                this.buildTree(node.children,level+1);
                                this.htmlOutput+='\n</div>';
                        }
                }
        }

        // открытие - закрытие нодов
        this.OnOff = function (el) {
                var re=new RegExp("treenode_(plus|minus)(_last)?", "i");
                if (! (tmp=re.exec(el.className))) return;
                var subtree = document.getElementById('s'+el.id);
                if (tmp[1]=='plus') {
                        el.className = 'treenode_minus'+tmp[2];
                        if (subtree) subtree.style.display = 'block';
                        this.arrNodes[el.id].is_opened = true;
                }
                if (tmp[1]=='minus') {
                        el.className = 'treenode_plus'+tmp[2];
                        if (subtree) subtree.style.display = 'none';
                        this.arrNodes[el.id].is_opened = false;
                }
                var opened = [];
                for (var id in this.arrNodes) if (this.arrNodes[id].is_opened) opened[opened.length]=id;
                this.setCookie('co' + this.instanceName, opened.join(','));
        }

        // подсветка выбранного нода
        this.Sel = function (el) {
                var re=new RegExp("treeitem_(active|inactive)", "i");
                if (! (tmp=re.exec(el.className))) return;
                var node_id = el.id.substr(1);

                // если нет ссылки, но есть плюс - открываем узел
                if (el.getElementsByTagName('A').length == 0) {
                        if (el1 = document.getElementById(node_id)){
                                if (this.arrNodes[node_id].children.length) el1.fireEvent('onclick');
                        }
                }

                // если уже подсвечен - выходим
                if (tmp[1]=='active') return;

                for (var id in this.arrNodes) {
                        if (this.arrNodes[id].is_selected) {
                                if (el1 = document.getElementById('i'+id)) el1.className = 'treeitem_inactive';
                        }
                }
                el.className = 'treeitem_active';
                this.arrNodes[node_id].is_selected = true;
                this.setCookie('cs' + this.instanceName, node_id);
        }

        // Установка кук
        this.setCookie = function(cookieName, cookieValue) {
                document.cookie =cookieName + '=' + cookieValue + ';PATH=/';
        }

        // Считка кук
        this.getCookie = function(cookieName) {
                var tmp;
                var re=new RegExp(cookieName+"=([^;]+)", "i");
                if (tmp=re.exec(document.cookie)) return tmp[1]; else return '';
        }

}
