--- casetracker.module	2008-07-15 17:30:46.000000000 +0100
+++ casetracker.module	2008-07-16 11:42:38.000000000 +0100
@@ -1348,6 +1349,13 @@ function casetracker_settings() {
     '#description'   => t('Select the node types that will be considered Case Tracker cases.'),
   );
 
+  $form['casetracker_general']['casetracker_assignto_roles'] = array(
+    '#type' => 'checkboxes',
+    '#title' => t('User roles assignment'),
+    '#default_value' => variable_get('casetracker_assignto_roles', array()),
+    '#options' => user_roles(1),
+    '#description'   => t('Select the user roles to which cases can be assigned'),
+  );
   return system_settings_form($form);
 }
 
@@ -1357,8 +1365,26 @@ function casetracker_settings() {
  * include OG specific users subscribed to a project.
  */
 function casetracker_autocomplete($string) {
+  $where = array();
+  $args = array();
+  $join = array();
+
+  if (!empty($string)) {
+    $where[] = "LOWER(name) LIKE LOWER('%s%%')";
+    $args[] = $string;
+  }
+  else {
+    $where[] = "u.uid > 0";
+  }
+
+  $roles = variable_get('casetracker_assignto_roles', array());
+  $roles = array_intersect(array_keys(user_roles(1)), $roles);
+  if (!empty($roles) && !in_array(DRUPAL_AUTHENTICATED_RID, $roles)) {
+    $where[] = "r.rid IN (". implode($roles, ',') .")";
+    $join[] = 'LEFT JOIN {users_roles} r ON u.uid = r.uid';
+  }
   $matches = array();
-  $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name) LIKE LOWER('%s%%')", $string, 0, 10);
+  $result = db_query('SELECT u.name, u.uid FROM {users} u '. implode(' ', $join) .' WHERE '. implode(' AND ', $where) .' ORDER BY u.name ASC', $args);
   while ($user = db_fetch_object($result)) {
     $matches[$user->name] = check_plain($user->name);
   }
