var Popup = new Class(
{
   Implements: [Options, Events],

   options:
   {
      bgcolor: '#000000',
      opacity: 0.6,
      windowId: false,
      backWindowId: 'backWindowId',
      fadeTime: 100,
      closeBut: false,
      contentId: false,
      closeTime: 100,
      backTime: 100,
      isCentre: true
   },

   initialize: function(element, options)
   {
      this.setOptions(options);
      this.fade = null;
      this.open();
      $$(this.options.closeBut).addEvent('click', function(){this.close();}.bind(this));
      if (this.options.isCentre) window.addEvent('scroll', function(){if ($(this.options.windowId).getCoordinates().top >= 0) $(this.options.windowId).centre();}.bind(this));
   },

   open: function()
   {
      $(this.options.windowId).setOpacity(0);
      $(this.options.windowId).centre();
      new Fx.Morph(this.options.windowId, {duration: this.options.fadeTime}).start({'opacity': [0, 1]});
      this.fadeOn();
   },

   close: function()
   {
      if ($(this.options.windowId).style.top == '-1000000px') return;
      new Fx.Morph(this.options.windowId, {duration: this.options.closeTime}).start({'opacity': [1, 0]}, function(){$(this.options.windowId).style.top = '-1000000px';});
      $(this.options.windowId).style.top = '-1000000px';
      this.fadeOff();
   },

   fadeOn: function()
   {
      this.setupFadeElement();
      this.fade.style.position = 'absolute';
      this.fade.style.backgroundColor = this.options.bgcolor;
      this.fade.style.top = 0;
      this.fade.style.left = 0;
      this.fade.style.width = window.getScrollSize()['x'] + 'px';
      this.fade.style.height = window.getScrollSize()['y'] + 'px';
      this.fade.style.zIndex = $(this.options.windowId).getStyle('z-index').toInt() - 1;
      new Fx.Morph(this.fade.id, {duration: this.options.backTime}).start({'opacity': [0, this.options.opacity]});
   },

   fadeOff: function()
   {
      this.setupFadeElement();
      new Fx.Morph(this.fade.id, {duration: this.options.backTime}).start({'opacity': [this.options.opacity, 0]}).addEvent('complete', function(){this.fade.dispose();}.bind(this));
   },

   setupFadeElement: function()
   {
      if (this.fade) return;
      if (!$(this.options.backWindowId))
      {
         this.fade = new Element('div', {id: this.options.backWindowId + parseInt(Math.random() * 1000000)});
         this.fade.setOpacity(0);
         this.fade.inject(document.body, 'top');
      }
      else this.fade = $(this.options.backWindowId);
   }
});

Element.implement({makePopup: function(options){return new Popup(this, options);}});
