var BoxMenu = Class.create();

BoxMenu.prototype = {
    initialize: function(nodes, hid) {
        this.nodes = nodes;
        this.hid = hid; // html id
    },
    
    clickNode: function(event) {
        if (!this.haschildren) {
            document.location = this.link;
            return;
        }

        Element.toggle(this.children_tr);
    },

    setActiveNode: function(id) {
        if (!id || !this.nodes[id]) {
            return;
        }

        node = this.nodes[id];
        Element.addClassName(node.td, 'active');

        p = id;
        while (p) {
            if (this.nodes[p].haschildren) {
                Element.show(this.nodes[p].children_tr);
            }

            p = this.nodes[p].parent;
        }
    },

    mouseOverNode: function(event) {
        Element.addClassName(this, 'hover');
    },

    mouseOutNode: function(event) {
        Element.removeClassName(this, 'hover');
    },

    displayNode: function(id) {
        var node = this.nodes[id];
    
        el = $(this.hid+'['+node.parent+'][children]');
    
        n_tr = el.insertRow(el.rows.length);
        n_td = n_tr.insertCell(n_tr.cells.length);
        node.td = n_td;

        n_td.className = 'node l'+node.level;
        n_td.onclick = this.clickNode.bindAsEventListener(node);
        n_td.onmouseover = this.mouseOverNode;
        n_td.onmouseout = this.mouseOutNode;
    
        n_td.appendChild(document.createTextNode(node.name));
    
        if (node.haschildren) {
            node.children_tr = el.insertRow(el.rows.length);
            Element.hide(node.children_tr);
            n_tds = node.children_tr.insertCell(node.children_tr.cells.length);
            n_tds.innerHTML += '<table align="center" cellspacing="0">'+
                        '<tbody id="'+this.hid+'['+id+'][children]"></tbody></table>';
        }
    },

    addNode: function(id) {
        // skip if already added
        if (this.nodes[id].added) {
            return;
        }
    
        var node = this.nodes[id];
    
        // add parent first
        if (node.parent && !this.nodes[node.parent].added) {
            this.addNode(node.parent);
        }
    
        this.displayNode(id);
        node.added = true;
    },

    build: function() {
        for (id in this.nodes) {
            this.addNode(id);
        }
    }
}
