if (typeof cooper == 'undefined')
{
    cooper = {}
}

cooper.Dialog = function (container)
{
    this.container = container
    
    if (!this.container.parent().is('body'))
    {
        this.container.appendTo($('body'))
    }
    
    container.append(
        E('a', 'close-button')
        .attr({
            href: '#'
        })
        .click(function (e)
        {
            e.preventDefault()
            this.close()
        }.bind(this))
    )
    
    if (!cooper.Dialog._backdrop)
    {
        cooper.Dialog._backdrop = E('iframe')
        .attr({
            src: '/black.html',
            border: '0',
            frameBorder: '0',
            scrolling: 'no'
        })
        .css({
            display: 'none',
            border: '0px',
            position: 'absolute',
            top: 0,
            left: 0,
            padding: 0,
            margin: 0,
            width: '100%',
            height: '100%',
            opacity: 0.5,
            zIndex: 2
        })
        .appendTo('body')
    }
    
    var reposition = this.reposition.bind(this)
    
    $(window)
        .resize(reposition)
        .scroll(reposition)
}

cooper.Dialog.prototype = 
{
    is_open: function ()
    {
        return this.container.is(':visible')
    },
    
    open: function ()
    {
        if (this.container.is(':hidden'))
        {
            this.position()
            cooper.Dialog._backdrop.fadeIn(250, function ()
            {
                this.container.show()
            }.bind(this))
        }
    },
    
    close: function ()
    {
        if (this.container.is(':visible'))
        {
            this.container.hide()
            cooper.Dialog._backdrop.fadeOut(250)
        }
    },
    
    position: function ()
    {
        var win = $(window)
        var top = ((win.height()/2.25) - (this.container.height()/2)) + win.scrollTop()
        
        if (top < 0)
        {
            top = 10
        }
        
        this.container.css({
            top: top + 'px',
            left: (((win.width()/2) - (this.container.width()/2)) + win.scrollLeft()) + 'px'
        })
        
        cooper.Dialog._backdrop.css({
            top: win.scrollTop(),
            left: win.scrollLeft()
        })
    },
    
    reposition: function ()
    {
        if (this.container.is(':visible'))
        {
            this.position()
        }
    }
}
