Index: /extensions/UserCollections/include/UserCollection.class.php
===================================================================
--- /extensions/UserCollections/include/UserCollection.class.php	(revision 23360)
+++ /extensions/UserCollections/include/UserCollection.class.php	(revision 23361)
@@ -26,6 +26,6 @@
       'date_creation' => '0000-00-00 00:00:00',
       'nb_images' => 0,
-      'active' => false,
-      'public' => false,
+      'active' => 0,
+      'public' => 0,
       'public_id' => null,
       );
@@ -56,13 +56,5 @@
     {
       $query = '
-SELECT
-    id,
-    user_id,
-    name,
-    date_creation,
-    nb_images,
-    active,
-    public,
-    public_id
+SELECT *
   FROM '.COLLECTIONS_TABLE.'
   WHERE
@@ -107,6 +99,6 @@
     {
       $this->data['name'] = $name;
-      $this->data['active'] = $active;
-      $this->data['public'] = $public;
+      $this->data['active'] = (int)$active;
+      $this->data['public'] = (int)$public;
       $this->data['public_id'] = 'uc'.hash('crc32', uniqid(serialize($this->data), true));
       
@@ -139,17 +131,4 @@
         $this->addImages($images);
       }
-      
-      // only one active collection allowed
-      if ($this->data['active'])
-      {
-        $query = '
-UPDATE '.COLLECTIONS_TABLE.'
-  SET active = 0
-  WHERE
-    user_id = '.$this->data['user_id'].'
-    AND id != '.$this->data['id'].'
-;';
-        pwg_query($query);
-      }
     }
     else
@@ -210,8 +189,5 @@
     if (empty($image_ids) or !is_array($image_ids)) return;
     
-    foreach ($image_ids as $image_id)
-    {
-      unset($this->images[ array_search($image_id, $this->images) ]);
-    }
+    $this->images = array_diff($this->images, $image_ids);
     
     $query = '
@@ -241,6 +217,9 @@
       if ($this->isInSet($image_id)) continue;
       
-      array_push($this->images, $image_id);
-      array_push($inserts, array('col_id'=>$this->data['id'], 'image_id'=>$image_id));
+      $this->images[] = $image_id;
+      $inserts[] = array(
+        'col_id' => $this->data['id'],
+        'image_id' => $image_id,
+        );
     }
     
@@ -302,4 +281,5 @@
   {
     $set = array(
+      'ID' => $this->data['id'],
       'NAME' => $this->data['name'],
       'NB_IMAGES' => $this->data['nb_images'],
@@ -308,5 +288,4 @@
       'DATE_CREATION' => $this->data['date_creation'],
       'U_PUBLIC' => USER_COLLEC_PUBLIC . 'view/'.$this->data['public_id'],
-      'IS_TEMP' =>  $this->data['name'] == 'temp',
       );
     
@@ -568,4 +547,13 @@
     return $content;
   }
+  
+  /**
+   * delete
+   */
+  function delete()
+  {
+    $this->clearImages();
+    pwg_query('DELETE FROM '.COLLECTIONS_TABLE.' WHERE id = '.$this->data['id'].';');
+  }
 }
 
Index: /extensions/UserCollections/include/collections.inc.php
===================================================================
--- /extensions/UserCollections/include/collections.inc.php	(revision 23360)
+++ /extensions/UserCollections/include/collections.inc.php	(revision 23361)
@@ -19,5 +19,5 @@
     if (is_a_guest()) access_denied();
     
-    $template->set_filename('index', dirname(__FILE__) . '/../template/list.tpl');
+    $template->set_filename('index', realpath(USER_COLLEC_PATH.'template/list.tpl'));
     
     // actions
@@ -29,15 +29,22 @@
         case 'new':
         {
-          $UserCollection = new UserCollection('new', array(), empty($_GET['name']) ? 'temp' : $_GET['name'], 1);
-          
-          if (isset($_GET['redirect']))
-          {
-            $redirect = USER_COLLEC_PUBLIC.'edit/'.$UserCollection->getParam('id');
+          if (empty($_GET['name']))
+          {
+            array_push($page['errors'], l10n('Please give a name'));
           }
           else
           {
-            $redirect = USER_COLLEC_PUBLIC;
-          }
-          redirect($redirect);
+            $UserCollection = new UserCollection('new', array(), $_GET['name'], 1);
+            
+            if (isset($_GET['redirect']))
+            {
+              $redirect = USER_COLLEC_PUBLIC.'edit/'.$UserCollection->getParam('id');
+            }
+            else
+            {
+              $redirect = USER_COLLEC_PUBLIC;
+            }
+            redirect($redirect);
+          }
           break;
         }
@@ -46,40 +53,12 @@
         case 'delete':
         {
-          $query = '
-DELETE ci, c
-  FROM '.COLLECTION_IMAGES_TABLE.' AS ci
-    RIGHT JOIN '.COLLECTIONS_TABLE.' AS c 
-    ON ci.col_id = c.id
-  WHERE
-    c.user_id = '.$user['id'].'
-    AND c.id = '.$_GET['col_id'].'
-;';
-          pwg_query($query);
-      
-          redirect(USER_COLLEC_PUBLIC);
-          break;
-        }
-        
-        // save
-        case 'save':
-        {
-          if (empty($_GET['name']))
-          {
-            array_push($page['errors'], l10n('Please give a name'));
-          }
-          else
-          {
-            $query = '
-UPDATE '.COLLECTIONS_TABLE.'
-  SET
-    name = "'.pwg_db_real_escape_string($_GET['name']).'",
-    active = 0
-  WHERE
-    user_id = '.$user['id'].'
-    AND id = '.$_GET['col_id'].'
-;';
-            pwg_query($query);
-            
+          try {
+            $UserCollection = new UserCollection($_GET['col_id']);
+            $UserCollection->delete();
             redirect(USER_COLLEC_PUBLIC);
+          }
+          catch (Exception $e)
+          {
+            $page['errors'][] = $e->getMessage();
           }
           break;
@@ -87,16 +66,9 @@
         
         // set active
-        case 'set_active':
+        case 'toggle_active':
         {
           $query = '
 UPDATE '.COLLECTIONS_TABLE.'
-  SET active = 0
-  WHERE user_id = '.$user['id'].'
-;';
-          pwg_query($query);
-          
-          $query = '
-UPDATE '.COLLECTIONS_TABLE.'
-  SET active = 1
+  SET active = IF(active=1, 0, 1)
   WHERE
     user_id = '.$user['id'].'
@@ -111,40 +83,10 @@
     }
     
-    
-    // get collections
-    $query = '
-SELECT * 
-  FROM '.COLLECTIONS_TABLE.'
-  WHERE user_id = '.$user['id'].'
-  ORDER BY date_creation DESC
-';
-    $collections = hash_from_query($query, 'id');
-    
-    foreach ($collections as $col)
-    {
-      $col['date_creation'] = format_date($col['date_creation'], true);
-      $col['U_EDIT'] = USER_COLLEC_PUBLIC.'edit/'.$col['id'];
-      $col['U_ACTIVE'] = add_url_params(USER_COLLEC_PUBLIC, array('action'=>'set_active','col_id'=>$col['id']));
-      $col['U_DELETE'] = add_url_params(USER_COLLEC_PUBLIC, array('action'=>'delete','col_id'=>$col['id']));
-      
-      if (isset($pwg_loaded_plugins['BatchDownloader']))
-      {
-        $col['U_DOWNLOAD'] = add_url_params(USER_COLLEC_PUBLIC.'edit/'.$col['id'], array('action'=>'advdown_set'));
-      }
-      
-      // temporary collections are above save collections
-      if ($col['name'] == 'temp')
-      {
-        $col['name'] = 'temp #'.$col['id'];
-        $col['U_SAVE'] = add_url_params(USER_COLLEC_PUBLIC, array('action'=>'save','col_id'=>$col['id']));
-        $template->append('temp_col', $col);
-      }
-      else
-      {
-        $template->append('collections', $col);
-      }
-    }
-    
     $template->assign('U_CREATE', add_url_params(USER_COLLEC_PUBLIC, array('action'=>'new','col_id'=>'0')));
+    
+    $template->set_prefilter('index_category_thumbnails', 'user_collections_categories_list');
+    
+    include(USER_COLLEC_PATH . '/include/display_collections.inc.php');
+    
     break;
   }
@@ -160,5 +102,5 @@
     }
     
