--- C:/Documents and Settings/Boki/Desktop/head/patches/imagefield/imagefield.module	Sat Jun 16 14:25:37 2007
+++ C:/Documents and Settings/Boki/Desktop/head/patches/unique filenames/imagefield.module	Sat Jul 21 00:30:34 2007
@@ -486,6 +486,18 @@
 
     if ($valid_image) { 
       $file = _imagefield_scale_image($file, $field['widget']['max_resolution']);
+      
+      // The images in session need to have unique filenames, in order not to mix up the thumbs
+      $cnt = 1;
+      $filename_parts = explode('.', $file['filename']);
+      
+      $filename = _imagefield_rebuild_filename($filename_parts, $cnt);
+      while(file_exists($path . '/' . $filename) || _imagefield_in_session($filename)) {
+        $cnt++;
+        $filename = _imagefield_rebuild_filename($filename_parts, $cnt);
+      }
+      
+      $file['filename'] = $filename;
 
       // Create the filepath for the image preview
       if (function_exists('token_replace')) {
@@ -536,6 +548,33 @@
     }
   }
 }  
+
+function _imagefield_rebuild_filename($filename_parts, $cnt) {
+  $filename = ucfirst(strtolower($filename_parts[0])) . '_' . $cnt;
+  
+  foreach($filename_parts as $id => $part) {
+    if($id == 0) continue; // Ignore the first part, we already included it
+    $filename .= '.' . strtolower($part);  
+  }
+  
+  return $filename;
+}
+
+// See if a filename exists in the session, check every field
+function _imagefield_in_session($filename) {
+  if(count($_SESSION['imagefield']) > 0) { 
+    foreach($_SESSION['imagefield'] as $field) {
+      if(count($field) > 0) {
+        foreach($field as $file) {
+          if($file['filename'] == $filename) {
+            return true;  
+          }
+        }
+      }
+    }
+  }
+  return false;
+}
 
 function _imagefield_widget_form($node, $field, &$items) {
   drupal_add_js('misc/progress.js');
