/*
 * Popup fade box
 *
 **/
 
(function($) {

fadeBox = function(options) {
  options = $.extend({}, fadeBox.defaults, options);
  var $document = $(document);
  var boxContainer, boxBG, boxContainer, boxLayout, boxTitle, boxBody;
  boxBG = $('<div id="fadeBoxBG" style="display:none"></div>').appendTo('body');
  boxContainer = $('<div id="fadeBoxContainer" style="display:none"></div>').insertAfter(boxBG);
  boxLayout = $('<div id="boxLayout"></div>').appendTo(boxContainer);
  boxTitle = $('<div id="boxTitle"></div>').appendTo(boxLayout).wrap('<div id="boxTitleWrap"></div>');
  boxBody = $('<div id="boxBody"></div>').appendTo(boxLayout);

  boxBG.height($document.height());

  $(document).keydown(function(e){
    if (e.keyCode == 27) {
      hide();
    }
  });

  refreshCoords();
  refreshBox();

  // Refresh box position
  function refreshCoords() {
    var height = window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight)

    boxContainer.css({
      top: $document.scrollTop() + (height - boxContainer.height()) / 3,
      marginLeft: - boxContainer.width() / 2
    });
  }

  // Refresh box properties
  function refreshBox() {
    // Set title
    boxTitle.html(options.title);

    // Set box dimensions
    boxContainer.width(options.width);
    boxContainer.height(options.height);

    boxContainer.removeClass();
    boxContainer.unbind('click');
    if (options.hideOnClick) {
      boxContainer.click(function(){
        hide();
      });
    }
    boxContainer.addClass('popupBox');
    boxBG.click(function(){
    hide();
    });
  }

  // Show box
  function show() {
    refreshCoords();
    // Show blocking background
    boxBG.show();
    // Show box
    boxContainer.fadeIn('slow', options.onShow);
  }
  // Hide box
  function hide() {
    boxContainer.fadeOut('slow', function(){
      boxBG.hide();
      if (options.onHide) options.onHide();
    });
  }

  return {

    // Show box
    show: function() {
      show(); return this;
    },

    // Hide box
    hide: function() {
      hide(); return this;
    },

    // Insert html content into the box
    content: function(html) {
      boxBody.html(html);
      return this;
    },

    // Update box options
    setOptions: function(newOptions) {
      options = $.extend({}, options, newOptions);
      refreshBox();
      return this;
    }
  };
};

fadeBox.defaults = {
  hideOnClick: true,
  title: "Alert",
  width: "auto",
  height: "auto"
};

})(jQuery);