-    $template->set_filename('index', dirname(__FILE__).'/../template/edit.tpl');
+    $template->set_filename('index', realpath(USER_COLLEC_PATH.'template/edit.tpl'));
     
     $self_url = USER_COLLEC_PUBLIC . 'edit/'.$page['col_id'];
@@ -169,5 +111,4 @@
       'collection_toggle_url' => $self_url,
       'U_LIST' => USER_COLLEC_PUBLIC,
-      'AJAX_COL_ID' => $page['col_id'],
       'UC_IN_EDIT' => true,
       ));
@@ -175,10 +116,4 @@
     try {
       $UserCollection = new UserCollection($page['col_id']);
-      
-      // security
-      if ( !is_admin() and $UserCollection->getParam('user_id') != $user['id'] )
-      {
-        access_denied();
-      }
       
       // save properties
@@ -244,13 +179,9 @@
       }
       
-      // remove an element
-      if ( isset($_GET['collection_toggle']) and preg_match('#^[0-9]+$#', $_GET['collection_toggle']) )
-      {
-        $UserCollection->removeImages(array($_GET['collection_toggle']));
-        unset($_GET['collection_toggle']);
-      }
       
       // add remove item links
-      $template->set_prefilter('index_thumbnails', 'user_collections_thumbnails_list_prefilter');
+      $template->set_prefilter('index_thumbnails', 'user_collections_thumbnails_list_button');
+      $template->set_prefilter('index', 'user_collections_thumbnails_list_cssjs');
+      $template->set_prefilter('index_thumbnails', 'user_collections_add_colorbox');
       
       // thumbnails
@@ -273,5 +204,5 @@
         add_url_params(USER_COLLEC_PUBLIC, array('action'=>'delete','col_id'=>$page['col_id']))
         );
-      if ($conf['user_collections']['allow_public'] and $conf['user_collections']['allow_mails'])
+      if ($conf['user_collections']['allow_public'] and $conf['user_collections']['allow_mails'] and !empty($page['items']))
       {
         $template->assign('U_MAIL', true);
@@ -308,4 +239,6 @@
       $UserCollection = new UserCollection($page['col_id']);
       $page['col_id'] = $UserCollection->getParam('id');
+      
+      $template->set_prefilter('index_thumbnails', 'user_collections_add_colorbox');
       
       // thumbnails
@@ -328,34 +261,22 @@
 }
 
-
-function user_collections_thumbnails_in_collection($tpl_thumbnails_var, $pictures)
+// modification on mainpage_categories.tpl
+function user_collections_categories_list($content, &$samrty)
 {
-  global $template, $page;
-  
-  $url = USER_COLLEC_PUBLIC . 'edit/'.$page['col_id'];
-  
-  foreach ($tpl_thumbnails_var as &$thumbnail)
-  {
-    $src_image = new SrcImage($thumbnail);
-    
-    $thumbnail['FILE_SRC'] = DerivativeImage::url(IMG_LARGE, $src_image);
-    $thumbnail['URL'] = duplicate_picture_url(
-        array(
-          'image_id' => $thumbnail['id'],
-          'image_file' => $thumbnail['file'],
-          'section' => 'none',
-        ),
-        array('start')
-      );
-      
-    $thumbnail['COLLECTION_SELECTED'] = true;
-    $thumbnail['COLLECTION_TOGGLE_URL'] = add_url_params($url, array('collection_toggle'=>$thumbnail['id']));
-  }
-  
-  $template->set_prefilter('index_thumbnails', 'user_collections_add_colorbox');
-  
-  return $tpl_thumbnails_var;
+  $search[0] = '<div class="thumbnailCategory">';
+  $replace[0] = '<div class="thumbnailCategory {*if $cat.active}activeCollection{/if*}">
+  <div class="collectionActions">
+    <a href="{$cat.URL}" rel="nofollow">{"Edit"|@translate}</a>
+    | <a href="{$cat.U_DELETE}" onClick="return confirm(\'{"Are you sure?"|@translate}\');" rel="nofollow">{"Delete"|@translate}</a>
+    {if $cat.U_ACTIVE}| <a href="{$cat.U_ACTIVE}" rel="nofollow">{if $cat.active}{"set inactive"|@translate}{else}{"set active"|@translate}{/if}</a>{/if}
+  </div>';
+  
+  // $search[1] = '<a href="{$cat.URL}">{$cat.NAME}</a>';
+  // $replace[1] = '<a href="{$cat.URL}">{$cat.NAME}</a> {if $cat.active}<span class="collectionActive">({"active"|@translate})</span>{/if}';
+  
+  return str_replace($search, $replace, $content);
 }
 
