From d6f1870b4cef6c160a8c4e76bc13e6068345db13 Mon Sep 17 00:00:00 2001
From: James Elliott <james.elliott@acquia.com>
Date: Fri, 22 Apr 2011 15:04:55 -0400
Subject: [PATCH 11/15] Woo, got the display switching working... AJAX style without selection loss

---
 css/media.thumbnails.css                     |    5 +-
 includes/media.admin.inc                     |    7 +-
 includes/media.browser.inc                   |  472 ++++++++++++--------------
 includes/media.pages.inc                     |   45 ++--
 js/media.admin.js                            |   30 +--
 js/media.dialog.js                           |   32 +-
 media.module                                 |   68 ++---
 modules/media_internet/media_internet.module |   16 +-
 8 files changed, 304 insertions(+), 371 deletions(-)

diff --git a/css/media.thumbnails.css b/css/media.thumbnails.css
index 36ed607..6bc0ad4 100644
--- a/css/media.thumbnails.css
+++ b/css/media.thumbnails.css
@@ -127,9 +127,10 @@ html.js .media-thumbnails-select {
 html.js .media-thumbnails-select ul {
   padding: 0;
   margin: 0 0 0 5px;
-  display: inline-block;
+  display: inline;
 }
 
 .media-thumbnails-select li {
-  display: inline-block;
+  padding: 0;
+  display: inline;
 }
\ No newline at end of file
diff --git a/includes/media.admin.inc b/includes/media.admin.inc
index 109ab61..13f1a79 100644
--- a/includes/media.admin.inc
+++ b/includes/media.admin.inc
@@ -50,9 +50,10 @@ function media_admin($form, $form_state) {
     '#value' => t('Submit'),
     '#submit' => array('media_admin_submit'),
     '#validate' => array('media_admin_validate'),
-    '#attributes' => array('class' => array('use-ajax-submit')),
   );
   
+  module_load_include('inc', 'media', '/includes/media.browser');
+  
   // Enable the add media button
   $settings = array(
     'media' => array(
@@ -71,9 +72,9 @@ function media_admin($form, $form_state) {
   );
   
   drupal_add_js($settings, 'setting');
-  
+
   $form['browser'] = media_browser_build();
-  
+
   return $form;
 }
 
diff --git a/includes/media.browser.inc b/includes/media.browser.inc
index e79c578..9a96333 100644
--- a/includes/media.browser.inc
+++ b/includes/media.browser.inc
@@ -4,55 +4,97 @@
  * @file
  * Media Browser page callback
  */
-function media_browser($form, &$form_state) {
-
-//  if ($messages = theme('status_messages')) {
-//    $form['ajax']['messages'] = array(
-//      '#markup' => $messages,
-//      '#weight' => -1,
-//    );
-//  }
+
+function media_form_media_browser_form_alter(&$form, &$form_state, $form_id) {
+  $form['actions'] = array(
+    $form_id . '-submit' => array(
+      '#type' => 'submit',
+      '#value' => t('Okay'),
+      '#ajax' => array(
+        'callback' => 'media_browser_select',
+        'path' => 'media/browser',
+      ),
+      '#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',
+      ),
+    ),
+  );
+}
+
+function media_browser_select($form, &$form_state) {
+  if (!form_get_errors() && isset($form_state['values']['fids'])) {
+    $command = array(
+      'command' => 'mediaBrowserSelected',
+      'files' => $form_state['values']['fids'],
+    );
+  } else {
+    $command = media_browser_refresh($form, $form_state);
+  }
+
+  return $command;
+}
+
+function media_browser_dismiss() {
+  $commands = array();
+  $commands[] = array(
+    'command' => 'mediaBrowserDismiss',
+  );
   
+  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(
+    'command' => 'insert',
+    'method' => 'replaceWith',
+    'data' => drupal_render($form),
+    'selector' => '#' . strtr($form_state['values']['form_id'], '_', '-'),
+  );
+}
+
+function media_browser_launch() {
+  return array(
+    'command' => 'mediaBrowserLaunch',
+    'data' => drupal_render(media_browser_forms()),
+  );
+}
+
+function media_browser() {
   $commands = array();
+  
+  if (!isset($_POST['form_id'])) {
+    $commands[] = media_browser_launch();
+  } else {
+    // This will load the necessary files for processing the form
+    $plugins = media_browser_get_plugins();
+    
+    list($form, $form_state) = ajax_get_form();
+    drupal_process_form($form['#form_id'], $form, $form_state);
 
-  if (isset($form_state['dismiss'])) {
-    $command = 'mediaBrowserDismiss';
-    $data = '';
-  }
-  else if (form_get_errors()) {
-    $command = 'mediaBrowserRefresh';
-    $data = drupal_render($form);
-  }
-  else if (isset($form_state['values']['fid'])) {
-    // The form has submitted, selected a piece (or pieces) of media and we refreshed.
-    // So we're just going to send the media entity out as a JS setting so the browser can close itself.
-    $selected = $form_state['values']['fid'];
-    if (!is_array($form_state['values']['fid'])) {
-      $selected = array($form_state['values']['fid']);
-    }
-    if (!is_numeric($selected[0])) {
-      throw new Exception('Error selecting media, fid param is not an fid or an array of fids');
+    if (!empty($form_state['triggering_element'])) {
+      $callback = $form_state['triggering_element']['#ajax']['callback'];
     }
-    $selectedMedia = entity_load('media', $selected);
-    foreach ($selectedMedia as &$media) {
-      media_browser_build_media_item($media);
+    if (!empty($callback) && function_exists($callback)) {
+      $commands[] = $callback($form, $form_state);
     }
-    $setting = array('media' => array('selectedMedia' => array_values($selectedMedia)));
-    #drupal_add_js($setting, 'setting');
-    
-    $command = 'mediaBrowserSelected';
-    $data = array_values($selectedMedia);
-  } 
-  else {
-    $command = 'mediaBrowserLaunch';
-    $data = drupal_render(media_browser_forms());
   }
-  
-  $commands[] = array(
-    'command' => $command,
-    'data' => $data,
-    'post' => $_POST,
-  );
 
   return array('#type' => 'ajax', '#commands' => $commands);
 }  
@@ -67,28 +109,8 @@ function media_browser_forms() {
   media_set_browser_params($params);
 
   // Normal browser operation.
-  foreach (module_implements('media_browser_plugin_info') as $module) {
-    foreach(module_invoke($module, 'media_browser_plugin_info') 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));
-  }
-  elseif (!empty($params['disabledPlugins'])) {
-    $plugins = array_diff_key($plugins, array_fill_keys($params['disabledPlugins'], 1));
-  }
+  $plugins = media_browser_get_plugins($params);
 
-  foreach ($plugins as $key => &$plugin) {
-    $plugin += module_invoke($plugin['#module'], 'media_browser_plugin_view', $key, $params);
-  }
-  
   // Allow modules to change the tab names or whatever else they want to change
   // before we render.  Perhaps this should be an alter on the theming function
   // that we should write to be making the tabs.
@@ -96,14 +118,11 @@ function media_browser_forms() {
   
   $tabs = array(); // List of tabs to render.
   
-  $browser_settings = array();
-
-  foreach (element_children($plugins, TRUE) as $key) {
-    $plugin = $plugins[$key];
-
-    //Add any JS settings
-    $browser_settings[$key] = isset($plugin['#settings']) ? $plugin['#settings'] : array();
-
+  $browser_settings = array('media' => array('dialog' => array()));
+  
+  $output = array();
+  
+  foreach ($plugins as $key => $plugin) {
     // If this is a "ajax" style tab, add the href, otherwise an id.
     $href = isset($plugin['#callback']) ? $plugin['#callback'] : "#media-tab-$key";
     $tabs[] = "<a href='$href'><span>{$plugin['#title']}</span></a>";
@@ -116,25 +135,16 @@ EOS;
     </div>
     <!-- End #media-tab-$key -->
 EOS;
-    
-    $plugin['form']['actions'] = array(
-      'submit' => array(
-        '#type' => 'submit',
-        '#value' => t('Okay'),
-        '#attributes' => array('class' => array('use-ajax-submit')),
+    $form_state = array(
+      'build_info' => array(
+        'base_form_id' => 'media_browser_form',
       ),
-      'cancel' => array(
-        '#type' => 'submit',
-        '#value' => t('Cancel'),
-        '#name' => 'cancel',
-        '#attributes' => array('class' => array('use-ajax-submit')),
-      )
     );
-    
+    $plugin['form'] = drupal_build_form($plugin['#form_id'], $form_state);
     $plugins[$key] = $plugin;
   }
   
-  drupal_add_js(array('media' => array('dialog' => $browser_settings)), 'setting');
+  drupal_add_js($browser_settings, 'setting');
   
   $build['tabset'] = array(
     '#prefix' => '<div id="media-browser-tabset">',
@@ -144,40 +154,34 @@ EOS;
   
   $build['tabset']['list'] = array(
     '#markup' => '<ul><li>' . implode('</li><li>', $tabs) . '</li></ul>'
-  );  
+  );
   
   $build['tabset']['plugins'] = $plugins;
 
   return $build;
 }
 
-function media_browser_form_validate($form, &$form_state) {
-  if (isset($form_state['clicked_button']) && $form_state['clicked_button']['#name'] == 'cancel') {
-    $form_state['dismiss'] = TRUE;
-  }
-  #module_load_include('inc', 'media', 'includes/media.pages');
-  $fs = form_state_defaults();
-  $fs['values'] = array(1,2);
-  drupal_form_submit('media_add_upload', $fs);
-  form_set_error('upload', 'This is a fake error');
-}
-
 function media_browser_build() {
-  $build = array();
+  $form = array();
   // Attach browser JS
-  media_attach_browser_js($build);
+  media_attach_browser_js($form);
 
   // Gather the display information.
   $display = media_browser_get_display();
   
-  // Build the display switch.
-  $build['switch'] = media_browser_display_switch(array('active display' => $display['name']));
+  $form['browser'] = array(
+    '#prefix' => '<div id="media-browser">',
+    '#suffix' => '</div>',
+  );
   
+  // Build the display switch.
+  $form['browser']['switch'] = media_browser_display_switch();
+
   // Build the display.
   include_once $display['file'];
-  $build['display'] = $display['callback']();
-
-  return $build;
+  $form['browser']['display'] = $display['callback']();
+  
+  return $form;
 }
 
 function media_browser_get_display() {
@@ -194,15 +198,65 @@ function media_browser_get_display() {
   return $display;
 }
 
-function media_browser_set_display($type) {
+function media_browser_set_display($type, $js = FALSE) {
   global $user;
-
-  if (in_array($type, array_keys(media_display_types()))) {
+  $types = media_display_types();
+  
+  
+  if (in_array($type, array_keys($types))) {
     $user->data['media_display_type'] = $type;
     user_save($user);
   }
+  
+  if ($js) {
+    list($form, $form_state) = ajax_get_form();
+    $form['browser'] = media_browser_build();
+    drupal_process_form($form['#form_id'], $form, $form_state);
+    
+    $commands = array();
+    
+    $container = array_slice(array_reverse($form_state['triggering_element']['#array_parents']), 2);
+    $element = $form;
+    foreach($container as $key) {
+      $element = $element[$key];
+    }
+    
+    $commands[] = array(
+      'command' => 'insert',
+      'selector' => '#media-browser',
+      'method' => 'replaceWith',
+      'data' => drupal_render($element),
+      'state' => $form_state,
+      'element' => $element,
+    );
+    
+    return array('#type' => 'ajax', '#commands' => $commands);
+  } else {
+    drupal_goto(drupal_get_destination());
+  }
+}
 
-  drupal_goto(drupal_get_destination());
+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) {
+      $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));
+  }
+  elseif (!empty($params['disabledPlugins'])) {
+    $plugins = array_diff_key($plugins, array_fill_keys($params['disabledPlugins'], 1));
+  }
+  return $plugins;
 }
 
 /**
@@ -240,6 +294,14 @@ function media_browser_table() {
   $files = array();
   $options = array();
 
+  $form['files'] = array(
+   '#type' => 'tableselect',
+   '#header' => $header,
+   '#options' => $options,
+   '#empty' => t('No media available.'),
+   '#attributes' => array('class' => array('media-display-table', 'media-clear')),
+  );
+  
   foreach ($result as $file) {
     $options[$file->fid] = array(
       'title' => theme('media_link', array('file' => $file)),
@@ -249,18 +311,19 @@ function media_browser_table() {
       'timestamp' => format_date($file->timestamp, 'short'),
     );
     $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(
+      '#type' => 'checkbox',
+      '#title_display' => 'invisible',
+      '#return_value' => $file->fid,
+    );
   }
-
-  $form['files'] = array(
-   '#type' => 'tableselect',
-   '#header' => $header,
-   '#options' => $options,
-   '#empty' => t('No media available.'),
-   '#attributes' => array('class' => array('media-display-table', 'media-clear')),
-  );
   
-  $form['pager'] = array('#markup' => theme('pager', array('tags' => NULL)));
+  $form['files']['#options'] = $options;
 
+  $form['pager'] = array('#markup' => theme('pager', array('tags' => NULL)));
+  
   return $form;
 }
 
@@ -342,45 +405,38 @@ function media_browser_thumbnails() {
 /**
  * Build the display switch portion of the file listings form.
  */
-function media_browser_display_switch($options = array()) {
-  $options += array(
-    'active display' => 'list',
-  );
+function media_browser_display_switch() {
+  global $user;
+  $type =  isset($user->data['media_display_type']) ?  $user->data['media_display_type'] : 'list';
   $display_types = media_display_types();
 
   // Build the item list.
-  $display_items = array();
-  foreach ($display_types as $delta => $item) {
-    $attributes = array('title' => $item['description']);
+  $links = array();
 
-    // Set a seperate icon for the active item.
-    if ($delta == $options['active display']) {
+  foreach ($display_types as $delta => $item) {
+    $attributes = array(
+      'title' => $item['description'],
+    );
+    $icon = $item['icon'];
+    if ($delta == $type) {
       $icon = $item['icon_active'];
       $attributes['class'][] = 'active';
     }
-    else {
-      $icon = $item['icon'];
-    }
-
-    $display_items[] = array(
-      'data' => l(theme('image', array('path' => $icon, 'alt' => $item['title'])),
-        'media/browser/' . $delta,
-        array(
-          'html' => TRUE,
-          'attributes' => $attributes,
-          'query' => drupal_get_destination(),
-        )),
+    
+    $links[$delta] = array(
+      '#type' => 'button',
+      '#title' => $delta,
+      '#value' => $delta,
+      '#href' => '/media/browser/nojs/' . $delta,
+      '#ajax' => array(
+        'path' => 'media/browser/ajax/' . $delta,
+      ),
+      '#limit_validation_errors' => array(),
+      '#executes_submission_callback' => FALSE,
     );
   }
-
-  return array(
-    '#type' => 'markup',
-    '#markup' => theme('item_list', array(
-       'items' => $display_items,
-       'attributes' => array('class' => 'media-display-switch'),
-      )
-    ),
-  );
+  
+  return $links;
 }
 
 /**
@@ -420,87 +476,33 @@ function media_get_browser_params() {
  */
 function media_media_browser_plugin_info() {
   $plugins = array();
-
+  module_load_include('inc', 'media', '/includes/media.pages');
+  
   // @TODO: Should we add a permission around this?
   $plugins['library'] = array(
+    '#title' => 'library',
+    '#form_id' => 'media_library_form',
     '#weight' => 10,
   );
 
   if (user_access('administer media') || user_access('edit media')) {
+    if (FALSE && module_exists('plupload')) {
+      $upload_form_id = 'media_add_upload_multiple';
+    }
+    else {
+      $upload_form_id = 'media_add_upload';
+    }
+
     $plugins['upload'] = array(
+      '#title' => t('Upload'),
+      '#form_id' => $upload_form_id,
       '#weight' => -10,
-     );
+    );
   }
   return $plugins;
 }
 
 /**
- * Implementaion of hook_media_browser_plugin_view().
- */
-function media_media_browser_plugin_view($plugin_name, $params) {
-  $path = drupal_get_path('module', 'media');
-
-  module_load_include('inc', 'media', 'includes/media.admin');
-  module_load_include('inc', 'media', 'includes/media.pages');
-
-  $types = isset($params['types']) ? $params['types'] : array();
-
-  // The multiselect parameter is a string.  So we check to see if it is set and
-  // adjust the local variable accordingly.
-  $multiselect = FALSE;
-  if (isset($params['multiselect']) && $params['multiselect'] != 'false') {
-    $multiselect = TRUE;
-  }
-
-  $redirect = array('media/browser', array('query' => array('render' => 'media-popup')));
-  switch ($plugin_name) {
-    case 'upload':
-      $attached = array();
-      if ($multiselect && module_exists('plupload')) {
-        $upload_form_id = 'media_add_upload_multiple';
-        $attached['js'] = array($path . '/js/plugins/media.upload_multiple.js');
-      }
-      else {
-        $upload_form_id = 'media_add_upload';
-      }
-
-      $upload_form = drupal_get_form($upload_form_id);
-      
-      return array(
-        '#title' => t('Upload'),
-        'form' => $upload_form,
-        '#attached' => $attached,
-      );
-      break;
-    case 'library':
-      return array(
-        '#title' => t('Library'),
-        '#attached' => array(
-          'js' => array(
-            $path . '/js/plugins/media.library.js',
-          ),
-          'css' => array(
-            //@todo: should move this.
-            $path . '/js/plugins/media.library.css',
-          ),
-        ),
-        '#settings' => array(
-          'viewMode' => 'thumbnails',
-          'getMediaUrl' => url('media/browser/list'),
-          'types' => $types,
-          'multiselect' => $multiselect,
-        // We should probably change this to load dynamically when requested
-        // via the JS file.
-        ),
-        'form' => drupal_get_form('media_library'),
-      );
-    break;
-  }
-
-  return array();
- }
-
-/**
  * Silly function to recursively run check_plain on an array.
  *
  * There is probably something in core I am not aware of that does this.
@@ -646,41 +648,3 @@ function media_browser_build_media_item(&$media) {
   $media->preview = drupal_render($preview);
   $media->url = file_create_url($media->uri);
 }
-
-/**
- * Creates a Drupal AJAX 'mediaBrowserLaunch' command.
- *
- * @param $output
- *   The form to display in the modal.
- * @param $title
- *   The title.
- * @param $url
- *   An optional URL.
- *
- * @return
- *   An array suitable for use with the ajax_render() function.
- */
-function media_browser_ajax_command_set_form($output, $title, $url = NULL) {
-  $command = array(
-    'command' => 'mediaBrowserLaunch',
-    'output' => $output,
-    'title' => $title,
-  );
-  if (isset($url)) {
-    $command['url'] = $url;
-  }
-  return $command;
-}
-
-/**
- * Creates a Drupal AJAX 'mediaBrowserDismiss' command.
- *
- * @return
- *   An array suitable for use with the ajax_render() function.
- */
-function media_browser_ajax_command_dismiss_form() {
-  $command = array(
-    'command' => 'mediaBrowserDismiss',
-  );
-  return $command;
-}
diff --git a/includes/media.pages.inc b/includes/media.pages.inc
index 5647680..1f2376e 100644
--- a/includes/media.pages.inc
+++ b/includes/media.pages.inc
@@ -176,7 +176,6 @@ function media_multiple_delete_confirm_submit($form, &$form_state) {
  * @todo: should use the AJAX uploader
  */
 function media_add_upload($form, &$form_state, $types = NULL) {
-  module_load_include('inc', 'media', '/includes/media.pages');
   $validators = array(
    'file_validate_extensions' => array(media_variable_get('file_extensions')),
    'file_validate_size' => array(parse_size(media_variable_get('max_filesize'))),
@@ -226,38 +225,32 @@ function media_add_upload_validate($form, &$form_state) {
     form_set_error('upload', t("Failed to upload the file."));
   }
   else {
-    $form_state['values']['upload'] = $file;
-  }
-}
-
-/**
- * Upload a file.
- */
-function media_add_upload_submit($form, &$form_state) {
-  $scheme = variable_get('file_default_scheme', 'public') . '://';
-  $file = $form_state['values']['upload'];
-  _media_save_file_permenently($file);
+    $scheme = variable_get('file_default_scheme', 'public') . '://';
+    _media_save_file_permenently($file);
 
-  $destination = file_stream_wrapper_uri_normalize($scheme . $file->filename);
+    $destination = file_stream_wrapper_uri_normalize($scheme . $file->filename);
 
-  $defaults = array (
-    'display' => TRUE,
-  );
+    $defaults = array (
+      'display' => TRUE,
+    );
 
-  // Save the uploaded file.
-  $file = file_move($file, $destination, FILE_EXISTS_RENAME);
+    // Save the uploaded file.
+    $file_permanent = file_move($file, $destination, FILE_EXISTS_RENAME);
 
-  if ($file) {
-    drupal_set_message(t('The file @name was uploaded', array('@name' => $file->filename)));
-  }
-  else {
-    drupal_set_message(t('An error occurred and no file was uploaded.'), 'error');
-    return;
+    if ($file_permanent) {
+      drupal_set_message(t('The file @name was uploaded', array('@name' => $file->filename)));
+      $form_state['values']['fids'] = array($file->fid);
+    }
+    else {
+      form_set_error('upload', t('An error occurred and no file was uploaded.'));
+    }
   }
 }
 
 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');
+  
   unset($form['upload']['#title']);
   // The validators will be set from plupload anyway.  This isn't pretty, but don't
   // it to show up twice.
@@ -423,3 +416,7 @@ function media_add_remote($form, &$form_state) {
   return $form;
 }
 
+function media_library_form($form, &$form_state) {
+  $form['browser'] = media_browser_build();
+  return $form;
+}
diff --git a/js/media.admin.js b/js/media.admin.js
index 41a8e97..eed581c 100644
--- a/js/media.admin.js
+++ b/js/media.admin.js
@@ -17,42 +17,18 @@ Drupal.media.admin = Drupal.media.admin || {};
  */
 Drupal.behaviors.mediaAdmin = {
   attach: function (context) {
-    var show_confirm_if_existing_selections = function () {
-      if ($(':checkbox:checked', $('form#media-admin')).length != 0) {
-        return confirm(Drupal.t('If you switch views, you will lose your selection.'));
-      }
-    }
-    $('.media-display-switch a', context).bind('click', show_confirm_if_existing_selections)
-
     // When any checkboxes are clicked on this form check to see if any are checked.
     // If any checkboxes are checked, show the edit options (@todo rename to edit-actions).
     $('#media-admin :checkbox', context).once('media-admin', function() {
       $(this).bind('change', Drupal.media.admin.showOrHideEditOptions).trigger('change');
     });
     
+    // When the media browser closes successfully, refresh the page
+    // @todo: Turn this into an AJAX refresh of the current display
+    $(window).bind('mediaBrowserSelect', function() {location.reload();});
   }
 };
 
-Drupal.media.admin.addMedia = function (event) {
-  event.preventDefault();
-  Drupal.media.dialog.launch();
-  return;
-  // This option format needs *serious* work.
-  // Not even bothering documenting it because it needs to be thrown.
-  // See media.browser.js and media.browser.inc - media_browser()
-  // For how it gets passed.
-  var options = {
-    disabledPlugins: ['library'],
-    multiselect: true
-  };
-  Drupal.media.popups.mediaBrowser(function (mediaFiles) {
-    // When the media browser succeeds, we refresh
-    // @TODO: Should jump to the new media file and perhaps highlight it.
-    parent.window.location.reload();
-    return false;
-  }, options);
-};
-
 Drupal.media.admin.showOrHideEditOptions = function(event) {
   event.stopPropagation();
   var fieldset = $('#edit-options');
diff --git a/js/media.dialog.js b/js/media.dialog.js
index c0779aa..7f8b5ff 100644
--- a/js/media.dialog.js
+++ b/js/media.dialog.js
@@ -51,19 +51,13 @@ Drupal.media.dialog.close = function () {
   $(this).remove();
 };
 
-Drupal.media.dialog.tabs = function (wrapper) {
-  var tab = $('.media-browser-active-tab', wrapper).val();
+Drupal.media.dialog.tabs = function (wrapper, tab) {
   $('#media-browser-tabset', wrapper).tabs({
     show: Drupal.media.dialog.tabSwitch,
     selected: tab
   });
 };
 
-Drupal.media.dialog.tabSwitch = function (event, ui) {
-  var value = $(this).tabs( "option", "selected" );
-  $('.media-browser-active-tab').val(value);
-};
-
 Drupal.ajax.prototype.commands.mediaBrowserLaunch = function (ajax, response, status) {
   // Create the dialog
   var wrapper = $('<div id="media-browser-wrapper"></div>');
@@ -80,16 +74,24 @@ Drupal.ajax.prototype.commands.mediaBrowserLaunch = function (ajax, response, st
   wrapper.dialog('open');
 };
 
-Drupal.ajax.prototype.commands.mediaBrowserRefresh = function (ajax, response, status) {
-  var wrapper = $('#media-browser-wrapper');
-  $('#media-browser-ajax-wrapper', wrapper).replaceWith(response.data);
-  Drupal.media.dialog.tabs($('#media-browser-wrapper'));
-  Drupal.attachBehaviors($('.media-browser-tabset', wrapper), ajax.settings);
+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);
 };
 
-Drupal.ajax.prototype.commands.mediaBrowserSelected = function (ajax, response, status) {
-  console.log(response);
-  //$('#media-browser-wrapper').dialog('close');
+Drupal.ajax.prototype.commands.mediaBrowserMessages = function (ajax, response, status) {
+  var $messages = $('#media-browser-wrapper .messages');
+  if ($messages.length) {
+    $messages.replaceWith(response.data);
+  } else {
+    $('#media-browser-wrapper').prepend(response.data);
+  }
 };
 
 Drupal.ajax.prototype.commands.mediaBrowserDismiss = function (ajax, response, status) {
diff --git a/media.module b/media.module
index aa0d854..f8fbc07 100644
--- a/media.module
+++ b/media.module
@@ -129,7 +129,7 @@ function media_menu() {
     'description' => 'Import files into your media library.',
     'page callback' => 'drupal_get_form',
     'page arguments' => array('media_add_upload'),
-    'file' => 'includes/media.browser.inc',
+    'file' => 'includes/media.pages.inc',
     'access arguments' => array('import media'),
     'type' => MENU_LOCAL_ACTION,
     'options' => array(
@@ -149,51 +149,36 @@ function media_menu() {
     'theme callback' => 'media_dialog_theme',
   );
   
-  $items['media/browser/%'] = array(
+  $items['media/browser/cancel'] = array(
+    'title' => 'Close the media browser',
+    'page callback' => 'media_browser_dismiss',
+    'delivery callback' => 'ajax_deliver',
+    'access callback' => TRUE,
+    'theme callback' => 'media_dialog_theme',
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/media.browser.inc',
+  );
+  
+  $items['media/browser/nojs/%'] = array(
     'title' => 'Media browser display type',
     'page callback' => 'media_browser_set_display',
-    'page arguments' => array(2),
+    'page arguments' => array(3, FALSE),
     'access callback' => 'media_access',
     'access arguments' => array('view'),
     'type' => MENU_CALLBACK,
     'file' => 'includes/media.browser.inc',
   );
-
-//  // A testbed to try out the media browser with different launch commands.
-//  $items['media/browser/testbed'] = array(
-//    'title' => 'Media Browser test',
-//    'description' => 'Make it easier to test media browser',
-//    'page callback' => 'drupal_get_form',
-//    'page arguments' => array('media_browser_testbed'),
-//    'file' => 'includes/media.browser.inc',
-//    'access arguments' => array('administer media'),
-//    'type' => MENU_CALLBACK,
-//  );
-//
-//
-//  /**
-//   * Browser callbacks
-//   * @var unknown_type
-//   */
-//  $items['media/browser/list'] = array(
-//    'title' => 'Media browser list',
-//    'description' => 'Ajax Callback for getting media',
-//    'page callback' => 'media_browser_list',
-//    'access callback' => 'media_access',
-//    'access arguments' => array('view'),
-//    'type' => MENU_CALLBACK,
-//    'file' => 'includes/media.browser.inc',
-//  );
-//
-//  $items['media/browser/library'] = array(
-//    'title' => 'Media browser library',
-//    'description' => 'Media Browser for picking media and uploading new media',
-//    'page callback' => 'media_browser_library',
-//    'access callback' => 'media_access',
-//    'access arguments' => array('view'),
-//    'type' => MENU_CALLBACK,
-//    'file' => 'includes/media.browser.inc',
-//  );
+  
+  $items['media/browser/ajax/%'] = array(
+    'title' => 'Media browser display type',
+    'page callback' => 'media_browser_set_display',
+    'page arguments' => array(3, TRUE),
+    'access callback' => 'media_access',
+    'access arguments' => array('view'),
+    'type' => MENU_CALLBACK,
+    'file' => 'includes/media.browser.inc',
+    'delivery callback' => 'ajax_deliver',
+  );
 
   $items['media/%media/format-form'] = array(
     'title' => 'Style selector',
@@ -363,6 +348,11 @@ function media_theme() {
       'variables' => array('file' => NULL),
       'file' => 'includes/media.theme.inc',
     ),
+      
+    'media_browser_display_switch' => array(
+      'render element' => 'element',
+      'file' => 'includes/media.theme.inc',
+    ),
   );
 }
 
diff --git a/modules/media_internet/media_internet.module b/modules/media_internet/media_internet.module
index a260a9d..8fe0590 100644
--- a/modules/media_internet/media_internet.module
+++ b/modules/media_internet/media_internet.module
@@ -12,6 +12,8 @@ function media_internet_media_browser_plugin_info() {
   */
   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,
     );
   }
@@ -44,7 +46,7 @@ function media_internet_media_browser_plugin_view($plugin_name, $params) {
       // @todo: implement the multiselect argument here.
       return array(
         '#title' => t('Web'),
-        'form' => drupal_get_form('media_internet_add'),
+        '#form_id' => 'media_internet_add',
       );
       break;
   }
@@ -121,10 +123,10 @@ function media_internet_add_validate($form, &$form_state) {
     $provider = media_internet_get_provider($embed_code);
     $provider->validate();  
   } catch (MediaInternetNoHandlerException $e) {
-    form_set_error('url', $e->getMessage());
+    form_set_error('embed_code', $e->getMessage());
     return;
   } catch (MediaInternetValidationException $e) {
-    form_set_error('url', $e->getMessage());
+    form_set_error('embed_code', $e->getMessage());
     return;
   }
   
@@ -134,7 +136,7 @@ function media_internet_add_validate($form, &$form_state) {
     try {
       $file = $provider->getFileObject();
     } catch (Exception $e) {
-      form_set_error('url', $e->getMessage());
+      form_set_error('embed_code', $e->getMessage());
       return;
     }
     
@@ -151,7 +153,7 @@ function media_internet_add_validate($form, &$form_state) {
       else {
         $message .= ' ' . array_pop($errors);
       }
-      form_set_error('url', $message);
+      form_set_error('embed_code', $message);
       return FALSE;
     }
   }
@@ -184,12 +186,12 @@ function media_internet_add_submit($form, &$form_state) {
     $file = $provider->save();
   }
   catch (Exception $e) {
-    form_set_error('url', $e->getMessage());
+    form_set_error('embed_code', $e->getMessage());
     return;
   }
 
   if (!$file->fid) {
-    form_set_error('url', 'Unknown error: unable to add file, please check URL / Embed code and try again ' . $embed_code);
+    form_set_error('embed_code', 'Unknown error: unable to add file, please check URL / Embed code and try again ' . $embed_code);
     return;
   }
 
-- 
1.7.4.msysgit.0

