PagedOverlay = new JS.Singleton({
    include: JS.State,
    
    initialize: function() {
        this.setState('CLOSED');
    },
    
    addLinks: function(links) {
        Ojay(links).forEach(this.addLink, this);
    },
    
    addLink: function(link) {
        if (!link.klass || link.klass !== Ojay.DomCollection) {
            link = Ojay(link);
        }
        
        link.on('click', function(el, ev) {
            ev.stopDefault();
            this.open(el.node.href);
        }, this);
    },
    
    fixSize: function() {
        this._overlay.fitToContent().center();
    },
    
    states: {
        CLOSED: {
            open: function(href) {
                this._makeCloseable();
                this._createOverlay();
                this.setState('ANIMATING');
                Ojay(document.body).addClass('overlaid');
                Ojay.HTTP.GET(href, {xhr: '1'}).insertInto(this._content)
                    .wait(0.01)
                    .evalScripts()
                    ._(this._mask).show('fade')
                    ._(this._overlay).getHTML().setStyle({overflow: 'hidden'})
                    ._(this._overlay).insert(this._closeButton, 'top')
                    .fitToContent()
                    .getHTML().setStyle({overflow: ''})
                    ._(this._overlay).center().show('fade')
                    ._(this).setState('OPEN');
            },
            
            _makeCloseable: function() {
                if (this._closeable) return;
                
                this._closeButton = Ojay(Ojay.HTML.span({className: 'close'}, 'Close'));
                Ojay.Keyboard.listen(document, 'ESCAPE', this.close, this);
                this._closeButton.on('click', this.close, this);
                this._closeable = true;
            },
            
            _createOverlay: function() {
                this._mask = new Ojay.PageMask({
                    color:   '#000',
                    opacity: 0.75
                });
                
                this._overlay = new Ojay.ContentOverlay({
                    width:   840,
                    content: this._closeButton
                });
                
                this._content = this._overlay.getContentElement();
                
                this._mask.positionBehind(this._overlay);
                
                this._overlay.getHTML().on('form:updated', this.fixSize, this);
                this._overlay.getHTML().on('form:completed', this.close, this);
            }
        },
        
        OPEN: {
            close: function() {
                this.setState('ANIMATING');
                this._overlay.hide('fade').close()
                    ._(this._mask).hide('fade').close()
                    ._(Ojay(document.body)).removeClass('overlaid')
                    ._(this).setState('CLOSED');
            }
        },
        
        ANIMATING: {}
    }
});