+// colorbox
 function user_collections_add_colorbox($content)
 {
Index: /extensions/UserCollections/include/display_collections.inc.php
===================================================================
--- /extensions/UserCollections/include/display_collections.inc.php	(revision 23361)
+++ /extensions/UserCollections/include/display_collections.inc.php	(revision 23361)
@@ -0,0 +1,120 @@
+<?php
+defined('USER_COLLEC_PATH') or die('Hacking attempt!');
+
+
+// collections orders
+if (isset($_GET['uc_collection_order']))
+{
+  if ( (int)$_GET['uc_collection_order'] > 0)
+  {
+    pwg_set_session_var('uc_collection_order', (int)$_GET['uc_collection_order']);
+  }
+  else
+  {
+    pwg_unset_session_var('uc_collection_order');
+  }
+  redirect(USER_COLLEC_PUBLIC);
+}
+
+$col_order_id = pwg_get_session_var('uc_collection_order', 0);
+$orders = get_collections_preferred_orders();
+
+// get sorted collections
+$query = '
+SELECT * 
+  FROM '.COLLECTIONS_TABLE.'
+  WHERE user_id = '.$user['id'].'
+  ORDER BY '.$orders[$col_order_id][1].'
+';
+$categories = hash_from_query($query, 'id');
+
+$template->assign('COLLECTIONS_COUNT', count($categories));
+
+// order menu
+if (count($categories))
+{
+  $url = add_url_params(USER_COLLEC_PUBLIC, array('uc_collection_order' => ''));
+  
+  foreach ($orders as $order_id => $order)
+  {
+    if ($order[2])
+    {
+      $template->append(
+        'image_orders',
+        array(
+          'DISPLAY' => $order[0],
+          'URL' => $url.$order_id,
+          'SELECTED' => ($col_order_id == $order_id ? true:false),
+          )
+        );
+    }
+  }
+}
+
+
+if (count($categories))
+{
+  $query = '
+SELECT * FROM (
+  SELECT
+      i.*,
+      ci.col_id
+    FROM '.IMAGES_TABLE.' AS i
+    INNER JOIN '.COLLECTION_IMAGES_TABLE.' AS ci
+      ON i.id = ci.image_id
+    WHERE col_id IN('.implode(',', array_keys($categories)).')
+    ORDER BY ci.add_date DESC
+  ) AS t
+  GROUP BY col_id
+;';
+  $thumbnails = hash_from_query($query, 'col_id');
+  
+  $thumbnails[0] = array(
+    'id' => 0,
+    'path' => 'themes/default/icon/img_small.png',
+    'picture_ext' => 'png',
+    'width' => 32,
+    'height' => 32,
+    'rotation' => 0,
+    );
+  
+  foreach ($thumbnails as &$info)
+  {
+    $info['src_image'] = new SrcImage($info);
+  }
+  unset($info);
+  
+  $tpl_thumbnails_var = array();
+
+  foreach ($categories as $category)
+  {
+    $thumb = empty($thumbnails[ $category['id'] ]) ? $thumbnails[0] : $thumbnails[ $category['id'] ];
+    $counter = get_display_images_count($category['nb_images'], $category['nb_images'], 0);
+    
+    $tpl_var = array_merge( $category, array(
+      'representative'   => $thumb,
+      'TN_ALT'   => strip_tags($category['name']),
+      'URL'   => USER_COLLEC_PUBLIC.'edit/'.$category['id'],
+      'CAPTION_NB_IMAGES' => empty($counter) ? sprintf(l10n('%d photo'), 0) : $counter,
+      'NAME'  => $category['name'],
+      'INFO_DATES' => format_date($category['date_creation'], true),
+      
+      // 'U_ACTIVE' => add_url_params(USER_COLLEC_PUBLIC, array('action'=>'toggle_active','col_id'=>$category['id'])),
+      'U_DELETE' => add_url_params(USER_COLLEC_PUBLIC, array('action'=>'delete','col_id'=>$category['id'])),
+      ));
+
+    $tpl_thumbnails_var[] = $tpl_var;
+  }
+  
+  $derivative_params = trigger_event('get_index_album_derivative_params', ImageStdParams::get_by_type(IMG_THUMB) );
+  $template->assign(array(
+    'maxRequests' =>$conf['max_requests'],
+    'category_thumbnails' => $tpl_thumbnails_var,
+    'derivative_params' => $derivative_params,
+    ));
+  
+  $template->set_filename('index_category_thumbnails', 'mainpage_categories.tpl');
+  $template->assign_var_from_handle('CATEGORIES', 'index_category_thumbnails');
+}
+
+?>
Index: /extensions/UserCollections/include/display_thumbnails.inc.php
===================================================================
--- /extensions/UserCollections/include/display_thumbnails.inc.php	(revision 23360)
+++ /extensions/UserCollections/include/display_thumbnails.inc.php	(revision 23361)
@@ -113,4 +113,32 @@
     );
 }
+
+
+function user_collections_thumbnails_in_collection($tpl_thumbnails_var, $pictures)
+{
+  global $template, $page;
+  
+  $url = USER_COLLEC_PUBLIC . 'edit/'.$page['col_id'];
+  
+  foreach ($tpl_thumbnails_var as &$thumbnail)
+  {
+    $src_image = new SrcImage($thumbnail);
+    
+    $thumbnail['FILE_SRC'] = DerivativeImage::url(IMG_LARGE, $src_image);
+    $thumbnail['URL'] = duplicate_picture_url(
+        array(
+          'image_id' => $thumbnail['id'],
+          'image_file' => $thumbnail['file'],
+          'section' => 'none',
+        ),
+        array('start')
+      );
+      
+    $thumbnail['COLLECTION_SELECTED'] = true;
+    $thumbnail['COLLECTION_TOGGLE_URL'] = add_url_params($url, array('collection_toggle'=>$thumbnail['id']));
+  }
+  
+  return $tpl_thumbnails_var;
+}
   
 ?>
Index: /extensions/UserCollections/include/events.inc.php
===================================================================
--- /extensions/UserCollections/include/events.inc.php	(revision 23360)
+++ /extensions/UserCollections/include/events.inc.php	(revision 23361)
@@ -20,5 +20,9 @@
     if (in_array(@$tokens[1], array('edit','view','list')))
     {
-       $page['sub_section'] = $tokens[1];
+      $page['sub_section'] = $tokens[1];
+      if ($tokens[1]=='edit' and isset($conf['GThumb']) && is_array($conf['GThumb']))
+      {
+        $conf['GThumb']['big_thumb'] = false; // big thumb is buggy with removes
+      }
     }
     else
@@ -55,23 +59,4 @@
 // | CATEGORY PAGE
 // +-----------------------------------------------------------------------+
-/* toggle an image, in case of no javascript or first call (must create the collection) */
-function user_collections_index_actions()
-{
-  if (is_a_guest()) return;
-  
-  global $page, $UserCollection;
-     
-  // add image to collection list
-  if ( isset($_GET['collection_toggle']) and  preg_match('#^[0-9]+$#', $_GET['collection_toggle']) )
-  {
-    if (empty($UserCollection))
-    {
-      $UserCollection = new UserCollection(get_current_collection_id(true));
-    }
-    $UserCollection->toggleImage($_GET['collection_toggle']);
-    redirect(duplicate_index_url(array(), array('collection_toggle')));
-  }
-}
-
 /* add buttons on thumbnails list */
 function user_collections_thumbnails_list($tpl_thumbnails_var, $pictures)
@@ -79,5 +64,5 @@
   if (is_a_guest()) return $tpl_thumbnails_var;
   
-  global $page, $template, $UserCollection;
+  global $page, $template, $user;
   
   // the content is different on collection edition page and no button on batch downloader set edition page
@@ -87,71 +72,70 @@
   }
   
