if (typeof $.bb == 'undefined') $.bb = {};

$.bb.dialog = function(id,url,options) {
  var settings = $.extend({
    caption: 'Dialog',
    onshow: function(dialog){}
  },options);
  settings.id = id;
  settings.url = url;
  //
  // Create the curtain, if not already done
  //
  if ($('#bbDialogCurtain').length==0) {
    $('<div></div>')
      .attr('id','bbDialogCurtain')
      .appendTo('body');
    $('#bbDialogCurtain').hide();
  }
  //
  // If not previously done, create the dialog chrome
  //
  if ($('#'+id).length==0) {
    $('<div></div>')
      .attr('id',id)
      .addClass('bbDialogBox')
      .appendTo('body')
      .append(
        $('<div></div>')
          .addClass('bbDialogCaptionBar')
          .append(
            $('<div></div>').text(settings.caption)
          )
          .append(
            $('<img>')
              .attr('src',bb.contextPath+'/resources/images/dialog.close.gif')
              .click(function(){ $('#'+id).bbDismissDialog() })
          )
       )
      .append(
        $('<div></div>')
          .addClass('bbDialogBody')
       );
    $('#'+id)
      .hide()
      [0].settings = settings;
  }
}

$.fn.bbShowDialog = function() {
  if (!this.is('div.bbDialogBox')) return;
  this.each(function(){
    var box = this;
    var settings = box.settings;
    $('<div>Loading...</div>')
       .appendTo($('.bbDialogBody',box));
    $('.bbDialogBody',box).load(settings.url,function(){
      $('#bbDialogCurtain')
        .css({
          width: $(document).width(),
          height: $(document).height()
        })
        .show();
      $(box)
        .css({
          top: ($('body').height() - $(box).height())/2,
          left: ($('body').width() - $(box).width())/2
        })
        .show();
      settings.onshow(box);
      if (typeof box.onshow=='function') box.onshow(box);
    });
  });
}

$.fn.bbDismissDialog = function() {
  if (!this.is('div.bbDialogBox')) return;
  this.hide();
  $('#bbDialogCurtain').hide();
}
