var darkbox =
{
  divBackground: null,
  divBox:        null,
  divClose:      null,
  
  width:         320,
  height:        240,
  
  labels:
  {
    'close': 'Close'
  },
  
  background:
  {
    'color': '#000',
    'opacity': .5
  },
  
  style:
  {
    'padding': 5
  },
  
  initialized: false,
  init: function()
  {
    if (this.initialized) return;
        
    this.divBox = $('<div/>').css({
      'position': 'fixed',
      'background': '#fff',
      'padding': this.style.padding + 'px',
      'z-index': 11,
      'top': '50%',
      'left': '50%'
    }).hide();
    
    this.divBackground = $('<div/>').css({
      'position': 'fixed',
      'background': this.background.color,
      'top': 0,
      'left': 0,
      'width': '100%',
      'height': '100%',
      'z-index': 10,
      'opacity': this.background.opacity
    }).hide();
    
    this.divClose = $('<div/>').css({
      'position': 'absolute',
      'z-index': 13,
      'top': '5px',
      'right': '5px',
      'background': '#fff',
      'padding': this.style.padding + 'px',
      'font-weight': 'bold',
      'color': '#444',
      'font-size': '14px',
      'cursor': 'pointer'
    }).append(this.labels.close);
    
    var darkbox = this;
    this.close = function()
    {
      darkbox.divBackground.hide();
      darkbox.divBox.fadeOut();
    };
    
    this.divBackground.click(this.close);
    
    $('body').append(this.divBackground).append(this.divBox);
    
    this.initialized = true;
  },
  
  calculateSizes: function()
  {
    var body = $('body')[0];
    var viewportHeight = window.innerHeight;
    if (!viewportHeight) viewportHeight = body.clientHeight;
    var documentHeight = body.scrollHeight;
    
    if (this.height + (2 * this.style.padding) > viewportHeight)
      this.divBox.css({
        'top': 0,
        'margin-top': 0,
        'position': 'absolute'
      });
    else
      this.divBox.css({
        'top': '50%',
        'margin-top': '-' + parseInt(this.height / 2) + 'px',
        'position': 'fixed'
      });
    
    this.divBox.css('margin-left', '-' + parseInt(this.width/2) + 'px');
  },
  
  show: function(dom)
  {
    this.init();
    this.calculateSizes();
    this.divBackground.show();
    this.divBox.empty().append(dom).append(this.divClose.click(this.close)).fadeIn('slow');
  },
  
  showImage: function(url, width, height)
  {
    if (width == undefined) width = this.width;
    else this.width = width;
    
    if (height == undefined) height = this.height;
    else this.height = height;

    this.show(
      $('<img src="' + url + '" width="' + width + '" height="' + height + '"/>').
        css('z-index', 12));
  }
}