-  // get existing collections
-  $col_id = get_current_collection_id(false);
-  if (empty($UserCollection) and $col_id !== false)
-  {
-    $UserCollection = new UserCollection($col_id);
-    $collection = $UserCollection->getImages();
-  }
-  else if (!empty($UserCollection))
-  {
-    $collection = $UserCollection->getImages();
-  }
-  else
-  {
-    $collection = array();
-  }
-  
-  // if the collection doesn't exists we don't use AJAX to force menu refresh
-  if ($col_id === false)
-  {
-    $template->assign('NO_AJAX', true);
-  }
-  else
-  {
-    $template->assign('AJAX_COL_ID', $col_id );
-  }
-  
-  // template vars
-  $url = duplicate_index_url(array(), array('collection_toggle'));
+  $image_ids = array_map(create_function('$i', 'return $i["id"];'), $pictures);
+  
+  // get collections for each picture
+  $query = '
+SELECT
+    image_id,
+    GROUP_CONCAT(col_id) AS col_ids
+  FROM '.COLLECTION_IMAGES_TABLE.'
+  WHERE col_id IN (
+      SELECT id
+      FROM '.COLLECTIONS_TABLE.'
+      WHERE user_id = '.$user['id'].'
+    )
+    AND image_id IN('.implode(',', $image_ids).')
+  GROUP BY image_id
+;';
+  $image_collections = simple_hash_from_query($query, 'image_id', 'col_ids');
   
   foreach ($tpl_thumbnails_var as &$thumbnail)
   {
-    if (in_array($thumbnail['id'], $collection))
-    {
-      $thumbnail['COLLECTION_SELECTED'] = true;
-    }
-    $thumbnail['COLLECTION_TOGGLE_URL'] = add_url_params($url, array('collection_toggle'=>$thumbnail['id']));
+    $thumbnail['COLLECTIONS'] = @$image_collections[ $thumbnail['id'] ];
   }
   unset($thumbnail);
   
+  // get all collections
+  $query = '
+SELECT id, name, nb_images, active
+  FROM '.COLLECTIONS_TABLE.'
+  WHERE user_id = '.$user['id'].'
+  ORDER BY name ASC
+;';
+  $collections = hash_from_query($query, 'id');
+  
   $template->assign(array(
+    'COLLECTIONS' => $collections,
     'USER_COLLEC_PATH' => USER_COLLEC_PATH,
     ));
   
   // thumbnails buttons
-  $template->set_prefilter('index_thumbnails', 'user_collections_thumbnails_list_prefilter');
+  $template->set_prefilter('index_thumbnails', 'user_collections_thumbnails_list_button');
+  $template->set_prefilter('index', 'user_collections_thumbnails_list_cssjs');
   
   return $tpl_thumbnails_var;
 }
 
