From b683bc329cdb507a5d5a705f17dbd58b961765e3 Mon Sep 17 00:00:00 2001
From: James Elliott <james.elliott@acquia.com>
Date: Mon, 25 Apr 2011 18:15:24 -0400
Subject: [PATCH 13/15] WYSIWYG still broken

---
 css/media.css                                |    9 +-
 includes/media.admin.inc                     |    6 +-
 includes/media.browser.inc                   |  134 ++++++++++++++++----------
 includes/media.filter.inc                    |   44 +++++++++
 includes/media.pages.inc                     |   43 +++++++--
 js/media.dialog.js                           |   38 ++++----
 js/media.format_form.js                      |   10 +--
 js/media.js                                  |   31 ++-----
 js/media.thumbnails.js                       |    2 +-
 js/plugins/media.library.js                  |   26 +++---
 js/plugins/media.upload_multiple.js          |    6 -
 js/wysiwyg-media.js                          |   23 +++--
 media.api.php                                |   54 ++--------
 media.module                                 |   52 ++++++++---
 modules/media_internet/media_internet.module |   25 +-----
 wysiwyg_plugins/media.inc                    |    7 +-
 16 files changed, 281 insertions(+), 229 deletions(-)

diff --git a/css/media.css b/css/media.css
index 17c18fe..97e31f1 100644
--- a/css/media.css
+++ b/css/media.css
@@ -13,12 +13,15 @@
   margin-bottom: 10px;
 }
 #media-display-switches .form-media-display {
-  background: #f2f1f1;
+  background-color: #f2f1f1;
+  background-position: center center;
+  background-repeat: no-repeat;
   border: 1px solid;
   border-color: #e4e4e4 #d2d2d2 #b4b4b4 #d3d3d3;
   display: block;
   float: left;
-  padding: 7px 9px;
+  text-indent: -2000px;
+  padding: 4px 15px;
 }
 #media-display-switches .form-media-display:first-child {
   -moz-border-radius-topleft: 4px;
@@ -34,7 +37,7 @@
 }
 #media-display-switches .form-media-display.active {
   position: relative;
-  background: #666;
+  background-color: #666;
   border: 1px solid #555;
   color: #fff;
 }
diff --git a/includes/media.admin.inc b/includes/media.admin.inc
index 13f1a79..1d7e0e4 100644
--- a/includes/media.admin.inc
+++ b/includes/media.admin.inc
@@ -49,7 +49,7 @@ function media_admin($form, $form_state) {
     '#type' => 'submit',
     '#value' => t('Submit'),
     '#submit' => array('media_admin_submit'),
-    '#validate' => array('media_admin_validate'),
+    '#validate' => array('media_admin_delete_validate'),
   );
   
   module_load_include('inc', 'media', '/includes/media.browser');
