var _popup_windows_list = new Array();

function popup(id) {
    this.id = id;
    
    _popup_windows_list[_popup_windows_list.length] = this;
    
    this._wnd = null;
    this.getWindow = function() {
        if (this._wnd == null) {
            this._wnd = $(this.id);
            if (!this._wnd) {
                this._wnd = document.createElement("div");
                this._wnd.style.position = 'absolute';
                this._wnd.style.display = 'none';
                this._wnd.id = this.id;
                document.body.appendChild(this._wnd);
            }
            Event.observe(this._wnd, 'click', function(event) { Event.stop(event); });
        }
        return this._wnd;
    }
    
    this.show = function(left, top, width, height) {
        var w = this.getWindow();
        w.style.left = left + 'px';
        w.style.top = top + 'px';
        if (width) w.style.width = width + 'px'; else w.style.width = '';
        if (height) w.style.height = height + 'px'; else w.style.height = '';
        w.style.display = 'block';
    }
    
    this.hide = function() {
        var w = this.getWindow();
        w.style.display = 'none';
        w.style.left = '-1000px';
        w.style.top = '-1000px';
    }
    
    this.setHTML = function(html) {
        this.getWindow().innerHTML = html;
    }
}

function getPopupWindow(id) {
    for (var i=0; i<_popup_windows_list.length; i++)
        if (_popup_windows_list[i].id == id)
            return _popup_windows_list[i];
            
    return new popup(id);
}

Event.observe(document, 'click', function() {
    for (var i=0; i<_popup_windows_list.length; i++) _popup_windows_list[i].hide();
});

function showPopupWindow(id, html, left, top) {
    var wnd = getPopupWindow(id);
    wnd.setHTML(html);
    
    var x = left;
    var y = top;
    if (!x && !y)
    {
        var off = document.viewport.getScrollOffsets();
        var dim = document.viewport.getDimensions();
        
        var cx = off.left + dim.width / 2;
        var cy = off.top + dim.height / 2;
        
        dim = Element.getDimensions(wnd._wnd);
        x = cx - dim.width / 2;
        y = cy - dim.height / 2;
    }
    
    wnd.show(x,y);
    return wnd;
}