-function user_collections_thumbnails_list_prefilter($content, &$smarty)
-{
-  // add links
+// add links
+function user_collections_thumbnails_list_button($content, &$smarty)
+{
   $search = '#(<li>|<li class="gthumb">)#';
   $replace = '$1
-{strip}<a class="addCollection" href="{$thumbnail.COLLECTION_TOGGLE_URL}" data-id="{$thumbnail.id}" data-stat="{if $thumbnail.COLLECTION_SELECTED}remove{else}add{/if}" rel="nofollow">
-<span class="uc_remove" {if not $thumbnail.COLLECTION_SELECTED}style="display:none;"{/if}>
-{\'Remove from collection\'|@translate}&nbsp;<img src="{$ROOT_URL}{$USER_COLLEC_PATH}template/resources/image_delete.png" title="{\'Remove from collection\'|@translate}">
-</span>
-<span class="uc_add" {if $thumbnail.COLLECTION_SELECTED}style="display:none;"{/if}>
-{\'Add to collection\'|@translate}&nbsp;<img src="{$ROOT_URL}{$USER_COLLEC_PATH}template/resources/image_add.png" title="{\'Add to collection\'|@translate}">
-</span>
+{strip}<a class="addCollection" data-id="{$thumbnail.id}" data-cols="[{$thumbnail.COLLECTIONS}]" rel="nofollow">
+{if not $UC_IN_EDIT}
+{\'Add to collection\'|@translate}&nbsp;<img src="{$ROOT_URL}{$USER_COLLEC_PATH}template/resources/image_add.png" alt="[+]">
+{else}
+{\'Remove from collection\'|@translate}&nbsp;<img src="{$ROOT_URL}{$USER_COLLEC_PATH}template/resources/image_delete.png" alt="[+]">
+{/if}
 </a>{/strip}';
-
-  // custom CSS and AJAX request
+  
+  return preg_replace($search, $replace, $content);
+}
+
+// add css & js and menu
+function user_collections_thumbnails_list_cssjs($content, &$smarty)
+{
   $content.= file_get_contents(USER_COLLEC_PATH.'template/thumbnails_css_js.tpl');
-  
-  return preg_replace($search, $replace, $content);
+  return $content;
 }
 
@@ -165,42 +149,41 @@
   if (is_a_guest()) return;
   
-  global $template, $picture, $UserCollection;
-  
-  // add image to collection list
-  if ( isset($_GET['action']) and $_GET['action'] == 'collection_toggle' )
-  {
-    if (empty($UserCollection))
-    {
-      $UserCollection = new UserCollection(get_current_collection_id(true));
-    }
-    
-    $UserCollection->toggleImage($picture['current']['id']);
-    redirect(duplicate_picture_url());
-  }
-  
-  // get existing collection
-  if (empty($UserCollection) and ($col_id = get_current_collection_id(false)) !== false)
-  {
-    $UserCollection = new UserCollection($col_id);
-    $collection = $UserCollection->isInSet($picture['current']['id']);
-  }
-  else if (!empty($UserCollection))
-  {
-    $collection = $UserCollection->isInSet($picture['current']['id']);
-  }
-  else
-  {
-    $collection = false;
-  }  
-  
-  $url = add_url_params(duplicate_picture_url(), array('action'=>'collection_toggle'));    
-  
-  $button = '
-<a href="'.$url.'" title="'.($collection?l10n('Remove from collection'):l10n('Add to collection')).'" class="pwg-state-default pwg-button" rel="nofollow">
-  <span class="pwg-icon" style="background:url(\''.get_root_url().USER_COLLEC_PATH.'template/resources/image_'.($collection?'delete':'add').'.png\') center center no-repeat;"> </span>
-  <span class="pwg-button-text">'.($collection?l10n('Remove from collection'):l10n('Add to collection')).'</span>
-</a>';
-  // $template->add_picture_button($button, 50);
-  $template->concat('PLUGIN_PICTURE_ACTIONS', $button);
+  global $template, $picture, $user;
+  
+  // get collections for this picture
+  $query = '
+SELECT GROUP_CONCAT(col_id)
+  FROM '.COLLECTION_IMAGES_TABLE.'
+  WHERE col_id IN (
+      SELECT id
+      FROM '.COLLECTIONS_TABLE.'
+      WHERE user_id = '.$user['id'].'
+    )
+    AND image_id = '.$picture['current']['id'].'
+  GROUP BY image_id
+;';
+  list($image_collections) = pwg_db_fetch_row(pwg_query($query));
+  
+  // get all collections
+  $query = '
+SELECT id, name, nb_images, active
+  FROM '.COLLECTIONS_TABLE.'
+  WHERE user_id = '.$user['id'].'
+  ORDER BY name ASC
+;';
+  $collections = hash_from_query($query, 'id');
+  
+  $template->assign(array(
+    'CURRENT_COLLECTIONS' => $image_collections,
+    'COLLECTIONS' => $collections,
+    'USER_COLLEC_PATH' => USER_COLLEC_PATH,
+    'USER_COLLEC_ABS_PATH' => realpath(USER_COLLEC_PATH).'/',
+    'IN_PICTURE' => true,
+    ));
+  
+  // toolbar button
+  $template->set_filename('usercol_button', realpath(USER_COLLEC_PATH.'template/picture_button.tpl'));
+  $button = $template->parse('usercol_button', true);
+  $template->add_picture_button($button, 50);
 }
 
@@ -225,13 +208,6 @@
   $max = 6;
   
-  global $template, $page, $conf, $user, $UserCollection;
+  global $template, $page, $conf, $user;
   $menu = &$menu_ref_arr[0];
-  
-  // the editable counter is for the active collection, except if we are currently editing a collection
-  $col_in_edit = 0;
-  if ( @$page['section'] == 'collections' and @$page['sub_section']=='edit' and !empty($page['col_id']) )
-  {
-    $col_in_edit = $page['col_id'];
-  }
   
   if (($block = $menu->get_block('mbUserCollection')) != null)
@@ -250,7 +226,6 @@
     for ($i=0; $i<$max && $i<count($collections); $i++)
     {
-      $collections[$i]['count_handler'] = $col_in_edit!=0 ? $collections[$i]['id']==$col_in_edit : $collections[$i]['active'];
       $collections[$i]['U_EDIT'] = USER_COLLEC_PUBLIC.'edit/'.$collections[$i]['id'];
-      array_push($data['collections'], $collections[$i]);
+      $data['collections'][] = $collections[$i];
     }
     
Index: /extensions/UserCollections/include/functions.inc.php
===================================================================
--- /extensions/UserCollections/include/functions.inc.php	(revision 23360)
+++ /extensions/UserCollections/include/functions.inc.php	(revision 23361)
@@ -54,5 +54,5 @@
 function get_collection_preferred_image_orders()
 {
-  global $conf, $page;
+  global $conf;
     
   return trigger_event('get_category_preferred_image_orders', array(
@@ -72,3 +72,15 @@
 }
 
+function get_collections_preferred_orders()
+{
+  return array(
+    array(l10n('Name, A &rarr; Z'),               'name ASC',           true),
+    array(l10n('Name, Z &rarr; A'),               'name DESC',          true),
+    array(l10n('Date created, new &rarr; old'),   'date_creation DESC', true),
+    array(l10n('Date created, old &rarr; new'),   'date_creation ASC',  true), 
+    array(l10n('Photos number, high &rarr; low'), 'nb_images DESC',     true),
+    array(l10n('Photos number, low &rarr; high'), 'nb_images ASC',      true),
+    );
+}
+
 ?>
Index: /extensions/UserCollections/include/ws_functions.inc.php
===================================================================
--- /extensions/UserCollections/include/ws_functions.inc.php	(revision 23360)
+++ /extensions/UserCollections/include/ws_functions.inc.php	(revision 23361)
@@ -12,9 +12,9 @@
     array(
       'name' => array(),
-      'user_id' => array('default' => null),
+      'user_id' => array('default' => null, 'info'=>'Admin parameter, default is current user'),
       'active' => array('default' => 0),
       'public' => array('default' => 0),
       ),
-    'Create a new User Collection. If "user_id" is empty, the collection is created for the current user.'
+    'Create a new User Collection.'
     );
     
@@ -23,7 +23,7 @@
     'ws_collections_delete',
     array(
-      'col_id' => array(),
-      ),
-    'Delete a User Collection. The current user must be admin or owner of the collection.'
+      'col_id' => array('info'=>'The current user must be admin or owner of the collection'),
+      ),
+    'Delete a User Collection.'
     );
     
@@ -33,5 +33,5 @@
     array(
       'col_id' => array('default' => null),
-      'user_id' => array('default' => null),
+      'user_id' => array('default' => null, 'info'=>'Admin parameter, default is current user'),
       'name' => array('default' => null),
       'public' => array('default' => null),
@@ -45,8 +45,8 @@
     'ws_collections_addImages',
     array(
-      'col_id' => array(),
+      'col_id' => array('info'=>'The current user must be admin or owner of the collection'),
       'image_ids' => array('flags'=>WS_PARAM_FORCE_ARRAY),
       ),
-    'Add images to a collection. The current user must be admin or owner of the collection.'
+    'Add images to a collection.'
     );
     
@@ -55,8 +55,8 @@
     'ws_collections_removeImages',
     array(
-      'col_id' => array(),
+      'col_id' => array('info'=>'The current user must be admin or owner of the collection'),
       'image_ids' => array('flags'=>WS_PARAM_FORCE_ARRAY),
       ),
-    'Remove images from a collection. The current user must be admin or owner of the collection.'
+    'Remove images from a collection.'
     );
     
@@ -78,7 +78,11 @@
     array(
       'col_id' => array(),
-      'content' => array('default'=>array('id','name','url','path'), 'flags'=>WS_PARAM_FORCE_ARRAY),
-      ),
-    'Returns a serialized version of the collection in CSV.<br>Available options for "content" are : id, file, name, url, path.<br>The return type is plain/text whatever you select as response format.'
+      'content' => array(
+        'default'=>array('id','name','url','path'),
+        'flags'=>WS_PARAM_FORCE_ARRAY,
+        'info'=>'Available options are: id, file, name, url, path'
+        ),
+      ),
+    'Returns a serialized version of the collection in CSV.<br>The return type is plain/text whatever you select as response format.'
     );
 }
Index: /extensions/UserCollections/language/en_UK/plugin.lang.php
===================================================================
--- /extensions/UserCollections/language/en_UK/plugin.lang.php	(revision 23360)
+++ /extensions/UserCollections/language/en_UK/plugin.lang.php	(revision 23361)
@@ -27,4 +27,5 @@
 $lang['Save'] = 'Save';
 $lang['%d more...'] = '%d more...';
+$lang['(remove)'] = '(remove)';
 
 $lang['Allow users to set their collections as public'] = 'Allow users to set their collections as public';
@@ -58,5 +59,8 @@
 $lang['Date added to collection, new &rarr; old'] = 'Date added to collection, new &rarr; old';
 $lang['Date added to collection, old &rarr; new'] = 'Date added to collection, old &rarr; new';
-
+$lang['Name, A &rarr; Z'] = 'Name, A &rarr; Z';
+$lang['Name, Z &rarr; A'] = 'Name, Z &rarr; A';
+$lang['Photos number, high &rarr; low'] = 'Photos number, high &rarr; low';
+$lang['Photos number, low &rarr; high'] = 'Photos number, low &rarr; high';
 
 ?>
Index: /extensions/UserCollections/language/fr_FR/plugin.lang.php
===================================================================
--- /extensions/UserCollections/language/fr_FR/plugin.lang.php	(revision 23360)
+++ /extensions/UserCollections/language/fr_FR/plugin.lang.php	(revision 23361)
@@ -19,5 +19,5 @@
 $lang['Collection'] = 'Collection';
 $lang['Remove from collection'] = 'Supprimer de la collection';
-$lang['Add to collection'] = 'Ajouter à la collection';
+$lang['Add to collection'] = 'Ajouter à une collection';
 $lang['Clear'] = 'Vider';
 $lang['You have %d collection'] = 'Vous avez %d collection';
