var popupmanager = {
    id:null,
    sub_ids:[],
    f:function() {},
    onmouseup_registered:false,
    register:function(id, f)
    {
        this.register_onmouseup();
        if (popupmanager.id && $(popupmanager.id))
        {
            popupmanager.f();
            popupmanager.id = null;
        }
        popupmanager.id = id;
        popupmanager.f = f;
    },
    onclick:function(event)
    {
        var element;
        if (!popupmanager.id)
        {
            return (false);
        }
        element = tools.get_event_source(event);
        if (!tools.html_element_is_in(element, popupmanager.id) && !this.is_in_sub_popin(element))
        {
            setTimeout(function() {
                popupmanager.close();
            }.bind(this), 1);
        }
        return (true);
    },
    add_sub_id:function(id)
    {
        this.sub_ids.push(id);
    },
    is_in_sub_popin:function(element)
    {
        var i;

        i = 0;
        while (this.sub_ids[i])
        {
            if (tools.html_element_is_in(element, this.sub_ids[i]))
                return (true);
            i++;
        }
        return (false);
    },
    close:function()
    {
        if ($(popupmanager.id))
        {
            popupmanager.f();
        }
        popupmanager.id = null;
        popupmanager.f = function() {};
        this.close_sub_ids();
        this.sub_ids = [];
    },
    close_sub_ids:function()
    {
        this.sub_ids.each(
            function (id_html)
            {
                if ($(id_html))
                {
                    $(id_html).remove();
                }
            }
        );
    },
    register_onmouseup:function()
    {
        if (this.onmouseup_registered)
        {
            return (false);
        }
        document.observe("mouseup", this.onmouseup.bind(this));
        this.onmouseup_registered = true;
        return (true);
    },
    onmouseup:function(event)
    {
        event = tools.get_event(event);
        var event_source = tools.get_event_source(event);
        if (event_source.tagName != "HTML")
        {
            this.onclick(event);
        }        
    }
};

