--- realname.module	Tue Dec 30 15:30:42 2008
+++ realname.module	Mon Feb 16 03:06:37 2009
@@ -47,6 +47,14 @@
 function realname_menu() {
   global $user;
   $items = array();
+  
+  $items['realname/autocomplete'] = array(
+    'title' => 'Realname autocomplete',
+    'page callback' => 'realname_autocomplete',
+    'access callback' => 'user_access',
+    'access arguments' => array('access user profiles'),
+    'type' => MENU_CALLBACK,
+  );
 
   $items['admin/user/realname'] = array(
     'title' => 'RealName',
@@ -247,6 +255,11 @@
       $form['name']['#default_value'] = $user->uid ? $user->realname : '';
       break;
   }
+  
+  if (isset($form['#id']) && $form['#id'] == 'node-form' && user_access('administer nodes')) {
+    $form['author']['name']['#autocomplete_path'] = 'realname/autocomplete';
+    array_unshift($form['#validate'], 'realname_node_form_validate');
+  }
 }
 
 //********************************************************************
@@ -367,6 +380,56 @@
   }
 
   return $ret;
+}
+
+/**
+ * Menu callback; Retrieve a JSON object containing autocomplete suggestions for existing users.
+ */
+function realname_autocomplete($string = '') {
+  $matches = array();
+  if ($string) {
+    $result = db_query("SELECT uid, name FROM {users}");
+    while ($user = db_fetch_object($result)) {
+      $realname = realname_make_name($user);
+      if (strpos(strtolower($realname), strtolower($string)) === 0) {
+        $realname = $realname . ' [' . $user->name . ']';
+        $matches[$realname] = check_plain($realname);
+        //Limit results to 10
+        if (count($matches) == 10) {
+          break;
+        }
+      }
+    }
+  }
+
+  drupal_json($matches);
+}
+
+function realname_node_form_validate($form, &$form_state) {
+  if ($username = realname_node_validate($form_state['values'], $form)) {
+    //Update the form's "authored by" value
+    $form_item['#parents'] = array('name');
+    form_set_value($form_item, $username, $form_state);
+  }
+}
+
+/**
+ * Perform validation checks on the given node.
+ * Precedes node_validate when the user has the 'administer nodes' permission.
+ * This is necessary to validate the "authored by" field against the format used by realname_autocomplete.
+ */
+function realname_node_validate($node, $form = array()) {
+  // Convert the node to an object, if necessary.
+  $node = (object)$node;
+
+  //Only try modifying the "authored by" value if it isn't already a valid username
+  if (!empty($node->name) && !($account = user_load(array('name' => $node->name))) && strrpos($node->name, '[') !== FALSE) {
+    $node->name = substr($node->name, strrpos($node->name, '[')+1, -1);
+    if (!empty($node->name) && $account = user_load(array('name' => $node->name))) {
+      return $node->name;
+    }
+  }
 }
 
 /**
