// Popup class
function Popup() {
  this.popup;
  this.overlay;
  this.delay = 400;
  
  this.start = function(element) {
    this.popup = $(element);
    this.overlay = this.popup.prev('#overlay');
    this.adjustPopup();
    this.adjustOverlay();
  };
  
  this.showAll = function() {
    this.overlay.show();
    this.overlay.animate({'opacity':'0.7'}, this.delay, function() { popup.showPopup(); });
  };
  
  this.showPopup = function() {
    this.popup.show();
    this.popup.animate({'opacity':'1'}, this.delay, function() { });
    this.autosize();
    this.relocate();
  };
  
  this.hideAll = function() {
    this.popup.animate({'opacity':'0'}, this.delay, function() { popup.animateOveralyOut(); });
  };
  
  this.animateOveralyOut = function() {
    this.popup.hide();
    this.overlay.animate({'opacity':'0'}, this.delay, function() { popup.hideOverlay(); });
  };
  
  this.hideOverlay = function() {
    this.overlay.hide();
  };
  
  this.paddingVertical = function() {
    $c = this.popup.find('.message');
    return (parseInt($c.css('padding-top')) + parseInt($c.css('padding-bottom')));
  };
  
  this.paddingHorizontal = function() {
    $c = this.popup.find('.message');
    return (parseInt($c.css('padding-left')) + parseInt($c.css('padding-right')));
  };
  
  this.autosize = function() {
    $center = this.popup.find('.message');
    this.resize($center.width() + this.paddingHorizontal(), $center.height() + this.paddingVertical());
  };
  
  this.resize = function(width, height) {
    $center = this.popup.find('.message');
    $center.css({
      'height':height - this.paddingVertical() + 'px',
      'width':width - this.paddingHorizontal() + 'px'
    });
  };
  
  this.relocate = function() {
    this.popup.css({
      'top':($(window).height() / 2 - this.popup.height() / 2) + 'px',
      'left':($(window).width() / 2 - this.popup.width() / 2) + 'px'
    });
  };
  
  this.adjustPopup = function() {
    this.popup.css('opacity', '0');
    this.popup.find('.close').bind({
      click: function() {
        popup.hideAll();
      }
    });
  };
  
  this.adjustOverlay = function() {
    this.overlay.css('opacity', '0');
    this.overlay.bind({
      click: function() {
        popup.hideAll();
      }
    });
  };
}
var popup = new Popup();