@@ -27,4 +27,5 @@
 $lang['Save'] = 'Sauvegarder';
 $lang['%d more...'] = 'et %d autres...';
+$lang['(remove)'] = '(retirer)';
 
 $lang['Allow users to set their collections as public'] = 'Les utilisateurs peuvent rendre leurs collections publiques';
@@ -58,4 +59,8 @@
 $lang['Date added to collection, new &rarr; old'] = 'Date d\'ajout à la collection, récent &rarr; ancien';
 $lang['Date added to collection, old &rarr; new'] = 'Date d\'ajout à la collection, ancien &rarr; récent';
+$lang['Name, A &rarr; Z'] = 'Nom, A &rarr; Z';
+$lang['Name, Z &rarr; A'] = 'Nom, Z &rarr; A';
+$lang['Photos number, high &rarr; low'] = 'Nombre de photos, élévé &rarr; faible';
+$lang['Photos number, low &rarr; high'] = 'Nombre de photos, faible &rarr; élévé';
 
 ?>
Index: /extensions/UserCollections/main.inc.php
===================================================================
--- /extensions/UserCollections/main.inc.php	(revision 23360)
+++ /extensions/UserCollections/main.inc.php	(revision 23361)
@@ -4,5 +4,5 @@
 Version: auto
 Description: Registered users can select pictures from the gallery and save them into collections, like advanced favorites.
-Plugin URI: http://piwigo.org/ext/extension_view.php?eid=615
+Plugin URI: auto
 Author: Mistic
 Author URI: http://www.strangeplanet.fr
@@ -41,5 +41,4 @@
 
   // thumbnails actions
-  add_event_handler('loc_end_index', 'user_collections_index_actions');
   add_event_handler('loc_end_index_thumbnails', 'user_collections_thumbnails_list', EVENT_HANDLER_PRIORITY_NEUTRAL-10, 2);
 
Index: /extensions/UserCollections/template/list.tpl
===================================================================
--- /extensions/UserCollections/template/list.tpl	(revision 23360)
+++ /extensions/UserCollections/template/list.tpl	(revision 23361)
@@ -2,5 +2,5 @@
 
 {footer_script require='jquery'}
-jQuery(".save_col").click(function() {ldelim}
+jQuery(".new_col").click(function() {ldelim}
   var name = prompt("{'Collection name:'|@translate}");
   if (name != null) {ldelim}
@@ -11,11 +11,7 @@
   }
 });
+
+jQuery(".titrePage h2").append(" [{$COLLECTIONS_COUNT}]");
 {/footer_script}
-
-{if $themeconf.name == "clear"}
-{html_head}{literal}
-<style type="text/css">.collecList a { color:#eee; }</style>
-{/literal}{/html_head}
-{/if}
 
 {* <!-- Menubar & titrePage --> *}
@@ -35,56 +31,10 @@
 
 
-<p style="text-align:left;font-weight:bold;margin:20px;"><a href="{$U_CREATE}" class="save_col">{'Create a new collection'|@translate}</a></p>
+<p style="text-align:left;font-weight:bold;margin:20px;"><a href="{$U_CREATE}" class="new_col">{'Create a new collection'|@translate}</a></p>
 
-
-{if $temp_col}
-<fieldset>
-  <legend>{'Unsaved collections'|@translate}</legend>
-  
-  <ul class="collecList">
-  {foreach from=$temp_col item=col}
-    <li {if $col.active}class="active"{/if}>
-      <p class="collecTitle">
-        <a href="{$col.U_EDIT}" rel="nofollow"><b>{$col.name}</b></a> 
-        <i>{'%d photos'|@translate|@sprintf:$col.nb_images}</i>
-      </p>
-      <p class="collecActions">
-        <a href="{$col.U_EDIT}" rel="nofollow">{'Edit'|@translate}</a>
-        | <a href="{$col.U_SAVE}" class="save_col" rel="nofollow">{'save'|@translate}</a>
-        {if $col.U_DOWNLOAD}| <a href="{$col.U_DOWNLOAD}" rel="nofollow">{'download'|@translate}</a>{/if}
-        | <a href="{$col.U_DELETE}" onClick="return confirm('{'Are you sure?'|@translate}');" rel="nofollow">{'Delete'|@translate}</a>
-        {if not $col.active}| <a href="{$col.U_ACTIVE}" rel="nofollow">{'set active'|@translate}</a>{/if}
-      </p>
-    </li>
-  {/foreach}
-  </ul>
-</fieldset>
-{/if}
-
-
-{if $collections}
-<fieldset>
-  <legend>{'Saved collections'|@translate}</legend>
-  
-  <ul class="collecList">
-  {foreach from=$collections item=col}
-    <li {if $col.active}class="active"{/if}>
-      <p class="collecDate">
-        {'created on %s'|@translate|@sprintf:$col.date_creation}
-      </p>
-      <p class="collecTitle">
-        <a href="{$col.U_EDIT}" rel="nofollow"><b>{$col.name}</b></a> 
-        <i>{'%d photos'|@translate|@sprintf:$col.nb_images}</i>
-      </p>
-      <p class="collecActions">
-        <a href="{$col.U_EDIT}" rel="nofollow">{'Edit'|@translate}</a>
-        {if $col.U_DOWNLOAD}| <a href="{$col.U_DOWNLOAD}" rel="nofollow">{'download'|@translate}</a>{/if}
-        | <a href="{$col.U_DELETE}" onClick="return confirm('{'Are you sure?'|@translate}');" rel="nofollow">{'Delete'|@translate}</a>
-        {if not $col.active}| <a href="{$col.U_ACTIVE}" rel="nofollow">{'set active'|@translate}</a>{/if}
-      </p>
-    </li>
-  {/foreach}
-  </ul>
-</fieldset>
+{if !empty($CATEGORIES)}
+{$CATEGORIES}
+{else}
+{'You have no collection'|@translate}
 {/if}
 
Index: /extensions/UserCollections/template/menublock_user_collec.tpl
===================================================================
--- /extensions/UserCollections/template/menublock_user_collec.tpl	(revision 23360)
+++ /extensions/UserCollections/template/menublock_user_collec.tpl	(revision 23361)
@@ -11,10 +11,10 @@
 		{foreach from=$block->data.collections item=col}
 		<li>
-      <a href="{$col.U_EDIT}" {if $col.active}style="font-weight:bold;"{/if} rel="nofollow">{$col.name}</a>&nbsp; 
-      {if $col.active}<i class="menuInfoCat">({'active'|@translate})</i>&nbsp;{/if} 
-      <span class="menuInfoCat">[<span {if $col.count_handler}class="nbImagesCollec"{/if}>{$col.nb_images}</span>]</span>
+      <a href="{$col.U_EDIT}" {*if $col.active}style="font-weight:bold;"{/if*} rel="nofollow">{$col.name}</a>&nbsp; 
+      {*if $col.active}<i class="menuInfoCat">({'active'|@translate})</i>&nbsp;{/if*} 
+      <span class="menuInfoCat">[<span class="nbImagesCollec-{$col.id}">{$col.nb_images}</span>]</span>
     </li>
 		{/foreach}
-    {if $block->data.MORE}<li class="menuInfoCat">{'%d more...'|@translate|sprintf:$block->data.MORE}</li>{/if}
+    {if $block->data.MORE}<li class="menuInfoCat"><a href="{$block->data.U_LIST}">{'%d more...'|@translate|sprintf:$block->data.MORE}</a></li>{/if}
 	{/strip}</ul>
   {/if}
Index: /extensions/UserCollections/template/picture_button.tpl
===================================================================
--- /extensions/UserCollections/template/picture_button.tpl	(revision 23361)
+++ /extensions/UserCollections/template/picture_button.tpl	(revision 23361)
@@ -0,0 +1,24 @@
+{include file=$USER_COLLEC_ABS_PATH|cat:'template/thumbnails_css_js.tpl'}
+
+{footer_script require='jquery'}{literal}
+jQuery().ready(function() {
+  jQuery("#collectionsLink").click(function() {
+	  var elt = jQuery("#collectionsDropdown");
+
+    elt.css("left", Math.min( jQuery(this).offset().left, jQuery(window).width() - elt.outerWidth(true) - 5))
+      .css("top", jQuery(this).offset().top + jQuery(this).outerHeight(true))
+      .toggle();
+
+    return false;
+  });
+
+  jQuery("#collectionsDropdown").on("mouseleave", function() {
+    jQuery(this).hide();
+  });
+});
+{/literal}{/footer_script}
+
+<a id="collectionsLink" title="{'Add to collection'|@translate}" class="pwg-state-default pwg-button addCollection" rel="nofollow" data-id="{$current.id}" data-cols="[{$CURRENT_COLLECTIONS}]">
+  <span class="pwg-icon" style="background:url('{$ROOT_URL}{$USER_COLLEC_PATH}template/resources/image_add.png') center center no-repeat;"></span>
+  <span class="pwg-button-text">{'Add to collection'|@translate}</span>
+</a>
Index: /extensions/UserCollections/template/style.css
===================================================================
--- /extensions/UserCollections/template/style.css	(revision 23360)
+++ /extensions/UserCollections/template/style.css	(revision 23361)
@@ -42,36 +42,25 @@
     margin-left:5px;
   }