@@ -62,6 +62,7 @@ function media_admin($form, $form_state) {
           '.action-links a[href="/admin/content/media/add"]' => array(
             'submit' => array(
               'disabledPlugins' => array('library'),
+              'trigger' => 'media-admin-base',
             ),
             'url' => '/media/browser',
             'base' => 'media-admin-base',
@@ -84,8 +85,9 @@ function media_admin($form, $form_state) {
  * Check if any files have been selected to perform the chosen
  * 'Update option' on.
  */
-function media_admin_validate($form, &$form_state) {
+function media_admin_delete_validate($form, &$form_state) {
   $files = array_filter($form_state['values']['files']);
+
   if (count($files) == 0) {
     form_set_error('', t('No items selected.'));
   }
diff --git a/includes/media.browser.inc b/includes/media.browser.inc
index d254791..cd0dc4b 100644
--- a/includes/media.browser.inc
+++ b/includes/media.browser.inc
@@ -27,20 +27,39 @@ function media_form_media_browser_form_alter(&$form, &$form_state, $form_id) {
         'path' => 'media/browser/cancel',
       ),
     ),
+    'trigger' => array(
+      '#type' => 'hidden',
+      '#value' => isset($form_state['values']['trigger']) ? $form_state['values']['trigger'] : $_POST['trigger'],
+    ),
+    '#weight' => 1000,
   );
 }
 
 function media_browser_select($form, &$form_state) {
-  if (!form_get_errors() && isset($form_state['values']['fids'])) {
-    $command = array(
+  $commands = array();
+  if (!form_get_errors() && isset($form_state['values']['fids']) && count($form_state['values']['fids']) > 0) {
+    $selected = $form_state['values']['fids'];
+    if (!is_array($form_state['values']['fids'])) {
+      $selected = array($form_state['values']['fids']);
+    }
+    if (!is_numeric($selected[0])) {
+      throw new Exception('Error selecting media, fid param is not an fid or an array of fids');
+    }
+    $selectedMedia = entity_load('media', $selected);
+    foreach ($selectedMedia as &$media) {
+      media_browser_build_media_item($media);
+    }
+    
+    $commands[] = array(
       'command' => 'mediaBrowserSelected',
-      'files' => $form_state['values']['fids'],
+      'files' => array_values($selectedMedia),
+      'trigger' => $_POST['trigger'],
     );
+    
   } else {
-    $command = media_browser_refresh($form, $form_state);
+    $commands = media_browser_refresh($form, $form_state);
   }
-
-  return $command;
+  return $commands;
 }
 
 function media_browser_dismiss() {
@@ -52,21 +71,21 @@ function media_browser_dismiss() {
   return array('#type' => 'ajax', '#commands' => $commands);
 }
 
-function media_browser_messages() {
-  $messages = theme('status_messages');
-  return array(
-    'command' => 'mediaBrowserMessages',
-    'data' => $messages,
-  );
-}
-
 function media_browser_refresh($form, &$form_state) {
-  return array(
+  $commands[] = array(
     'command' => 'insert',
     'method' => 'replaceWith',
     'data' => drupal_render($form),
     'selector' => '#' . strtr($form_state['values']['form_id'], '_', '-'),
   );
+  
+  $messages = theme('status_messages');
+  $commands[] = array(
+    'command' => 'mediaBrowserMessages',
+    'data' => $messages,
+  );
+  
+  return $commands;
 }
 
 function media_browser_launch() {
@@ -92,7 +111,7 @@ function media_browser() {
       $callback = $form_state['triggering_element']['#ajax']['callback'];
     }
     if (!empty($callback) && function_exists($callback)) {
-      $commands[] = $callback($form, $form_state);
+      $commands = $callback($form, $form_state);
     }
   }
 
@@ -101,9 +120,7 @@ function media_browser() {
   
 function media_browser_forms() {
   $build = array();
-  
-  $_POST['disabledPlugins'] = array('library');
-  
+
   $params = array_merge(drupal_get_query_parameters(), drupal_get_query_parameters($_POST));
   array_walk_recursive($params, '_media_recursive_check_plain');
   media_set_browser_params($params);
@@ -118,9 +135,8 @@ function media_browser_forms() {
   
   $tabs = array(); // List of tabs to render.
   
-  $browser_settings = array('media' => array('dialog' => array()));
-  
-  $output = array();
+  $browser_settings = array('media' => array('dialog' => array('params' => $params)));
+  drupal_add_js($browser_settings, 'setting');
   
   foreach ($plugins as $key => $plugin) {
     // If this is a "ajax" style tab, add the href, otherwise an id.
@@ -138,14 +154,13 @@ EOS;
     $form_state = array(
       'build_info' => array(
         'base_form_id' => 'media_browser_form',
+        'params' => $params,
       ),
     );
     $plugin['form'] = drupal_build_form($plugin['#form_id'], $form_state);
     $plugins[$key] = $plugin;
   }
   
-  drupal_add_js($browser_settings, 'setting');
-  
   $build['tabset'] = array(
     '#prefix' => '<div id="media-browser-tabset">',
     '#suffix' => '</div>',
@@ -240,15 +255,14 @@ function media_browser_get_plugins($params = array()) {
   $plugins = array();
   // Normal browser operation.
   foreach (module_implements('media_browser_plugin_info') as $module) {
-    foreach(module_invoke($module, 'media_browser_plugin_info') as $key => $plugin_data) {
+    foreach(module_invoke($module, 'media_browser_plugin_info', $params) as $key => $plugin_data) {
       $plugins[$key] = $plugin_data + array(
         '#module' => $module,
         '#weight' => 0,
       );
-      $plugins[$key]['#weight'] += count($plugins)/1000;
     }
   }
-  
+
   // Only the plugins in this array are loaded.
   if (!empty($params['enabledPlugins'])) {
     $plugins = array_intersect_key($plugins, array_fill_keys($params['enabledPlugins'], 1));
@@ -256,6 +270,9 @@ function media_browser_get_plugins($params = array()) {
   elseif (!empty($params['disabledPlugins'])) {
     $plugins = array_diff_key($plugins, array_fill_keys($params['disabledPlugins'], 1));
   }
+  
+  uasort($plugins, 'element_sort');
+
   return $plugins;
 }
 
@@ -268,6 +285,7 @@ function media_browser_table() {
   $params = array_merge(drupal_get_query_parameters(), drupal_get_query_parameters($_POST));
   $limit = isset($params['limit']) ? $params['limit'] : variable_get('media_admin_limit', 50);
   $types = isset($params['types']) ? $params['types'] : media_type_get_types();
+  $no_ops = isset($params['no_ops']) ? TRUE : FALSE;
 
   // Build the sortable table header.
   $header = array(
@@ -276,8 +294,11 @@ function media_browser_table() {
    'size' => array('data' => t('Size'), 'field' => 'f.filesize'),
    'author' => array('data' => t('Author'), 'field' => 'u.name'),
    'timestamp' => array('data' => t('Updated'), 'field' => 'f.timestamp', 'sort' => 'asc'),
-   'operations' => array('data' => t('Operations')),
   );
+  
+  if (!$no_ops) {
+    $header['operations'] = array('data' => t('Operations'));
+  }
 
   $query = db_select('file_managed', 'f')->extend('PagerDefault')->extend('TableSort');
   $query->join('users', 'u', 'f.uid = u.uid');
@@ -310,7 +331,10 @@ function media_browser_table() {
       'author' => theme('username', array('account' => $file)),
       'timestamp' => format_date($file->timestamp, 'short'),
     );
-    $options[$file->fid]['operations'] = l(t('edit'), 'media/' . $file->fid . '/edit', array('query' => $destination));
+    
+    if (!$no_ops) {
+      $options[$file->fid]['operations'] = l(t('edit'), 'media/' . $file->fid . '/edit', array('query' => $destination));
+    }
     
     // For some reason form_process_tableselect doesn't add these children on AJAX refresh
     $form['files'][$file->fid] = array(
@@ -336,6 +360,7 @@ function media_browser_thumbnails() {
   $params = array_merge(drupal_get_query_parameters(), drupal_get_query_parameters($_POST));
   $limit = isset($params['limit']) ? $params['limit'] : variable_get('media_admin_limit', 50);
   $types = isset($params['types']) ? $params['types'] : media_type_get_types();
+  $no_ops = isset($params['no_ops']) ? TRUE : FALSE;
 
   $query = new EntityFieldQuery();
 
@@ -356,23 +381,26 @@ function media_browser_thumbnails() {
   drupal_add_css($path . '/css/media.thumbnails.css');
   drupal_add_js($path . '/js/media.thumbnails.js');
   
-  $form['select_all'] = array(
-    '#theme' => 'links',
-    '#links' => array(
-      'all' => array(
-        'title' => 'all,',
-        'href' => '#',
-        'attributes' => array('class' => array('select')),
-      ),
-      'none' => array(
-        'title' => 'none',
-        'href' => '#',
-        'attributes' => array('class' => array('deselect')),
+  if (!isset($params['singleselect'])) {
+    $form['select_all'] = array(
+      '#theme' => 'links',
+      '#links' => array(
+        'all' => array(
+          'title' => 'all,',
+          'href' => '#',
+          'attributes' => array('class' => array('select')),
+        ),
+        'none' => array(
+          'title' => 'none',
+          'href' => '#',
+          'attributes' => array('class' => array('deselect')),
+        ),
       ),
-    ),
-    '#prefix' => '<div class="media-thumbnails-select"><strong>' . t('Select') . ':</strong>',
-    '#suffix' => '</div>',
-  );
+      '#prefix' => '<div class="media-thumbnails-select"><strong>' . t('Select') . ':</strong>',
+      '#suffix' => '</div>',
+    );
+  }
+  
 
   $destination = drupal_get_destination();
   $rows = array();
@@ -385,7 +413,7 @@ function media_browser_thumbnails() {
 
   if (count($media_entities)) {
     foreach ($media_entities as $media) {
-     $preview = media_get_thumbnail_preview($media, TRUE);
+     $preview = media_get_thumbnail_preview($media, !$no_ops);
      $form['files'][$media->fid] = array(
        '#type' => 'checkbox',
        '#title' => '',
@@ -420,15 +448,21 @@ function media_browser_display_switch() {
       $icon = $item['icon_active'];
       $attributes['class'][] = 'active';
     }
+    $attributes['style'] = 'background-image: url("' . base_path() . $icon . '");';
     
     $links[$delta] = array(
-      '#type' => 'image_button',
+      '#type' => 'button',
       '#button_type' => 'media-display',
       '#title' => $delta,
       '#value' => $delta,
+      '#name' => $delta,
       '#src' => $icon,
       '#ajax' => array(
         'path' => 'media/browser/ajax/' . $delta,
+        'submit' => array(
+          'limit' => isset($_POST['limit']) ? $_POST['limit'] : variable_get('media_admin_limit', 50),
+          'no_ops' => isset($_POST['no_ops']) ? $_POST['no_ops'] : '',
+        ),
       ),
       '#attributes' => $attributes,
       '#limit_validation_errors' => array(),
@@ -478,7 +512,7 @@ function media_get_browser_params() {
 /**
  * Implements hook_media_browser_plugin_info().
  */
-function media_media_browser_plugin_info() {
+function media_media_browser_plugin_info($params) {
   $plugins = array();
   module_load_include('inc', 'media', '/includes/media.pages');
   
@@ -486,11 +520,11 @@ function media_media_browser_plugin_info() {
   $plugins['library'] = array(
     '#title' => 'library',
     '#form_id' => 'media_library_form',
-    '#weight' => 10,
+    '#weight' => 10000,
   );
 
   if (user_access('administer media') || user_access('edit media')) {
-    if (FALSE && module_exists('plupload')) {
+    if (!isset($params['singleselect']) && module_exists('plupload')) {
       $upload_form_id = 'media_add_upload_multiple';
     }
     else {
diff --git a/includes/media.filter.inc b/includes/media.filter.inc
index 0930699..cdc9a39 100644
--- a/includes/media.filter.inc
+++ b/includes/media.filter.inc
@@ -240,6 +240,23 @@ function _media_generate_tagMap($text) {
   return $tagmap;
 }
 
+function media_format($media) {
+  $commands = array();
+  
+  if (!isset($_POST['form_id'])) {
+    $commands[] = array(
+      'command' => 'mediaBrowserLaunch',
+      'data' => drupal_render(drupal_get_form('media_format_form', $media)),
+    );
+  } else {
+    $commands[] = array(
+      'command' => 'mediaFormatSelected',
+    );
+  }
+  
+  return array('#type' => 'ajax', '#commands' => $commands);
+}
+
 /**
  * Form callback used when embedding media.
  *
@@ -335,6 +352,33 @@ function media_format_form($form, $form_state, $media) {
   if (!element_children($form['options'])) {
     $form['options']['#attributes'] = array('style' => 'display:none');
   }
+  
+  $form['actions'] = array(
+    $form_id . '-submit' => array(
+      '#type' => 'submit',
+      '#value' => t('Okay'),
+      '#ajax' => array(
+        'path' => 'media/' . $media->fid . '/format-form',
+      ),
+      '#name' => 'process',
+    ),
+    $form_id . '-cancel' => array(
+      '#type' => 'button',
+      '#value' => t('Cancel'),
+      '#name' => 'cancel',
+      '#limit_validation_errors' => array(),
+      '#executes_submit_callback' => FALSE,
+      '#ajax' => array(
+        'callback' => 'media_browser_dismiss',
+        'path' => 'media/browser/cancel',
+      ),
+    ),
+    'trigger' => array(
+      '#type' => 'hidden',
+      '#value' => isset($form_state['values']['trigger']) ? $form_state['values']['trigger'] : $_POST['trigger'],
+    ),
+    '#weight' => 1000,
+  );
 
   return $form;
 }
diff --git a/includes/media.pages.inc b/includes/media.pages.inc
index 1f2376e..77507c0 100644
--- a/includes/media.pages.inc
+++ b/includes/media.pages.inc
@@ -175,7 +175,9 @@ function media_multiple_delete_confirm_submit($form, &$form_state) {
  * Form callback for adding media via an upload form.
  * @todo: should use the AJAX uploader
  */
-function media_add_upload($form, &$form_state, $types = NULL) {
+function media_add_upload($form, &$form_state) {
+  $types = isset($form_state['build_info']['params']['params']['types']) ? $form_state['build_info']['params']['params']['types'] : '';
+  
   $validators = array(
    'file_validate_extensions' => array(media_variable_get('file_extensions')),
    'file_validate_size' => array(parse_size(media_variable_get('max_filesize'))),
@@ -247,9 +249,9 @@ function media_add_upload_validate($form, &$form_state) {
   }
 }
 
-function media_add_upload_multiple($form, &$form_state, $types) {
-  $form = media_add_upload($form, $form_state, $types);
-  $form['#attached']['js'] = array($path . '/js/plugins/media.upload_multiple.js');
+function media_add_upload_multiple($form, &$form_state) {
+  $form = media_add_upload($form, $form_state);
+  $form['#attached']['js'] = array(drupal_get_path('module', 'media') . '/js/plugins/media.upload_multiple.js');
   
   unset($form['upload']['#title']);
   // The validators will be set from plupload anyway.  This isn't pretty, but don't
@@ -257,7 +259,6 @@ function media_add_upload_multiple($form, &$form_state, $types) {
   unset($form['upload']['#description']);
   
   $form['upload']['#type'] = 'plupload';
-  $form['submit']['#value'] = t('Start upload');
   return $form;
 }
 
@@ -287,11 +288,17 @@ function media_add_upload_multiple_submit($form, &$form_state) {
     }
   }
   // Get a list of fids to pass back.
-  $fids = array();
-  foreach ($saved_files as $file) {
-    $fids[] = $file->fid;
+  if (count($saved_files) > 0) {
+    $fids = array();
+    foreach ($saved_files as $file) {
+      $fids[] = $file->fid;
+    }
+    $form_state['values']['fids'] = $fids;
+    drupal_set_message(t('Files in the queue were successfully uploaded'));
+  } else {
+    form_set_error('upload', t('No files were selected to be uploaded'));
+    return;
   }
-  $form_state['redirect'] = array('media/browser', array('query' => array('render' => 'media-popup', 'fid' => $fids)));
 }
 
 /**
@@ -417,6 +424,24 @@ function media_add_remote($form, &$form_state) {
 }
 
 function media_library_form($form, &$form_state) {
+  $path = drupal_get_path('module', 'media');
+  drupal_add_js($path . '/js/plugins/media.library.js');
+  drupal_add_css($path . '/css/media.library.css');
+  
+  // Disable operations when rendering the media listings
+  $_POST['no_ops'] = TRUE;
+  
   $form['browser'] = media_browser_build();
   return $form;
 }
+
+function media_library_form_validate($form, &$form_state) {
+  foreach($form_state['values']['files'] as $key => $file) {
+    if ($file) {
+      $form_state['values']['fids'][] = $key;
+    }
+  }
+  if (!isset($form_state['values']['fids'])) {
+    form_set_error('files', t('No files selected'));
+  }
+}
diff --git a/js/media.dialog.js b/js/media.dialog.js
index 7f8b5ff..158139e 100644
--- a/js/media.dialog.js
+++ b/js/media.dialog.js
@@ -6,17 +6,19 @@ Drupal.media.dialog = Drupal.media.dialog || {};
 Drupal.behaviors.dialog = {
   attach: function (context, settings) {
     // Enable any dialog launchers
-    for(var launcher in settings.media.dialog.launchers) {
-      $(launcher, context).once('media-launcher', function() {
-        var $this = $(this);
-        var element_settings = $.extend(Drupal.media.dialog.ajaxDefaults(), settings.media.dialog.launchers[launcher]);
-        var id = $this.attr('id');
-        if (!id) {
-          id = element_settings.base;
-          $this.attr('id', element_settings.base);
-        }
-        Drupal.ajax[id] = new Drupal.ajax(id, this, element_settings);
-      });
+    if (typeof settings.media.dialog != 'undefined' && typeof settings.media.dialog.launchers != 'undefined') {
+      for(var launcher in settings.media.dialog.launchers) {
+        $(launcher, context).once('media-launcher', function() {
+          var $this = $(this);
+          var element_settings = $.extend(Drupal.media.dialog.ajaxDefaults(), settings.media.dialog.launchers[launcher]);
+          var id = $this.attr('id');
+          if (!id) {
+            id = element_settings.base;
+            $this.attr('id', element_settings.base);
+          }
+          Drupal.ajax[id] = new Drupal.ajax(id, this, element_settings);
+        });
+      }
     }
   }
 };
@@ -38,11 +40,11 @@ Drupal.media.dialog.defaults = function () {
   return {
     modal: true,
     width: '80%',
-    maxHeight: '80%',
     resizable: false,
     draggable: false,
     autoOpen: false,
-    close: Drupal.media.dialog.close
+    close: Drupal.media.dialog.close,
+    position: ['center', 50]
   };
 };
 
@@ -53,7 +55,7 @@ Drupal.media.dialog.close = function () {
 
 Drupal.media.dialog.tabs = function (wrapper, tab) {
   $('#media-browser-tabset', wrapper).tabs({
-    show: Drupal.media.dialog.tabSwitch,
+    show: 'yes', 
     selected: tab
   });
 };
@@ -76,13 +78,7 @@ Drupal.ajax.prototype.commands.mediaBrowserLaunch = function (ajax, response, st
 
 Drupal.ajax.prototype.commands.mediaBrowserSelected = function (ajax, response, status) {
   $('#media-browser-wrapper').dialog('close');
-//  var $messages = $('.messages');
-//  if ($messages.length) {
-//    $messages.replaceWith(response.data);
-//  } else {
-//    $('#page').prepend(response.data);
-//  }
-  $(window).trigger('mediaBrowserSelect', response.files);
+  $('#' + response.trigger).trigger('mediaBrowserSelect', {files: response.files});
 };
 
 Drupal.ajax.prototype.commands.mediaBrowserMessages = function (ajax, response, status) {
diff --git a/js/media.format_form.js b/js/media.format_form.js
index a2755bb..43ea6e0 100644
--- a/js/media.format_form.js
+++ b/js/media.format_form.js
@@ -14,15 +14,7 @@ Drupal.media.mediaFormatSelected = {};
 
 Drupal.behaviors.mediaFormatForm = {
   attach: function (context, settings) {
-    // Add "Submit" and "Cancel" buttons inside the IFRAME that trigger the
-    // behavior of the hidden "OK" and "Cancel" buttons that are outside the
-    // IFRAME. See Drupal.media.browser.validateButtons() for more details.
-    $('<a class="button fake-ok">Submit</a>').appendTo($('#media-format-form')).bind('click', Drupal.media.formatForm.submit);
-    $('<a class="button fake-cancel">Cancel</a>').appendTo($('#media-format-form')).bind('click', Drupal.media.formatForm.submit);
-
-    if (Drupal.settings.media_format_form.autosubmit) {
-      $('.button.fake-ok').click();
-    }
+    
   }
 };
 
diff --git a/js/media.js b/js/media.js
index d135c86..35be59c 100644
--- a/js/media.js
+++ b/js/media.js
@@ -17,11 +17,6 @@ Drupal.behaviors.mediaElement = {
     
     // For each widget (in case of multi-entry)
     $('.media-widget', context).once('mediaBrowserLaunch', function () {
-      var options = settings.media.elements[this.id];
-      globalOptions = {};
-      if (options.global != undefined) {
-        var globalOptions = options.global;
-      }
       //options = Drupal.settings.media.fields[this.id];
       var fidField = $('.fid', this);
       var previewField = $('.preview', this);
@@ -31,28 +26,16 @@ Drupal.behaviors.mediaElement = {
       if (fidField.val() != 0) {
         removeButton.css('display', 'inline-block');
       }
-
-      // When someone clicks the link to pick media (or clicks on an existing thumbnail)
-      $('.launcher', this).bind('click', function () {
-        // Launch the browser, providing the following callback function
-        // @TODO: This should not be an anomyous function.
-        Drupal.media.popups.mediaBrowser(function (mediaFiles) {
-          if (mediaFiles.length < 0) {
-            return;
-          }
-          var mediaFile = mediaFiles[0];
-          // Set the value of the filefield fid (hidden).
-          fidField.val(mediaFile.fid);
-          // Set the preview field HTML.
-          previewField.html(mediaFile.preview);
-          // Show the Remove button.
-          removeButton.show();
-        }, globalOptions);
-        return false;
+      
+      // Bind the action for when media is selected
+      $(this).bind('mediaBrowserSelect', function(event, data) {
+        previewField.html(data.files[0].preview);
+        fidField.val(data.files[0].fid);
+        removeButton.css('display', 'inline-block');
       });
 
       // When someone clicks the Remove button.
-      $('.remove', this).bind('click', function () {
+      removeButton.bind('click', function () {
         // Set the value of the filefield fid (hidden).
         fidField.val(0);
         // Set the preview field HTML.
diff --git a/js/media.thumbnails.js b/js/media.thumbnails.js
index 3e0372a..e2df658 100644
--- a/js/media.thumbnails.js
+++ b/js/media.thumbnails.js
@@ -27,7 +27,7 @@ Drupal.media.thumbnails.selectNone = function (event) {
 };
 
 Drupal.media.thumbnails.itemClick = function (event) {
-  if ($(event.target).is('img, a')) {
+  if ($(event.target).is('a img, a')) {
     return;
   }
   var checkbox = $(this).parent().find(':checkbox');
diff --git a/js/plugins/media.library.js b/js/plugins/media.library.js
index bcb1bd1..e228a4a 100644
--- a/js/plugins/media.library.js
+++ b/js/plugins/media.library.js
@@ -2,24 +2,26 @@
 (function ($) {
 
 Drupal.media = Drupal.media || {};
-Drupal.media.browser = Drupal.media.browser || {};
+Drupal.media.library = Drupal.media.library || {};
 
 Drupal.behaviors.mediaLibrary = {
   attach: function (context, settings) {
-
+    var callback = Drupal.media.library.multiSelect;
+    
+    if (settings.media.dialog.params.singleselect) {
+      callback = Drupal.media.library.singleSelect;
+      $('#media-library-form', context).addClass('single-select');
+    }
+    
+    $('#media-library-form input[type=checkbox]', context).bind('change', callback);
   }
 };
 
-Drupal.media.browser.library.prototype.mediaSelected = function (media) {
-  Drupal.media.browser.selectMedia(media);
-};
-
-Drupal.media.browser.library.prototype.singleSelect = function (event) {
-  
-}
-
-Drupal.media.browser.library.prototype.multiSelect = function (event) {
-  
+Drupal.media.library.singleSelect = function (event) {
+  event.preventDefault();
+  var checkboxes = $('#media-library-form input[type=checkbox]:checked').not(this)
+  checkboxes.attr('checked', false);
+  $('#media-library-form .selected').removeClass('selected');
 }
 
 }(jQuery));
diff --git a/js/plugins/media.upload_multiple.js b/js/plugins/media.upload_multiple.js
index c82826b..b80627a 100755
--- a/js/plugins/media.upload_multiple.js
+++ b/js/plugins/media.upload_multiple.js
@@ -4,10 +4,4 @@ Drupal.behaviors.mediaUploadMultiple.attach = function (context, settings) {
   // When the plupload element initializes, it expands the size of the elements
   // it has created, so we need to resize the browser iframe after it's done.
   var uploader = jQuery('#edit-upload').pluploadQueue();
-  if (uploader) {
-    // Handle the case in which the uploader has already finished initializing.
-    Drupal.media.browser.resizeIframe();
-    // Handle the case in which the uploader has not yet initialized.
-    uploader.bind("PostInit", Drupal.media.browser.resizeIframe);
-  }
 };
diff --git a/js/wysiwyg-media.js b/js/wysiwyg-media.js
index 156229a..97dadf2 100644
--- a/js/wysiwyg-media.js
+++ b/js/wysiwyg-media.js
@@ -25,9 +25,16 @@ Drupal.wysiwyg.plugins.media = {
    */
   invoke: function (data, settings, instanceId) {
     if (data.format == 'html') {
-      Drupal.media.popups.mediaBrowser(function (mediaFiles) {
-        Drupal.wysiwyg.plugins.media.mediaBrowserOnSelect(mediaFiles, instanceId);
-      }, settings['global']);
+//      if (typeof Drupal.ajax[instanceId] == 'undefined') {
+//        var element_settings = Drupal.media.dialog.ajaxDefaults();
+//        element_settings.event = 'launchWYSIWYG';
+//        
+//        settings.trigger = instanceId;
+//        element_settings.submit = settings;
+//        
+//        Drupal.ajax[instanceId] = new Drupal.ajax(instanceId, $('#' + instanceId), element_settings);
+//      }
+//      $('#' + instanceId).bind('mediaBrowserSelect', Drupal.wysiwyg.plugins.media.mediaBrowserOnSelect).trigger('launchWYSIWYG');
     }
   },
 
@@ -35,13 +42,9 @@ Drupal.wysiwyg.plugins.media = {
    * Respond to the mediaBrowser's onSelect event.
    * @TODO: Debug calls from this are never called. What's its function?
    */
-  mediaBrowserOnSelect: function (mediaFiles, instanceId) {
-    var mediaFile = mediaFiles[0];
-    var options = {};
-    Drupal.media.popups.mediaStyleSelector(mediaFile, function (formattedMedia) {
-      Drupal.wysiwyg.plugins.media.insertMediaFile(mediaFile, formattedMedia.type, formattedMedia.html, formattedMedia.options, Drupal.wysiwyg.instances[instanceId]);
-    }, options);
-
+  mediaBrowserOnSelect: function (event, data) {
+    var mediaFile = data.files[0];
+    // Need to figure out some way of launching the format form    
     return;
   },
 
diff --git a/media.api.php b/media.api.php
index 0cf18a3..5a0dd5d 100644
--- a/media.api.php
+++ b/media.api.php
@@ -1,49 +1,6 @@
 <?php
 
 /**
- * Return an array of plugins for the media browser.
- *
- * Implementors are expected to return a renderable element.
- *
- * Each element will be a jQuery tab on the media browser.
- *
- * Some elements are special:
- *  - #title: The title that goes on the tab
- *  - #settings: Drupal.settings.media.browser.$key (where key is the array key).
- *  - #callback: If provided, will make the tab an "ajax" tab.
- *
- * Example:
- *   $plugins['library'] = array(
- *  '#title' => t('Library'),
- *  '#attached' => array(
- *    'js' => array(
- *       $path . '/js/plugins/media.library.js',
- *     ),
- *   ),
- *   '#settings' => array(
- *     'viewMode' => 'thumbnails',
- *     'getMediaUrl' => url('media/browser/list'),
- *   ),
- *   '#markup' => '<div> Library goes here</div>',
- * );
- *
- * @param $plugin_name
- *  The name of the plugin to view
- *
- * @param $params
- *  An array of parameters which came in is $_GET['params'].
- *  The expected parameters is still being defined.
- *   - types: Array of media types to support
- *   - multiselect: Boolean enabling or disabling multiselect
- *
- * @return
- *  Renderable array.
- */
-function hook_media_browser_plugin_view($plugin_name, $params) {
-
-}
-
-/**
  * Returns a list of plugins for the media browser.
  *
  * Plugins are defined in a multi-dimensional associative
@@ -51,11 +8,22 @@ function hook_media_browser_plugin_view($plugin_name, $params) {
  *
  * - #weight (optional): Weight of the plugin in relation to other plugins
  *  when being displayed, e.g. tabs in the browser.
+ * - #title  (required): The title of the tab to be displayed in the media browser
+ * - #form_id (required): The name of the form that will be used to select media
+ * 
+ * Within this function the implementor is responsible to call any required
+ * module_load_include calls so that the central browser processing callback
+ * can process the form correctly.
  *
  * @example
  * <code>
+ * 
+ * module_load_include('inc', 'my_module', 'my_include');
+ * 
  * array(
  *  'unique_plugin_name' => array(
+ *     '#title' => 'unique_plugin_tab_name',
+ *     '#form_id' => 'unique_plugin_form_id',
  *     '#weight' => 42,
  *   ),
  * );
diff --git a/media.module b/media.module
index f8fbc07..e4e4c0a 100644
--- a/media.module
+++ b/media.module
@@ -183,12 +183,13 @@ function media_menu() {
   $items['media/%media/format-form'] = array(
     'title' => 'Style selector',
     'description' => 'Choose a format for a piece of media',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('media_format_form', 1),
+    'page callback' => 'media_format',
+    'page arguments' => array(1),
     'access arguments' => array('administer media'),
     'weight' => 0,
     'file' => 'includes/media.filter.inc',
-    'theme callback' => 'media_dialog_get_theme_name',
+    'delivery callback' => 'ajax_deliver',
+    'theme callback' => 'media_dialog_theme',
   );
 
   $items['media/%media'] = array(
@@ -991,7 +992,7 @@ function media_element_process(&$element, &$form_state, $form) {
   //$fid = isset($element['#default_value']['fid']) ? $element['#default_value']['fid'] : 0;
   $media = media_load($fid);
   $path = drupal_get_path('module', 'media');
-
+  
   $element['title'] = array(
     '#type' => 'item',
     '#title' => $element['#title'],
@@ -1010,7 +1011,34 @@ function media_element_process(&$element, &$form_state, $form) {
     '#type' => 'item',
     '#markup' => $markup,
     '#prefix' => '<div class="preview launcher">',
-    '#suffix' => '</div><a class="button launcher" href="#">' . t(media_variable_get('field_select_media_text')) . '</a><a class="button remove" href="#">' . t(media_variable_get('field_remove_media_text')) . '</a>',
+    '#suffix' => '</div>',
+  );
+  
+  $element['links'] = array(
+    'launcher' => array(
+      '#type' => 'link',
+      '#href' => '',
+      '#title' => t(media_variable_get('field_select_media_text')),
+      '#attributes' => array(
+        'class' => array('button'),
+      ),
+      '#ajax' => array(
+        'path' => 'media/browser',
+        'submit' => array(
+          'trigger' => $element['#id'],
+          'limit' => 20,
+          'singleselect' => TRUE,
+        ),
+      ),
+    ),
+    'remove' => array(
+      '#type' => 'link',
+      '#title' => t(media_variable_get('field_remove_media_text')),
+      '#href' => '',
+      '#attributes' => array(
+        'class' => array('button remove'),
+      ),
+    ),
   );
 
   /**
@@ -1053,13 +1081,13 @@ function media_element_process(&$element, &$form_state, $form) {
   // Media browser attach code.
   $element['#attached']['js'][] = drupal_get_path('module', 'media') . '/js/media.js';
 
-  $settings = array();
-  $setting['media']['elements'][$element['#id']] = $element['#media_options'];
-
-  $element['#attached']['js'][] = array(
-    'type' => 'setting',
-    'data' => $setting,
-  );
+//  $settings = array();
+//  $setting['media']['elements'][$element['#id']] = $element['#media_options'];
+//
+//  $element['#attached']['js'][] = array(
+//    'type' => 'setting',
+//    'data' => $setting,
+//  );
 
   // hmm... Might need to think about this.
   // All settings would likely apply to all media in a multi-value, but what about passing the existing fid?
diff --git a/modules/media_internet/media_internet.module b/modules/media_internet/media_internet.module
index 8fe0590..2a869b3 100644
--- a/modules/media_internet/media_internet.module
+++ b/modules/media_internet/media_internet.module
@@ -10,11 +10,12 @@ function media_internet_media_browser_plugin_info() {
    'search' => array(
    ),
   */
+  
   if (user_access('administer media') || user_access('add media from remote sources')) {
     $plugins['media_internet'] = array(
       '#title' => t('Web'),
       '#form_id' => 'media_internet_add',
-      '#weight' => -10,
+      '#weight' => 0,
     );
   }
   return $plugins;
@@ -31,28 +32,6 @@ function media_internet_permission() {
     ),
   );
 }
-/**
- * Implements hook_media_browser_plugin_view().
- */
-function media_internet_media_browser_plugin_view($plugin_name, $params) {
-  $path = drupal_get_path('module', 'media');
-
-  $types = isset($params['types']) ? $params['types'] : array();
-  $multiselect = isset($params['multiselect']) ? $params['multiselect'] : FALSE;
-  
-  $redirect = array('media/browser', array('query' => array('render' => 'media-popup')));
-  switch ($plugin_name) {
-    case 'media_internet':
-      // @todo: implement the multiselect argument here.
-      return array(
-        '#title' => t('Web'),
-        '#form_id' => 'media_internet_add',
-      );
-      break;
-  }
-  
-  return array();
-}
  
 /**
  *  Provides a form for adding media items from 3rd party sources.
diff --git a/wysiwyg_plugins/media.inc b/wysiwyg_plugins/media.inc
index 908e315..e03be80 100644
--- a/wysiwyg_plugins/media.inc
+++ b/wysiwyg_plugins/media.inc
@@ -28,10 +28,9 @@ function media_media_plugin() {
     'css file' => NULL,
     'css path' => NULL,
     'settings' => array(
-      'global' => array(
-        'types' => media_variable_get('wysiwyg_allowed_types'),
-        'id' => 'media_wysiwyg',
-      ),
+      'types' => media_variable_get('wysiwyg_allowed_types'),
+      'singleselect' => TRUE,
+      'limit' => 10,
     ),
    );
 
-- 
1.7.4.msysgit.0

