/******************************************************************************
  MUBI jQuery Modal Dialog Plugin
  Creates a standard modal dialog for MUBI

  Usage:
  $('a.modal').modalDialog({ id: 'list_embedder', width: 600, reload: false });

  Parameters:
    id:     (string)  The ID of the modal dialog window container
    title:  (string)  The title displayed at the top of the modal dialog
    width:  (integer) The width of the modal dialog
    reload: (boolean) Specifies whether the contents of the modal dialog
                      should be reloaded every time it's opened

    NOTE: The action in the controller that launches the modal dialog should
          render with :layout => false
******************************************************************************/

(function($) {
  $.fn.modalDialog = function( settings ) {
    var defaults = {
      'id': 'modal_dialog',
      'reload': false,
      'width': 700
    };

    if ( settings ) $.extend( defaults, settings );

    this.each( function() {
      var container = $(settings.id);

      $(this).click( function(e) {
        // This check requires jQuery 1.4+
        // Prior to 1.4 jQuery returns the document element when no matching elements are found.
        if ( container.length == 0 )
        {
          container = $('<div />', { id: settings.id }).appendTo('body').dialog({
            autoOpen: false,
            position: 'top',
            width: settings.width,
            resizable: false,
            draggable: false,
            modal: true,
            closeText: '',
            title: settings.title,
            dialogClass: 'mubi_modal_dialog'
          });
        }

        if ( container.contents().length == 0 || settings.reload )
        {
          container.load( $j(this).attr('href'), function() {
            container.dialog('open');
          });
        }
        else
        {
          container.dialog('open');
        }
        
        e.preventDefault();
        return false;
      });
    });

    return this;
  };
})(jQuery);