-  
-.collecList {
-  list-style:none;
-  padding:0;
-  margin:0;
+
+/* .thumbnailCategory.activeCollection {
+  border:1px solid #999;
+} */
+.thumbnailCategory {
+  position:relative;
 }
-  .collecList li {
-    height:35px;
-    padding:5px 10px;
-    margin:4px 0;
-    background:#444;
-    border-radius:4px;
-  }
-    .collecList li.active {
-      background:#555;
-      border:1px solid #999;
-    }
-  .collecList p {
-    margin:0;
-  }
-    .collecList .collecDate {
-      float:right;
-      font-size:0.9em;
-    }
-    .collecList .collecActions { 
-      margin-top:2px;
-      display:none;
-    }
-    .collecList li:hover .collecActions { 
-      display:block;
-    }
-  
+.thumbnailCategory .collectionActions {
+  display:none;
+  position:absolute;
+  right:5px;
+  bottom:5px;
+}
+.thumbnailCategory:hover .collectionActions {
+  display:block;
+}
+/* .thumbnailCategory .collectionActive {
+  font-weight:normal;
+  font-style:italic;
+} */
+
 /* SEND BY MAIL */
 #mail_form {
Index: /extensions/UserCollections/template/style_thumbnails.css
===================================================================
--- /extensions/UserCollections/template/style_thumbnails.css	(revision 23361)
+++ /extensions/UserCollections/template/style_thumbnails.css	(revision 23361)
@@ -0,0 +1,47 @@
+#thumbnails li {
+  position:relative !important;
+  display:inline-block;
+}
+#thumbnails li .addCollection {
+  width:100%;
+  height:16px;
+  display:none;
+  position:absolute;
+  top:0;
+  background:rgba(0,0,0,0.8);
+  padding:2px;
+  border-radius:2px;
+  font-size:10px;
+  z-index:100 !important;
+  color:#eee;
+  white-space:nowrap;
+}
+#thumbnails li:hover .addCollection {
+  display:block !important;
+}
+
+#collectionsDropdown {
+  display:none;
+  position:fixed;
+  top:0;
+  left:0;
+  box-shadow:2px 2px 10px #000;
+}
+
+#collectionsDropdown .switchBoxTitle {
+  font-weight:bold;
+}
+
+#collectionsDropdown .switchBoxFooter {
+  border-top:1px solid #444;
+  padding-top:5px;
+  margin-top:5px;
+}
+
+#collectionsDropdown a, a.addCollection {
+  cursor:pointer;
+}
+
+#collectionsDropdown .remove, #collectionsDropdown input.new {
+  display:none;
+}
Index: /extensions/UserCollections/template/thumbnails_css_js.tpl
===================================================================
--- /extensions/UserCollections/template/thumbnails_css_js.tpl	(revision 23360)
+++ /extensions/UserCollections/template/thumbnails_css_js.tpl	(revision 23361)
@@ -1,19 +1,85 @@
-{html_style}
-#thumbnails li {ldelim} position:relative !important;display:inline-block; }
-li .addCollection {ldelim} width:100%;height:16px;display:none;position:absolute;top:0;background:rgba(0,0,0,0.8);padding:2px;border-radius:2px;font-size:10px;z-index:100 !important;color:#eee;white-space:nowrap; }
-li:hover .addCollection {ldelim} display:block !important; }
-{/html_style}
-
-{if not $NO_AJAX}
+{combine_css path=$USER_COLLEC_PATH|@cat:"template/style_thumbnails.css"}
+
+{* <!-- all pages but collection edit page --> *}
+{if not $UC_IN_EDIT}
 {footer_script require='jquery'}
-jQuery(".addCollection").click(function() {ldelim}
-  var $trigger = jQuery(this);
-  var toggle_id = $trigger.data("id");
-  var method = $trigger.data("stat");
-  
-  if (method != "add" && method != "remove") {ldelim}
-    $trigger.html("{'Un unknown error occured'|@translate}");
+var $cdm = jQuery("#collectionsDropdown");
+
+{if not $IN_PICTURE}
+$cdm.on("mouseleave", function() {ldelim}
+  $cdm.hide();
+});
+{/if}
+
+// click on "create collection" button
+$cdm.find("a.new").on("click", function(event) {ldelim}
+  jQuery(this).hide().next().show().focus();
+  event.stopPropagation();
+  return false;
+});
+
+// events on "new collection" input
+$cdm.find("input.new").on({ldelim}
+  // ENTER pressed
+  "keyup": function(event) {ldelim}
+    if (event.which != 13) return;
+    
+    jQuery(this).hide().prev().show();
+    var name = jQuery(this).val();
+    jQuery(this).val("{'Name'|@translate}");
+    
+    if (name == "") return;
+    
+    jQuery.ajax({ldelim}
+      type: "GET",
+      dataType: "json",
+      url: "{$ROOT_URL}ws.php",
+      data: {ldelim}
+        format: "json",
+        method: "pwg.collections.create",
+        name: name,
+        active: 1,
+      },
+      success: function(data) {ldelim}
+        if (data.stat == 'ok') {ldelim}
+          var col = data.result;
+          var html = '<span>&#9733;</span> <a class="add" data-id="'+ col.id +'">'+ col.name +'</a> '
+            +'<span class="menuInfoCat">[<span class="nbImagesCollec-'+ col.id +'">'+ col.nb_images +'</span>]</span> '
+            +'<a class="remove" data-id="'+ col.id +'">{'(remove)'|@translate}</a>'
+            +'<br>';
+          
+          $cdm.children(".switchBoxFooter").before(html);
+          $cdm.children(".noCollecMsg").remove();
+        }
+        else {ldelim}
+          alert(data.message);
+        }
+      },
+      error: function() {ldelim}
+        alert("{'Un unknown error occured'|@translate}");
+      }
+    });
+    
     return false;
