var ToolsListener = {

    hRE:/^h[2-9]$/i,
    divRE:/^div$/i,
    toolRE:/\btool\b/i,
    openRE:/ ?\bopen\b/i,
    tools: [],
    toolStates: {},

    init: function(node) {
        if(!node) return;
        // setup evenhandler
        if (typeof(this.handlers) == 'undefined') this.handlers = new Array();
        this.handlers[this.handlers.length]= addEventHandler(node, "click", function(e) {
            ToolsListener.clickHandler(e);
        });
        // gather all tools
        var divs = node.getElementsByTagName("DIV");
        for (var i=0;i<divs.length;i++) {
            if (this.toolRE.test(divs[i].className)) this.tools.push(divs[i]);
        }
        ToolsListener.getStates();
    },

    clickHandler: function(e) {
        // toggle clicked tool
        var e = e||event;
        if(e.shiftKey || e.ctrlKey || e.altKey) return true;
        var target = e.target||e.srcElement;
        while (!target.nodeName || target.nodeType == 3) target = target.parentNode;
        if (target.nodeName && this.hRE.test(target.nodeName)) {
            var tool = target;
            while (tool!=null && !this.divRE.test(tool.nodeName) && !this.toolRE.test(tool.className)) tool = tool.parentNode;
            if (tool!=null && this.divRE.test(tool.nodeName) && this.toolRE.test(tool.className)) {
                ToolsListener.toggle(tool);
                cancelEvent(e);
            }
        } else return true;
    },

    toggle: function(tool) {
        if (this.openRE.test(tool.className)) tool.className = tool.className.replace(this.openRE, "");
        else tool.className += " open";
        if (window.parent && parent.receiveDocumentHeight) {
            if (window.sendDocumentHeight) sendDocumentHeight();
        }
    },

    getStates: function() {
        var cookie = $.cookie("tools");
        if (cookie) {
            var openTools = cookie.split(",");
            for (var i=0; i < openTools.length; i++) $("#" + openTools[i]).addClass("open");
        }
    },

    saveStates: function() {
        var cookieValue = "";
        for (var i = 0; i < this.tools.length; i++) if (this.openRE.test(this.tools[i].className)) cookieValue = cookieValue + this.tools[i].id + ",";
        $.cookie("tools", cookieValue, { path: "/", expires: 1000 });
    }
};

if (onloadHandler) onloadHandler.add(function() {
    ToolsListener.init(document.getElementById("tools"));
});

if (onunloadHandler) onunloadHandler.add(function(){
    ToolsListener.saveStates();
});

function openTool(tool) {
    if (ClassName.contains(tool,"open")) return;
    ToolsListener.toggle(tool);
}

function openLogin(obj) {
    var logintool = document.getElementById("tool-00");
    if (logintool) {
        addEventHandler(obj, "click", function(e) {openTool(logintool); cancelEvent(e)});
    }
}
