var Bubble = Class.create();

Bubble.prototype =
{
    cacheHash: new Array(),
    container: '',
    pageId: '',
    url: '',

    initialize: function(container_id, page_id, url)
    {
        this.container = $(container_id);
        this.pageId = page_id;
        this.url = url;
    },

    show: function(y)
    {
        var cacher = this.cacheHash[this.pageId];
        this.container.style.top = y + 10 + 'px';

        if(! cacher)
        {
            new Ajax.Request(
                this.url,
                {
                    method: "post",
                    parameters:
                    {
                        id: this.pageId
                    },
                    onLoading: this.loading.bind(this),
                    onComplete: this.complete.bind(this)
                }
            );
        }
        else
        {
            this.container.innerHTML = this.cacheHash[this.pageId];
            this.container.style.display = 'block';
        }
    },

    complete: function(req)
    {
        if(req.status != 200)
        {
            this.container.innerHTML = '<table class="bubble" cellpadding="0" cellspacing="0"><tr><td class="lt"></td><td class="t"></td><td class="rt"></td></tr><tr><td class="l"></td><td class="c"><div style="text-align: right;"><div style="display: inline; cursor: pointer; font-weight: bold;" onClick="hideBubble();">x</div></div>Не могу получить данные, попробуйте снова.</td><td class="r"></td></tr><tr><td class="ld"></td><td class="d"></td><td class="rd"></td></tr></table>';
        }
        else
        {
            this.cacheHash[this.pageId] = req.responseText;
            this.container.innerHTML = this.cacheHash[this.pageId];
        }
    },

    loading: function()
    {
        this.container.innerHTML = '<table class="bubble" cellpadding="0" cellspacing="0"><tr><td class="lt"></td><td class="t"></td><td class="rt"></td></tr><tr><td class="l"></td><td class="c"><div style="text-align: right;"><div style="display: inline; cursor: pointer; font-weight: bold;" onClick="hideBubble();">x</div></div>Загружаю...</td><td class="r"></td></tr><tr><td class="ld"></td><td class="d"></td><td class="rd"></td></tr></table>';
        this.container.style.display = 'block';
    }
}

var lastPos = '';

function showBubble(page_id, obj)
{
    pos = getElementPosition(obj);
    if(lastPos == pos.top && $('bubbleContainer').style.display != 'none')
    {
        hideBubble();
    }
    else
    {
        lastPos = pos.top;
        var bubble = new Bubble('bubbleContainer', page_id, '/pages/bubble');
        bubble.show(pos.top);
    }
}

function hideBubble()
{
    $('bubbleContainer').style.display = 'none';
}

function getElementPosition(obj)
{
    var offsetLeft = 0, offsetTop = 0;
    do
    {
        offsetLeft += obj.offsetLeft;
        offsetTop  += obj.offsetTop;
    }
    while(obj = obj.offsetParent);
    return {"left":offsetLeft, "top":offsetTop};
}
