/*
---
description: Simple modal class (with overlay) for MooTools.

license: MIT-style

authors:
- Christopher Pitt

requires:
- Overlay (sixtyseconds)/0.1: Overlay

provides: [Modal]

...
*/

var Modal = new Class({
    'Implements': [Options, Events],

    'options': {    
        /*
        'onLoad': $empty,
        'onPosition': $empty,
        'onShow': $empty,
        'onHide': $empty,
        'onButton': $empty,
        */
        'z-index': 4,
        'buttons': 'ok|cancel',
        'container': document.body,
        'duration': 100,
        'color': '#000',
        'opacity': 0.7
    },
    
    'initialize': function(options)
    {
        this.setOptions(options);
        var self = this, buttons = this.options.buttons;
        
        self.window = new Element('div', {
        	'id': self.options.id,
            'class': 'modal-window',
            'styles': {
                'z-index': self.options['z-index'] + 10,
                'position': (Browser.Engine.trident && Browser.Engine.version <= 5) ? 'absolute' : 'fixed',
                'display': 'none'
            }
        }).inject(document.body);

        self.overlay = new Overlay($extend(self.options, {
            'onPosition': self.position.bind(self),
            'onHide': function() {
            	self.window.dispose();
            }.bind(self)
        }));

            
        self.content = document.id(self.options['content']) || new Element('div', {'class': 'modal-content'});
                    
        self.content.setStyles({
           'z-index': self.options['z-index'] + 11
        }).inject(self.window);            
            
        Array.each(buttons, function(button) {
            new Element('a', {
                'class': 'button ' + button.className,
                'title': button.title,
                'text': '    ',
                'href': '#',
                'events': {
                    'click': function(e) {
                        self.fireEvent('onButton', [e, button]);
                    }
                }
            }).inject(self.window);
        });
        
        this.fireEvent('onLoad');
    },
    
    'show': function()
    {
        this.overlay.show();
    },
    
    'hide': function()
    {
        this.overlay.hide();
    },
    
    'close': function()
    {
        this.overlay.hide();
    },
    
    'position': function()
    {
        var self = this,
            size = window.getSize(),
            coords = self.window
                .setStyle('display', 'block')
                .getCoordinates();
            
        self.window.setStyles({
            'top': Math.floor((size.y - coords.height) / 2),
            'left': Math.floor((size.x - coords.width) / 2)
        });
        
        self.fireEvent('onPosition');
    }
});