+  },
+  // prevent click propagation
+  "click": function(event) {ldelim}
+    event.stopPropagation();
+  },
+  // remove help on focus
+  "focus": function() {ldelim}
+    if (jQuery(this).val() == "{'Name'|@translate}") jQuery(this).val("");
+  },
+  // restore help on blur
+  "blur" : function() {ldelim}
+    if (jQuery(this).val() == "") jQuery(this).val("{'Name'|@translate}");
   }
+});
+
+// add and remove links (delegate for new collections)
+$cdm.on("click", ".add, .remove", function() {ldelim}
+  var img_id = $cdm.data("img_id");
+  var col_id = jQuery(this).data("id");
+  var method = jQuery(this).hasClass("add") ? "pwg.collections.addImages" : "pwg.collections.removeImages";
   
   jQuery.ajax({ldelim}
@@ -21,34 +87,126 @@
     dataType: "json",
     url: "{$ROOT_URL}ws.php",
-    data: {ldelim} "format": "json", "method": "pwg.collections."+method+"Images", "col_id": {$AJAX_COL_ID}, "image_ids": toggle_id },
+    data: {ldelim}
+      format: "json",
+      method: method,
+      col_id: col_id,
+      image_ids: img_id
+    },
     success: function(data) {ldelim}
-      if (data['stat'] == 'ok') {ldelim}
-        if (method == "add") {ldelim}
-          $trigger.children(".uc_remove").show();
-          $trigger.children(".uc_add").hide();
-          $trigger.data("stat", "remove");
-        }
-        else if (method == "remove") {ldelim}
-        {if $UC_IN_EDIT}
-          $trigger.parent("li").hide("fast", function() {ldelim} $(this).remove() });
-          if (typeof batchdown_count != 'undefined') batchdown_count-=1;
-        {else}
-          $trigger.children(".uc_remove").hide();
-          $trigger.children(".uc_add").show();
-          $trigger.data("stat", "add");
-        {/if}
-        }
+      if (data.stat == 'ok') {ldelim}
+        // update col counters
+        jQuery(".nbImagesCollec-"+col_id).html(data.result.nb_images);
         
-        jQuery(".nbImagesCollec").html(data['result']['nb_images']);
+        // update item datas
+        var $target = jQuery(".addCollection[data-id='"+ img_id +"']");
+        var col_ids = $target.data("cols");
+        if (method == "pwg.collections.addImages" && col_ids.indexOf(col_id) == -1)
+          col_ids[ col_ids.length ] = col_id;
+        else
+          col_ids.splice(col_ids.indexOf(col_id), 1);
+        $target.data("col", col_ids);
       }
       else {ldelim}
-        $trigger.html("{'Un unknown error occured'|@translate}");
+        alert(data.message);
       }
     },
     error: function() {ldelim}
-      $trigger.html("{'Un unknown error occured'|@translate}");
-    }
-  });
-  
+      alert("{'Un unknown error occured'|@translate}");
+    }
+  });
+  
+  $cdm.hide();
+  return false;
+});
+
+// main button, open the menu
+jQuery(".addCollection").on("click", function(event) {ldelim}
+  var img_id = jQuery(this).data("id");
+  var col_ids = jQuery(this).data("cols");
+  
+  $cdm.data("img_id", img_id);
+  
+  $cdm.children(".add").each(function() {ldelim}   
+    if (col_ids.indexOf($(this).data("id")) != -1) {ldelim}
+      $(this).css("font-weight", "bold").next().next().show();
+    }
+    else {ldelim}
+      $(this).css("font-weight", "normal").next().next().hide();
+    }
+  });
+  
+  {if not $IN_PICTURE}
+  $cdm.css({ldelim}
+    "top": event.pageY-5-$(window).scrollTop(),
+    "left": Math.min(event.pageX-jQuery(window).scrollLeft()-20, jQuery(window).width()-$cdm.outerWidth(true)-5) 
+  });
+  $cdm.show();
+  {/if}
+  
+  return false;
+});
+
+// try to respect theme colors
+$cdm.children(".switchBoxFooter").css("border-top-color", $cdm.children(".switchBoxTitle").css("border-bottom-color"));
+{/footer_script}
+
+<div id="collectionsDropdown" class="switchBox">
+  <div class="switchBoxTitle">{'Collections'|@translate}</div>
+  
+  {foreach from=$COLLECTIONS item=col}
+    <span>&#9733;</span> <a class="add" data-id="{$col.id}">{$col.name}</a>
+    <span class="menuInfoCat">[<span class="nbImagesCollec-{$col.id}">{$col.nb_images}</span>]</span>
+    <a class="remove" data-id="{$col.id}">{'(remove)'|@translate}</a>
+    <br>
+  {foreachelse}
+    <span class="noCollecMsg">{'You have no collection'|@translate}</span>
+  {/foreach}
+  
+  <div class="switchBoxFooter">
+  <span>&#10010;</span> <a class="new">{'Create a new collection'|@translate}</a>
+  <input class="new" value="{'Name'|@translate}" size="25"/>
+  </div>
+</div>
+
+{* <!-- collection edit page --> *}
+{else}
+{footer_script require='jquery'}
+jQuery(".addCollection").on("click", function(event) {ldelim}
+  var $trigger = jQuery(this);
+  var img_id = jQuery(this).data("id");
+  var col_id = {$collection.ID};
+  
+  jQuery.ajax({ldelim}
+    type: "GET",
+    dataType: "json",
+    url: "{$ROOT_URL}ws.php",
+    data: {ldelim}
+      format: "json",
+      method: "pwg.collections.removeImages",
+      col_id: col_id,
+      image_ids: img_id
+    },
+    success: function(data) {ldelim}
+      if (data.stat == 'ok') {ldelim}
+        $trigger.parent("li").hide("fast", function() {ldelim}
+          jQuery(this).remove();
+          if (typeof GThumb != "undefined") GThumb.build();
+        });
+        
+        jQuery(".nbImagesCollec-"+col_id).html(data.result.nb_images);
+        if (typeof batchdown_count != 'undefined') batchdown_count = data.result.nb_images;
+      }
+      else {ldelim}
+        alert(data.message);
+      }
+    },
+    error: function() {ldelim}
+      alert("{'Un unknown error occured'|@translate}");
+    }
+  });
+  
+  // not working, the event is fired twice
+  event.stopPropagation();
+  event.preventDefault();
   return false;
 });
