var popups = [];
var Popup = Class.create({
  initialize: function(element) {
    this.element = $(element);
    this.body = $(document.body);
    this.background = this.createBackground();
    window.popups.push(this);
    this.initializeElement();
  },
  createBackground: function() {
    var div = new Element('div', {className: 'popup-background', style: 'display: none; opacity: 0;'});
    div.observe('mousedown', M.send('stop'));
    this.body.insert({top: div});
    return div;
  },
  initializeElement: function() {
    this.background.insert({after: this.element});
    this.element.setStyle({position: 'fixed'})
    this.element.open = this.show.bind(this);
    this.element.close = this.hide.bind(this);
    this.element.popupObj = this;
  },
  visible: function() {
    return this.element.visible();
  },
  show: function(afterShowCallback) {
    this.background.setStyle({
      opacity: 0, 
      zIndex: 1000 * (window.popups.select(M.send('visible')).length + 1)
    });
    this.element.setStyle({
      opacity: 0,
      zIndex: 1000 * (window.popups.select(M.send('visible')).length + 1) + 1
    });
    this.position();
    new Fx.Style(this.background, 'opacity', {onStart: function(el) {
      el.show();
      fixIEOverlay(el);
    }}).custom(0, 0.7);
    new Fx.Style(this.element, 'opacity', {onStart: Element.show, onComplete: afterShowCallback || Prototype.emptyFunction}).custom(0, 1);
  },
  position: function() {
    var visible = this.visible();
    this.element.show();
    this.element.setStyle({
      top: (document.viewport.getHeight() / 2 - this.element.getHeight() / 2) + 'px',
      left: (document.viewport.getWidth() / 2 - this.element.getWidth() / 2) + 'px'
    });
    if (!visible) this.element.hide();
  },
  hide: function() {
    new Fx.Style(this.element, 'opacity', {onComplete: Element.hide}).custom(1, 0);
    new Fx.Style(this.background, 'opacity', {onComplete: function(el) {
      el.hide();
      fixIEOverlay(el);
    }}).custom(0.7, 0);
  }
});