Index: modules/book/book.css
===================================================================
RCS file: /cvs/drupal/drupal/modules/book/book.css,v
retrieving revision 1.1
diff -u -p -r1.1 book.css
--- modules/book/book.css	14 Aug 2006 07:14:49 -0000	1.1
+++ modules/book/book.css	29 Aug 2006 04:53:47 -0000
@@ -19,3 +19,12 @@
 .book-navigation .page-next {
   text-align: left;
 }
+.book-toc {
+  border-top: 1px solid #888;
+  border-bottom: 1px solid #888;
+}
+h2.book-outline {
+  border-top: 1px solid #888;
+  margin-top: 1em;
+  padding-top: 1em;
+}
Index: modules/book/book.install
===================================================================
RCS file: /cvs/drupal/drupal/modules/book/book.install,v
retrieving revision 1.5
diff -u -p -r1.5 book.install
--- modules/book/book.install	20 Aug 2006 06:38:50 -0000	1.5
+++ modules/book/book.install	29 Aug 2006 04:53:47 -0000
@@ -1,30 +1,106 @@
 <?php
-// $Id: book.install,v 1.5 2006/08/20 06:38:50 dries Exp $
+// $Id: 
 
 function book_install() {
   switch ($GLOBALS['db_type']) {
     case 'mysql':
     case 'mysqli':
+      db_query("CREATE TABLE {book_pages} (
+        nid int unsigned NOT NULL default '0',
+        book_id int unsigned NOT NULL default '0',
+        parent int unsigned NOT NULL default '0',
+        weight smallint NOT NULL default '0',
+        PRIMARY KEY (nid),
+        KEY book_id (book_id),
+        KEY parent (parent)
+      ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
       db_query("CREATE TABLE {book} (
+        nid int unsigned NOT NULL default '0',
         vid int unsigned NOT NULL default '0',
+        child_type varchar(32) NOT NULL default '',
+        weight smallint NOT NULL default '0',
+        toc_depth smallint unsigned NOT NULL default '1',
+        PRIMARY KEY  (nid, vid),
+        UNIQUE KEY vid (vid)
+      ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
+      break;
+    case 'pgsql':
+      db_query("CREATE TABLE {book_pages} (
+        nid int_unsigned NOT NULL default '0',
+        book_id int_unsigned NOT NULL default '0',
+        parent int_unsigned NOT NULL default '0',
+        weight smallint NOT NULL default '0',
+        PRIMARY KEY (nid)
+      ");
+      db_query("CREATE INDEX {book_pages}_bid_idx ON {book_pages} (book_id)");
+      db_query("CREATE INDEX {book_pages}_parent_idx ON {book_pages} (parent)");
+      db_query("CREATE TABLE {book} (
+        nid int_unsigned NOT NULL default '0',
+        vid int_unsigned NOT NULL default '0',
+        child_type varchar(32) NOT NULL default '',
+        weight smallint NOT NULL default '0',
+        toc_depth smallint_unsigned NOT NULL default '1',
+        PRIMARY KEY (nid, vid),
+        UNIQUE (vid)
+      )");
+      break;
+  }
+}
+
+/**
+ * Update book table definitions.
+ */
+function book_update_1000() {
+  $ret = array();
+  
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+    $ret[] = update_sql("CREATE TABLE {book_pages} (
         nid int unsigned NOT NULL default '0',
-        parent int NOT NULL default '0',
+        book_id int unsigned NOT NULL default '0',
+        parent int unsigned NOT NULL default '0',
         weight tinyint NOT NULL default '0',
-        PRIMARY KEY (vid),
-        KEY nid (nid),
+        PRIMARY KEY (nid),
+        KEY book_id (book_id),
         KEY parent (parent)
+        ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
+      $ret[] = update_sql("INSERT INTO {book_pages} (nid, parent, weight) SELECT b.nid, b.parent, b.weight FROM {book} b INNER JOIN node n ON b.vid=n.vid");
+      $ret[] = update_sql("UPDATE {node} SET type = 'book_page' WHERE type = 'book'");
+      $ret[] = update_sql("DROP TABLE {book}");
+      $ret[] = update_sql("CREATE TABLE {book} (
+        nid int unsigned NOT NULL default '0',
+        vid int unsigned NOT NULL default '0',
+        child_type varchar(32) NOT NULL default '',
+        weight smallint NOT NULL default '0',
+        toc_depth smallint unsigned NOT NULL default '1',
+        PRIMARY KEY  (nid, vid),
+        UNIQUE KEY vid (vid),
       ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
       break;
     case 'pgsql':
-      db_query("CREATE TABLE {book} (
-        vid int_unsigned NOT NULL default '0',
+      $ret[] = update_sql("CREATE TABLE {book_pages} (
         nid int_unsigned NOT NULL default '0',
-        parent int NOT NULL default '0',
+        book_id int_unsigned NOT NULL default '0',
+        parent int_unsigned NOT NULL default '0',
+        weight smallint NOT NULL default '0',
+        PRIMARY KEY (nid)
+      ");
+      $ret[] = update_sql("CREATE INDEX {book_pages}_bid_idx ON {book_pages} (book_id)");
+      $ret[] = update_sql("CREATE INDEX {book_pages}_parent_idx ON {book_pages} (parent)");
+      $ret[] = update_sql("INSERT INTO {book_pages} (nid, parent, weight) SELECT b.nid, b.parent, b.weight FROM {book} b INNER JOIN node n ON b.vid=n.vid");
+      $ret[] = update_sql("UPDATE {node} SET type = 'book_page' WHERE type = 'book'");
+      $ret[] = update_sql("DROP TABLE {book}");
+      $ret[] = update_sql("CREATE TABLE {book} (
+        nid int_unsigned NOT NULL default '0',
+        vid int_unsigned NOT NULL default '0',
+        child_type varchar(32) NOT NULL default '',
         weight smallint NOT NULL default '0',
-        PRIMARY KEY (vid)
+        toc_depth smallint_unsigned NOT NULL default '1',
+        PRIMARY KEY (nid, vid),
+        UNIQUE (vid)
       )");
-      db_query("CREATE INDEX {book}_nid_idx ON {book} (nid)");
-      db_query("CREATE INDEX {book}_parent_idx ON {book} (parent)");
       break;
   }
+  return $ret;
 }
Index: modules/book/book.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/book/book.module,v
retrieving revision 1.386
diff -u -p -r1.386 book.module
--- modules/book/book.module	23 Aug 2006 06:38:49 -0000	1.386
+++ modules/book/book.module	29 Aug 2006 04:53:48 -0000
@@ -3,7 +3,12 @@
 
 /**
  * @file
- * Allows users to collaboratively author a book.
+ * A module to enable nodes to be organized into books
+ *
+ * A book is a set of pages tied together in sequence, with links and menus to 
+ * guide users from section to section or to the previous page or the next.
+ * Users can collaborate in writing the book, reviewing or modifying the pages, 
+ * and putting them in the right order.
  */
 
 /**
@@ -11,11 +16,16 @@
  */
 function book_node_info() {
   return array(
-    'book' => array(
+    'book_page' => array(
       'name' => t('book page'),
+      'module' => 'book_page',
+      'description' => t("A book page is usually added to a book, but can also be independent. Books can represent a collaborative writing effort: users can collaborate writing the pages of the book, positioning the pages in the right order, and reviewing or modifying pages"),
+    ),
+    'book' => array(
+      'name' => t('book'),
       'module' => 'book',
-      'description' => t("A book is a collaborative writing effort: users can collaborate writing the pages of the book, positioning the pages in the right order, and reviewing or modifying pages previously written. So when you have some information to share or when you read a page of the book and you didn't like it, or if you think a certain page could have been written better, you can do something about it."),
-    )
+      'description' => t('Add a new book. Book pages (and other content) can then be added to this book and will be linked and displayed in a table of contents.'),
+    ),
   );
 }
 
@@ -27,24 +37,35 @@ function book_perm() {
 }
 
 /**
- * Implementation of hook_access().
+ * Implementation of hook_access() for a book cover.
  */
 function book_access($op, $node) {
   global $user;
 
   if ($op == 'create') {
-    // Only registered users can create book pages. Given the nature
-    // of the book module this is considered to be a good/safe idea.
-    return user_access('create book pages');
+    return user_access('create new books');
   }
-
   if ($op == 'update') {
-    // Only registered users can update book pages. Given the nature
-    // of the book module this is considered to be a good/safe idea.
-    // One can only update a book page if there are no suggested updates
-    // of that page waiting for approval. That is, only updates that
-    // don't overwrite the current or pending information are allowed.
+    if ($node->uid == $user->uid && user_access('edit own book pages')) {
+      return TRUE;
+    }
+    else {
+       // do nothing. node-access() will determine further access
+    }
+  }
+}
+
+/**
+ * Implementation of hook_access() for a book page.
+ */
+function book_page_access($op, $node) {
+  global $user;
 
+  if ($op == 'create') {
+    return user_access('create book pages');
+  }
+  if ($op == 'update') {
+    // users with 'edit book pages' permission may edit ALL book pages.
     if (user_access('edit book pages') || ($node->uid == $user->uid && user_access('edit own book pages'))) {
       return TRUE;
     }
@@ -60,21 +81,39 @@ function book_access($op, $node) {
 function book_link($type, $node = NULL, $teaser = FALSE) {
 
   $links = array();
-
-  if ($type == 'node' && isset($node->parent)) {
-    if (!$teaser) {
-      if (book_access('create', $node)) {
+  if ($type == 'node' && isset($node->book_id)) {
+    $book_types = variable_get('book_node_types', array('book'));
+    $child_type = db_result(db_query('SELECT child_type from {book} WHERE nid = %d ORDER BY vid DESC', $node->book_id));
+    if (!$child_type || in_array($child_type, $book_types)) {
+      $child_type  = 'book_page'; 
+    }
+    
+    if (in_array($node->type, $book_types)) {
+      if (node_access('create', $child_type)) {
         $links['book_add_child'] = array(
           'title' => t('add child page'),
-          'href' => "node/add/book/parent/$node->nid"
+          'href' => "node/add/". $child_type,
+          'query' => 'book='. $node->nid. '/'. $node->nid,
         );
       }
-      if (user_access('see printer-friendly version')) {
-        $links['book_printer'] = array(
-          'title' => t('printer-friendly version'),
-          'href' => 'book/export/html/'. $node->nid,
-          'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
-        );
+      return $links;
+    }
+    else {
+      if (!$teaser) {
+        if (node_access('create', $child_type)) {
+          $links['book_add_child'] = array(
+            'title' => t('add child page'),
+            'href' => "node/add/". $child_type,
+            'query' => 'book='. $node->book_id. '/'. $node->nid,
+          );
+        }
+        if (user_access('see printer-friendly version')) {
+          $links['book_printer'] = array(
+            'title' => t('printer-friendly version'),
+            'href' => 'book/export/html/'. $node->nid,
+            'attributes' => array('title' => t('Show a printer-friendly version of this book page and its sub-pages.'))
+          );
+        }
       }
     }
   }
@@ -105,13 +144,19 @@ function book_menu($may_cache) {
       'callback' => 'drupal_get_form',
       'callback arguments' => array('book_admin_orphan'),
       'type' => MENU_LOCAL_TASK,
-      'weight' => 8);
+      'weight' => 5);
+     $items[] = array('path' => 'admin/content/book/settings',
+      'title' => t('settings'),
+      'callback' => 'drupal_get_form',
+      'callback arguments' => array('book_admin_settings'),
+      'weight' => 8,
+      'type' => MENU_LOCAL_TASK);
     $items[] = array(
       'path' => 'book',
-      'title' => t('books'),
-      'callback' => 'book_render',
-      'access' => user_access('access content'),
-      'type' => MENU_SUGGESTED_ITEM);
+      'title' => t('book shelf'),
+      'callback' => 'book_shelf',
+      'type' => MENU_NORMAL_ITEM,
+      'access' => user_access('access content'));
     $items[] = array(
       'path' => 'book/export',
       'callback' => 'book_export',
@@ -123,126 +168,111 @@ function book_menu($may_cache) {
     // We put this in !$may_cache so it's only added once per request
     drupal_add_css(drupal_get_path('module', 'book') .'/book.css');
 
+    $items[] = array(
+      'path' => 'node/add/book_page/select_book',
+      'title' => t('New page'),
+      'callback' => 'drupal_get_form',
+      'callback arguments' => array('_add_page_select_book'),
+      'access' => user_access('create book pages'),
+      'type' => MENU_LOCAL_TASK, 
+      'weight' => 2);
     // To avoid SQL overhead, check whether we are on a node page and whether the
     // user is allowed to outline posts in books.
     if (arg(0) == 'node' && is_numeric(arg(1)) && user_access('outline posts in books')) {
-      // Only add the outline-tab for non-book pages:
-      $result = db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE n.nid = %d AND n.type != 'book'"), arg(1));
-      if (db_num_rows($result) > 0) {
+      $type = db_result(db_query("SELECT n.type FROM {node} n WHERE n.nid=%d",arg(1)));
+        $book_types = variable_get('book_node_types', array('book'));
+      if (($type) && (!in_array($type, $book_types))) {
         $items[] = array(
           'path' => 'node/'. arg(1) .'/outline',
           'title' => t('outline'),
           'callback' => 'drupal_get_form',
-          'callback arguments' => array('book_outline', arg(1)),
+          'callback arguments' => array('book_outline_form',arg(1)),
           'access' => user_access('outline posts in books'),
           'type' => MENU_LOCAL_TASK,
           'weight' => 2);
       }
     }
   }
-
   return $items;
 }
 
 /**
  * Implementation of hook_block().
  *
- * Displays the book table of contents in a block when the current page is a
- * single-node view of a book node.
+ * The navigation block displays the book table of contents in a block when the
+ * current page is a single-node view a node that's in the book hierarchy. 
  */
 function book_block($op = 'list', $delta = 0) {
   $block = array();
   if ($op == 'list') {
-    $block[0]['info'] = t('Book navigation');
+    $block['navigation']['info'] = t('Book navigation');
     return $block;
   }
-  else if ($op == 'view') {
-    // Only display this block when the user is browsing a book:
+  elseif ($op == 'view') {
+    // Book navigation block
+    // Only display this block when the user is browsing a node in the book outline (book_pages table):
     if (arg(0) == 'node' && is_numeric(arg(1))) {
-      $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), arg(1));
-      if (db_num_rows($result) > 0) {
-        $node = db_fetch_object($result);
-
-        $path = book_location($node);
-        $path[] = $node;
-
+      $this_node = node_load(arg(1));
+      $book_types = variable_get('book_node_types', array('book'));
+      if (isset($this_node->book_id) && (!in_array($this_node->type, $book_types))) {          
+        $path = book_location($this_node);
+        $path[] = $this_node;
+   
         $expand = array();
         foreach ($path as $key => $node) {
           $expand[] = $node->nid;
         }
-
+        $block['content'] = book_page_menu_tree($this_node->book_id,$path[0]->nid, 5, $expand);
         $block['subject'] = check_plain($path[0]->title);
-        $block['content'] = book_tree($expand[0], 5, $expand);
       }
     }
-
     return $block;
   }
 }
 
 /**
- * Implementation of hook_load().
+ * Implementation of hook_submit() for book pages.
  */
-function book_load($node) {
-  return db_fetch_object(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
+function book_page_submit(&$node) {
+  global $user;
+  // Set default values for non-administrators.
+  if (!user_access('administer nodes')) {
+    $node->revision = TRUE;
+    $node->uid = $user->uid; //TODO: do we want these settings?
+  }
 }
 
 /**
- * Implementation of hook_insert().
+ * Implementation of hook_form() for a book
  */
-function book_insert($node) {
-  db_query("INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->vid, $node->parent, $node->weight);
-}
+function book_form(&$node) {
 
-/**
- * Implementation of hook_update().
- */
-function book_update($node) {
-  if ($node->revision) {
-    db_query("INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->vid, $node->parent, $node->weight);
-  }
-  else {
-    db_query("UPDATE {book} SET parent = %d, weight = %d WHERE vid = %d", $node->parent, $node->weight, $node->vid);
-  }
-}
+  $form['title'] = array('#type' => 'textfield',
+    '#title' => t('Title'),
+    '#required' => TRUE,
+    '#default_value' => $node->title,
+    '#weight' => -5,
+    '#description' => t('Title of the whole book.'),
+  );
+  $form['body_filter']['body'] = array('#type' => 'textarea',
+    '#title' => t('Body'),
+    '#default_value' => $node->body,
+    '#rows' => 20,
+    '#required' => TRUE,
+    '#description' => t('The content of book cover.'),
+  );
+  $form['body_filter']['format'] = filter_form($node->format);
 
-/**
- * Implementation of hook_delete().
- */
-function book_delete(&$node) {
-  db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+  return $form;
 }
 
-/**
- * Implementation of hook_submit().
- */
-function book_submit(&$node) {
-  global $user;
-  // Set default values for non-administrators.
-  if (!user_access('administer nodes')) {
-    $node->revision = 1;
-    $book->uid = $user->uid;
-    $book->name = $user->uid ? $user->name : '';
-  }
-}
 
 /**
- * Implementation of hook_form().
+ * Implementation of hook_form() for a book page.
  */
-function book_form(&$node) {
+function book_page_form(&$node) {
+
   $type = node_get_types('type', $node);
-  if ($node->nid && !$node->parent && !user_access('create new books')) {
-    $form['parent'] = array('#type' => 'value', '#value' => $node->parent);
-  }
-  else {
-    $form['parent'] = array('#type' => 'select',
-      '#title' => t('Parent'),
-      '#default_value' => ($node->parent ? $node->parent : arg(4)),
-      '#options' => book_toc($node->nid),
-      '#weight' => -4,
-      '#description' => user_access('create new books') ? t('The parent section in which to place this page. Note that each page whose parent is &lt;top-level&gt; is an independent, top-level book.') : t('The parent that this page belongs in.'),
-    );
-  }
 
   $form['title'] = array('#type' => 'textfield',
     '#title' => check_plain($type->title_label),
@@ -258,128 +288,322 @@ function book_form(&$node) {
   );
   $form['body_filter']['format'] = filter_form($node->format);
 
+  return $form;
+}
+
+/**
+ * Helper function: generate a form for setting the parent, log message, and weight.
+ */
+function _book_parent_and_log_form($node, &$form) {
+
+  if ($node->book_id != 0 && array_key_exists($node->book_id, $all_books = _list_books())) {
+    $form_parent_title = t('Position in the book %book', array('%book' => $all_books[$node->book_id]));
+  }
+  else {
+    $node->book_id = 0;
+    $form_parent_title = t('Parent');
+  }
+  
+  $form['parent'] = array(
+    '#type' => 'select',
+    '#title' => $form_parent_title,
+    '#default_value' => $node->parent,
+    '#options' => select_book_page_parent($node->nid, $node->book_id),
+    '#weight' => -4,
+    '#description' => t('The parent that this page belongs under. "Top level" means the highest level within this book.'),
+  );
+  
   $form['log'] = array(
     '#type' => 'textarea',
     '#title' => t('Log message'),
+    '#rows' => 2,
     '#weight' => 5,
     '#description' => t('An explanation of the additions or updates being made to help other authors understand your motivations.'),
   );
 
-  if (user_access('administer nodes')) {
-    $form['weight'] = array('#type' => 'weight',
-      '#title' => t('Weight'),
-      '#default_value' => $node->weight,
+  if (user_access('outline posts in books')) {
+    $form['weight'] = array(
+      '#type' => 'weight',
+      '#title' => t('Book outline weight'),
+      '#default_value' => (isset($node->weight) ? $node->weight : 0),
       '#delta' => 15,
-      '#weight' => 5,
+      '#weight' => 6,
       '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
-    );
+    );  
   }
   else {
-    // If a regular user updates a book page, we preserve the node weight; otherwise
+   // If a regular user updates a book page, we preserve the node weight; otherwise
     // we use 0 as the default for new pages
     $form['weight'] = array(
-      '#type' => 'value',
-      '#value' => isset($node->weight) ? $node->weight : 0,
-    );
+      '#type' => 'value', 
+      '#value' => (isset($node->weight) ? $node->weight : 0),
+    ); 
   }
+}
 
-  return $form;
+/**
+ * Helper function: return an array of available books as (book_id => title).
+ */
+function _list_books(){
+  static $books = NULL;
+  
+  if (empty($books)) {
+    $result = db_query(db_rewrite_sql('SELECT b.nid, n.title FROM {book} b JOIN {node} n ON n.vid = b.vid ORDER BY b.weight ASC, n.title ASC'));
+    $books = array();
+    $books[0] = t('Independent, top-level book page');
+    while ($book = db_fetch_object($result)) {
+      $books[$book->nid] = $book->title;
+    }
+  } 
+  return $books;   
+}
+ 
+/**
+ * Helper function: generate a select form listing available books.
+ */
+function _book_select_form($default_book_id = 0, $nid, $note = NULL){
+
+  $books = _list_books();
+
+  $form = array();
+  $form['book_id'] = array(
+    '#type' => 'select',
+    '#title' => t('Select a book'),
+    '#default_value' => $default_book_id,
+    '#options' => $books,
+    '#description' => t('Select the book you wish to add/move your page to.'),
+    '#weight' => 50,
+  ); 
+  $form['nid'] = array(
+    '#type' => 'value',
+    '#value' => $nid,
+  );
+  if ($note) {
+    $form['note'] = array(
+      '#value' => '<p>'. $note. '</p>',
+      '#weight' => 52,
+    );
+  }
+  return $form; 
 }
 
 /**
- * Implementation of function book_outline()
- * Handles all book outline operations.
+ * 
  */
-function book_outline($nid) {
-  $node = node_load($nid);
-  $page = book_load($node);
+function book_admin_settings() {  
 
-  $form['parent'] = array('#type' => 'select',
-    '#title' => t('Parent'),
-    '#default_value' => $page->parent,
-    '#options' => book_toc($node->nid),
-    '#description' => t('The parent page in the book.'),
-  );
-  $form['weight'] = array('#type' => 'weight',
-    '#title' => t('Weight'),
-    '#default_value' => $page->weight,
-    '#delta' => 15,
-    '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
+  $types = node_get_types();
+  $form['types'] = array(
+    '#type' => 'fieldset',
+    '#tree' => TRUE,
+    '#description' => t('Important: deselecting a currently selected type will cause all child pages to become indepndent book pages'),
   );
-  $form['log'] = array('#type' => 'textarea',
-    '#title' => t('Log message'),
-    '#description' => t('An explanation to help other authors understand your motivations to put this post into the book.'),
+  $current_types = variable_get('book_node_types', array('book'));
+  foreach ($types as $nt) {
+   $form['types'][$nt->type] = array(
+    '#type' => 'checkbox', 
+    '#title' => $nt->name,
+    '#default_value' => in_array($nt->type, $current_types),
+  );
+    $options[$nt->type] = $nt->name;    
+  }
+  $form['types']['book']['#disabled'] = TRUE;
+  $form['types']['book']['#value'] = TRUE;
+  $form['types']['book_page']['#disabled'] = TRUE;
+
+  $form['types']['#title'] = t('Select node types that will be books.  The %book type is always selected, and the %book_page type may not be selected.',array ('%book' => $options['book']));
+  $form['previous_types'] = array(
+    '#type' => 'value',
+    '#value' => $current_types,
+   );
+  
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Select book types'),
+    '#weight' => 65,
   );
+  return $form;
+}
 
-  $form['nid'] = array('#type' => 'value', '#value' => $nid);
-  if ($page->nid) {
-    $form['update'] = array('#type' => 'submit',
+function book_admin_settings_submit($form_id, $form_values) {
+ 
+  $types = array();
+  foreach ($form_values['types'] as $key => $value) {
+    if ($value) {
+      $types[] = $key;
+    }
+  }
+  variable_set('book_node_types',$types);
+  $prev_types = $form_values['previous_types'];
+  foreach ($types as $nt) {
+    if (!in_array($nt, $prev_types)) {
+      //TODO 
+      drupal_set_message($nt.' is no longer a book type');
+    }
+  }
+  return 'admin/content/book';
+}
+
+/**
+ * Menu call back: handle all book outline operations on individual nodes.
+ */
+function book_outline_form($nid){
+  
+  $node = node_load($nid);
+  $book_types = variable_get('book_node_types', array('book'));
+  if (in_array($node->type, $book_types)) {
+    return array(); 
+  }
+  
+  if (isset($node->book_id)) { // node is already part of the book outline
+    
+    $form = array();
+    _book_parent_and_log_form($node, $form);        
+
+    $form['outline_heading'] = array(
+      '#value' => '<h2>'. t('Update book outline').'</h2>',
+      '#weight' => -10,
+    );
+    $form['update'] = array(
+      '#type' => 'submit',
       '#value' => t('Update book outline'),
+      '#weight' => 10,
     );
-    $form['remove'] = array('#type' => 'submit',
-      '#value' => t('Remove from book outline'),
+    $form['move_page'] = array(
+      '#value' => '<h2 class="book-outline">'. t('Move this post to a different book.'). '</h2>',
+      '#weight' => 40,
+    );
+    $children_note = t("Note: All of this pages's children will be moved together to the new book. If you do not wish that, please update the outline of the child pages first.");
+    $form = array_merge($form,_book_select_form($node->book_id, $node->nid, $children_note));
+    $form['select'] = array(
+      '#type' => 'submit',
+      '#value' => t('Select book'),
+      '#weight' => 55,
     );
+    $form['may_remove'] = array(
+      '#value' => '<h2 class="book-outline">'. t('Remove this post from the book outline.'). '</h2>'. '<p>'. t('Child pages (if any) will be orphaned; you should move them first.'). '</p>',
+      '#weight' => 60,
+    );
+    //TODO: links to child pages
+    $form['remove'] = array(
+      '#type' => 'submit',
+      '#value' => t('Remove from book outline'),
+      '#weight' => 65,
+    );     
   }
   else {
-    $form['add'] = array('#type' => 'submit', '#value' => t('Add to book outline'));
+    $form = _book_select_form(0, $node->nid);
+    $form['add_note'] = array(
+      '#value' => '<h2 class="book-outline">'. t('Add this post to the selected book.'). '</h2>',
+      '#weight' => 40,
+    );
+    $form['add'] = array(
+      '#type' => 'submit', 
+      '#value' => t('Add to book outline'),
+      '#weight' => 55,
+    );
   }
-
   drupal_set_title(check_plain($node->title));
+  
   return $form;
 }
 
 /**
- * Handles book outline form submissions.
+ * Recursivly update each child page when moving a node to a different book.
+ * 
+ * @param $parent 
+ *   the nid of the parent that is being moved.
+ * @param $book_id 
+ *   the book_id (book ID) of the book the parent is moving to.
+ * @param $children 
+ *   the book hierarchy of the book that the node with nid==$parent is moving
+ *   from, as generated by function book_page_tree.
+ */
+function book_update_children_book_id($parent, $book_id, &$children) { 
+
+  if (isset($children[$parent])) {
+    foreach($children[$parent] as $child) {
+      book_update_children_book_id($child->nid, $book_id, $children);
+      db_query("UPDATE {book_pages} SET book_id = %d WHERE nid = %d", $book_id, $child->nid);
+    }
+  }
+} 
+
+/**
+ * Handle book outline form submissions.
  */
-function book_outline_submit($form_id, $form_values) {
+function book_outline_form_submit($form_id, $form_values) {
   $op = $_POST['op'];
   $node = node_load($form_values['nid']);
 
   switch ($op) {
     case t('Add to book outline'):
-      db_query('INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)', $node->nid, $node->vid, $form_values['parent'], $form_values['weight']);
-      db_query("UPDATE {node_revisions} SET log = '%s' WHERE vid = %d", $form_values['log'], $node->vid);
-      drupal_set_message(t('The post has been added to the book.'));
+      db_query('INSERT INTO {book_pages} (nid, book_id, parent, weight) VALUES (%d, %d, %d, %d)', $node->nid, $form_values['book_id'], $form_values['book_id'], $form_values['weight']);
+      drupal_set_message(t('The post has been added to the book.').'<br/>'.t('You can now update where in the book you want to locate the post.'));
+      cache_clear_all();
+      return 'node/'. $node->nid. '/outline';
       break;
     case t('Update book outline'):
-      db_query('UPDATE {book} SET parent = %d, weight = %d WHERE vid = %d', $form_values['parent'], $form_values['weight'], $node->vid);
+      db_query('UPDATE {book_pages} SET parent = %d, weight = %d WHERE nid = %d', $form_values['parent'], $form_values['weight'], $node->nid);
       db_query("UPDATE {node_revisions} SET log = '%s' WHERE vid = %d", $form_values['log'], $node->vid);
       drupal_set_message(t('The book outline has been updated.'));
+      cache_clear_all();
       break;
     case t('Remove from book outline'):
-      db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
-      drupal_set_message(t('The post has been removed from the book.'));
+      db_query('DELETE FROM {book_pages} WHERE nid = %d', $node->nid);
+      db_query("UPDATE {node_revisions} SET log = '%s' WHERE vid = %d", $form_values['log'], $node->vid);
+      drupal_set_message(t('The post has been removed from the book. Child pages may have been orphaned.'));
+      cache_clear_all();
+      break;
+    case t('Select book'):
+      if ($form_values['book_id']  != $node->book_id) {
+        book_update_children_book_id($node->nid, $form_values['book_id'], book_page_tree($node->book_id));
+        db_query('UPDATE {book_pages} SET book_id = %d, parent = %d, weight = 0 WHERE nid = %d', $form_values['book_id'], $form_values['book_id'], $node->nid);
+        drupal_set_message(t('The post and its children have been relocated to the choosen book.').'<br/>'.t('You can now update where in the book you want to locate the post.'));
+        cache_clear_all();
+        return 'node/'. $node->nid. '/outline';
+      }
+      else {
+        drupal_set_message(t('You selected the book that this post already belongs to. No changes were made.')); 
+      }
       break;
   }
   return "node/$node->nid";
 }
 
+
 /**
- * Given a node, this function returns an array of 'book node' objects
- * representing the path in the book tree from the root to the
- * parent of the given node.
- *
- * @param node - a book node object for which to compute the path
- *
- * @return - an array of book node objects representing the path of
- * nodes root to parent of the given node. Returns an empty array if
- * the node does not exist or is not part of a book hierarchy.
- *
- */
-function book_location($node, $nodes = array()) {
-  $parent = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), $node->parent));
-  if (isset($parent->title)) {
-    $nodes = book_location($parent, $nodes);
-    $nodes[] = $parent;
+ * Determine the path in the book tree from the top to the parent of the node.
+ *
+ * @param node 
+ *   a book node object for which to compute the path
+ * @return 
+ *   an array of book node objects representing the path of nodes from the
+ *   top of the book to the parent of the given node. Returns an empty array if
+ *   the node does not exist or is not part of a book hierarchy.
+ *
+ */
+function book_location($node) {
+  
+  $nodes = array();
+  
+  $pages = pages_of_book_by_nid($node->book_id);
+  if (isset($pages[$node->parent])) {
+    $nodes[0]= $pages[$node->parent];
+    $i = 0;
+    while ($nodes[$i]->parent) {
+      $nodes[] = $pages[$nodes[$i++]->parent];
+    }
   }
-  return $nodes;
+  
+  return array_reverse($nodes);
 }
 
 /**
  * Accumulates the nodes up to the root of the book from the given node in the $nodes array.
  */
 function book_location_down($node, $nodes = array()) {
-  $last_direct_child = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND b.parent = %d ORDER BY b.weight DESC, n.title DESC'), $node->nid));
+  $last_direct_child = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.parent, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.status = 1 AND bp.parent = %d ORDER BY bp.weight DESC, n.title DESC'), $node->nid));
   if ($last_direct_child) {
     $nodes[] = $last_direct_child;
     $nodes = book_location_down($last_direct_child, $nodes);
@@ -395,9 +619,11 @@ function book_prev($node) {
   if ($node->parent == 0) {
     return NULL;
   }
+  
+  //$children = book_page_tree($node->book_id); TODO- use this instead
 
   // Previous on the same level:
-  $direct_above = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 AND (b.weight < %d OR (b.weight = %d AND n.title < '%s')) ORDER BY b.weight DESC, n.title DESC"), $node->parent, $node->weight, $node->weight, $node->title));
+  $direct_above = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE bp.parent = %d AND n.status = 1 AND (bp.weight < %d OR (bp.weight = %d AND n.title < '%s')) ORDER BY bp.weight DESC, n.title DESC"), $node->parent, $node->weight, $node->weight, $node->title));
   if ($direct_above) {
     // Get last leaf of $above.
     $path = book_location_down($direct_above);
@@ -406,7 +632,7 @@ function book_prev($node) {
   }
   else {
     // Direct parent:
-    $prev = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d AND n.status = 1'), $node->parent));
+    $prev = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.nid = %d AND n.status = 1'), $node->parent));
     return $prev;
   }
 }
@@ -416,17 +642,17 @@ function book_prev($node) {
  */
 function book_next($node) {
   // get first direct child
-  $child = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 ORDER BY b.weight ASC, n.title ASC'), $node->nid));
-  if ($child) {
-    return $child;
+  $children = book_page_tree($node->book_id);  //= db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE bp.parent = %d AND n.status = 1 ORDER BY bp.weight ASC, n.title ASC'), $node->nid));
+  if (isset($children[$node->nid][0])) {
+    return $children[$node->nid][0];
   }
 
   // No direct child: get next for this level or any parent in this book.
-  $path = book_location($node); // Path to top-level node including this one.
+  $path = book_location($node); // Path to top-level node including this one's parent.
   $path[] = $node;
 
   while (($leaf = array_pop($path)) && count($path)) {
-    $next = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC"), $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
+    $next = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE bp.parent = %d AND n.status = 1 AND (bp.weight > %d OR (bp.weight = %d AND n.title > '%s')) ORDER BY bp.weight ASC, n.title ASC"), $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
     if ($next) {
       return $next;
     }
@@ -434,14 +660,30 @@ function book_next($node) {
 }
 
 /**
- * Returns the content of a given node. If $teaser if TRUE, returns
- * the teaser rather than full content. Displays the most recently
- * approved revision of a node (if any) unless we have to display this
- * page in the context of the moderation queue.
- */
-function book_content($node, $teaser = FALSE) {
-  // Return the page body.
-  return node_prepare($node, $teaser);
+* Implementation of hook_view() for a book cover.
+*/
+function book_view(&$node, $teaser = FALSE, $page = FALSE) {
+  $node = node_prepare($node, $teaser);
+
+  if (!$teaser) {
+  $node->content['book_toc'] = array(
+      '#value' => theme('book_toc', $node),
+      '#weight' => 200,
+    );
+  }
+  return $node;
+}
+
+/**
+ * Create formatted html for the table of contents displayed on book $node.
+ *
+ * @ingroup themeable 
+ */
+function theme_book_toc($node) {
+  $toc = '<div class="book-toc"><h3>' . t('Table of contents') . '</h3>';
+  $toc .= book_page_menu_tree($node->book_id, $node->nid, $node->toc_depth);
+  $toc .= '</div>';
+  return $toc;
 }
 
 /**
@@ -450,39 +692,79 @@ function book_content($node, $teaser = F
  * Appends book navigation to all nodes in the book.
  */
 function book_nodeapi(&$node, $op, $teaser, $page) {
+  $book_types = variable_get('book_node_types', array('book'));
+  
   switch ($op) {
+    case 'load': //all types handled here including book_page and book
+      $page_load = db_fetch_array(db_query('SELECT * FROM {book_pages} WHERE nid = %d', $node->nid));
+      if (in_array($node->type, $book_types)) {
+        $book_load = db_fetch_array(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
+        $page_load = array_merge($page_load, $book_load);
+      }
+      return $page_load;
+      break;
     case 'view':
       if (!$teaser) {
-        $book = db_fetch_array(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
-        if ($book) {
-          foreach ($book as $key => $value) {
-            $node->$key = $value;
-          }
-
+        // check if it is a node in the book outline:
+        if (isset($node->book_id)) {
           $path = book_location($node);
           // Construct the breadcrumb:
           $node->breadcrumb = array(); // Overwrite the trail with a book trail.
+          $node->breadcrumb[] = array ('path' => 'book', 'title' => t('books'));
+
           foreach ($path as $level) {
             $node->breadcrumb[] = array('path' => 'node/'. $level->nid, 'title' =>  $level->title);
           }
           $node->breadcrumb[] = array('path' => 'node/'. $node->nid);
-
-          $node->content['book_navigation'] = array(
-            '#value' => theme('book_navigation', $node),
-            '#weight' => 100,
-          );
-
-          if ($page) {
-            menu_set_location($node->breadcrumb);
+          menu_set_location($node->breadcrumb);
+          
+          if (($page) && (!in_array($node->type, $book_types))) {
+            $node->content['book_navigation'] = array(
+              '#value' => theme('book_page_navigation', $node),
+              '#weight' => 100,
+            );
           }
         }
       }
+      return $node;
+      break;
+    case 'update':
+      if (in_array($node->type, $book_types)) {
+        if ($node->revision) {
+          db_query('INSERT INTO {book} (nid, vid, child_type, weight, toc_depth) VALUES (%d, %d, "%s", %d, %d)', $node->nid, $node->vid, $node->child_type, $node->weight, $node->toc_depth);
+        }
+        else {
+          db_query('UPDATE {book} SET child_type = "%s", weight = %d, toc_depth = %d WHERE vid = %d', $node->child_type, $node->weight, $node->toc_depth, $node->vid);
+        }
+        $node->book_id = $node->nid;
+        $node->parent = 0;
+      }
+      if (isset($node->book_id) && isset($node->parent)) {
+        db_query("UPDATE {book_pages} SET book_id = %d, parent = %d, weight = %d WHERE nid = %d", $node->book_id, $node->parent, $node->weight, $node->nid);  
+      }
+      break;
+    case 'insert':
+      if (in_array($node->type, $book_types)) {
+        db_query('INSERT INTO {book} (nid, vid, child_type, weight, toc_depth) VALUES (%d, %d, "%s", %d, %d)', $node->nid, $node->vid, $node->child_type, $node->weight, $node->toc_depth);
+        $node->book_id = $node->nid;
+        $node->parent = 0;
+      }
+      if (isset($node->book_id) && isset($node->parent)) {
+        db_query("INSERT INTO {book_pages} (nid, book_id, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->book_id, $node->parent, $node->weight);
+      }
       break;
     case 'delete revision':
-      db_query('DELETE FROM {book} WHERE vid = %d', $node->vid);
+      if (in_array($node->type, $book_types)) {
+        db_query('DELETE FROM {book} WHERE vid = %d', $node->vid);
+      }
       break;
-    case 'delete':
-      db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+    case 'delete': //all types handled here including book_page and book
+      db_query('DELETE FROM {book_pages} WHERE nid = %d', $node->nid);
+      if (in_array($node->type, $book_types)) {
+        db_query('UPDATE {book_pages} SET book_id = 0 WHERE book_id = %d', $node->nid);
+        db_query('UPDATE {book_pages} SET parent = 0 WHERE parent = %d', $node->nid);
+        db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);        
+      }
       break;
   }
 }
@@ -493,20 +775,25 @@ function book_nodeapi(&$node, $op, $teas
  *
  * @ingroup themeable
  */
-function theme_book_navigation($node) {
+function theme_book_page_navigation($node) {
   $output = '';
   $links = '';
 
   if ($node->nid) {
-    $tree = book_tree($node->nid);
+    $tree = book_page_menu_tree($node->book_id, $node->nid, 1);
 
     if ($prev = book_prev($node)) {
       drupal_add_link(array('rel' => 'prev', 'href' => url('node/'. $prev->nid)));
       $links .= l(t('‹ ') . $prev->title, 'node/'. $prev->nid, array('class' => 'page-previous', 'title' => t('Go to previous page')));
     }
-    if ($node->parent) {
+    if ($node->parent != 0) {
       drupal_add_link(array('rel' => 'up', 'href' => url('node/'. $node->parent)));
-      $links .= l(t('up'), 'node/'. $node->parent, array('class' => 'page-up', 'title' => t('Go to parent page')));
+      if ($node->parent != $node->book_id){
+        $links .= l(t('up'), 'node/'. $node->parent, array('class' => 'page-up', 'title' => t('Go to parent page')));
+      }
+      else {
+        $links .= l(t('up'), 'node/'. $node->book_id, array('class' => 'page-up', 'title' => t('Go to book cover')));
+      }
     }
     if ($next = book_next($node)) {
       drupal_add_link(array('rel' => 'next', 'href' => url('node/'. $next->nid)));
@@ -529,74 +816,123 @@ function theme_book_navigation($node) {
 }
 
 /**
- * This is a helper function for book_toc().
+ * Returns an array of titles and nid entries of book pages where the array keys are the nid values
  */
-function book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
+function pages_of_book_by_nid($book_id) {
+ static $bynid = array();
+ 
+ if (!isset($bynid[$book_id])){
+   $pages= pages_of_book($book_id);
+   foreach ($pages as $node) {
+     $bynid[$book_id][$node->nid] = $node;
+   }
+ }
+ return $bynid[$book_id];
+}
+   
+/**
+ * Returns an array of titles and nid entries of book pages in table of contents order
+ */
+function pages_of_book($book_id) {
+ static $book = array();
+ 
+ if (!isset($book[$book_id])){
+   $book[$book_id] = array();
+   $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.parent, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.status = 1 AND bp.book_id = %d ORDER BY bp.weight ASC, n.title ASC'), $book_id);
+
+   while ($node = db_fetch_object($result)) {
+     $book[$book_id][] = $node;
+   }
+ }
+ return $book[$book_id];
+}
+
+/**
+ * Returns an array corresponding to the tree of titles and nid entries of book pages in table of contents order
+ */
+function book_page_tree($book_id){
+  static $children = array();
+  
+  if (!isset($children[$book_id])) {
+    $pages=pages_of_book($book_id);
+    $children[$book_id] = array();
+    foreach ($pages as $node) {
+      if (!$children[$book_id][$node->parent]) {
+        $children[$book_id][$node->parent] = array();
+      }
+      $children[$book_id][$node->parent][] = $node;
+    }
+  }
+  return $children[$book_id];
+}
+
+/**
+ * This is a helper function for select_book_page_parent
+ */
+function _book_toc_recurse($nid, $indent, $toc, &$children, $exclude) {
   if ($children[$nid]) {
-    foreach ($children[$nid] as $foo => $node) {
+    foreach ($children[$nid] as $node) {
       if (!$exclude || $exclude != $node->nid) {
         $toc[$node->nid] = $indent .' '. $node->title;
-        $toc = book_toc_recurse($node->nid, $indent .'--', $toc, $children, $exclude);
+        $toc = _book_toc_recurse($node->nid, $indent .'--', $toc, $children, $exclude);
       }
     }
   }
-
   return $toc;
 }
 
 /**
- * Returns an array of titles and nid entries of book pages in table of contents order.
+ * Returns an array of titles and nid entries of book pages in table of contents order
+ * for use in a form select.
  */
-function book_toc($exclude = 0) {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 ORDER BY b.weight, n.title'));
-
-  $children = array();
-  while ($node = db_fetch_object($result)) {
-    if (!$children[$node->parent]) {
-      $children[$node->parent] = array();
-    }
-    $children[$node->parent][] = $node;
-  }
-
+function select_book_page_parent($exclude = 0,  $book_id) {
+  
+  $children = book_page_tree($book_id);
   $toc = array();
-  // If the user has permission to create new books, add the top-level book page to the menu;
-  if (user_access('create new books')) {
-    $toc[0] = '<'. t('top-level') .'>';
-  }
+  $toc[$book_id] = '<'. t('top-level') .'>';
 
-  $toc = book_toc_recurse(0, '', $toc, $children, $exclude);
+  $toc = _book_toc_recurse($book_id, '', $toc, $children, $exclude);
 
   return $toc;
 }
 
 /**
- * This is a helper function for book_tree()
+ * This is a default theme display function for book_tree()
+ *
+ * @ingroup themeable
  */
-function book_tree_recurse($nid, $depth, $children, $unfold = array()) {
+function theme_book_tree_display($nid, $depth, $children, $unfold = NULL) {
   $output = '';
   if ($depth > 0) {
     if (isset($children[$nid])) {
-      foreach ($children[$nid] as $foo => $node) {
-        if (in_array($node->nid, $unfold)) {
-          if ($tree = book_tree_recurse($node->nid, $depth - 1, $children, $unfold)) {
-            $output .= '<li class="expanded">';
-            $output .= l($node->title, 'node/'. $node->nid);
-            $output .= '<ul class="menu">'. $tree .'</ul>';
-            $output .= '</li>';
+      $output .= '<ul class="menu">';
+      foreach ($children[$nid] as $node) {
+        if (isset($children[$node->nid])) {
+          if (empty($unfold)){
+             if (depth == 1) {
+            $output .= '<li class="collapsed">'. l($node->title, 'node/'. $node->nid);
+            }
+            else {
+              $output .= '<li class="expanded">' . l($node->title, 'node/'. $node->nid);
+              $output .= theme_book_tree_display($node->nid, $depth - 1, $children, $unfold);            
+            }
           }
           else {
-            $output .= '<li class="leaf">'. l($node->title, 'node/'. $node->nid) .'</li>';
+            if (depth == 1 || !in_array($node->nid, $unfold)) {
+              $output .= '<li class="collapsed">'. l($node->title, 'node/'. $node->nid);
+            }
+            else {
+              $output .= '<li class="expanded">' . l($node->title, 'node/'. $node->nid);
+              $output .= theme_book_tree_display($node->nid, $depth - 1, $children, $unfold);
+            }
           }
         }
         else {
-          if ($tree = book_tree_recurse($node->nid, 1, $children)) {
-            $output .= '<li class="collapsed">'. l($node->title, 'node/'. $node->nid) .'</li>';
-          }
-          else {
-            $output .= '<li class="leaf">'. l($node->title, 'node/'. $node->nid) .'</li>';
-          }
+          $output .= '<li class="leaf">'. l($node->title, 'node/'. $node->nid);
         }
+        $output .= '</li>';
       }
+      $output .= '</ul>';
     }
   }
 
@@ -604,35 +940,53 @@ function book_tree_recurse($nid, $depth,
 }
 
 /**
- * Returns an HTML nested list (wrapped in a menu-class div) representing the book nodes
+ * Returns an themed list representing the book nodes
  * as a tree.
  */
-function book_tree($parent = 0, $depth = 3, $unfold = array()) {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 ORDER BY b.weight, n.title'));
-
-  while ($node = db_fetch_object($result)) {
-    $list = isset($children[$node->parent]) ? $children[$node->parent] : array();
-    $list[] = $node;
-    $children[$node->parent] = $list;
-  }
-
-  if ($tree = book_tree_recurse($parent, $depth, $children, $unfold)) {
-    return '<ul class="menu">'. $tree .'</ul>';
-  }
+function book_page_menu_tree($book_id, $parent = 0, $depth = 1, $unfold = array()) {
+  
+  $children = book_page_tree($book_id);
+  return theme('book_tree_display',$parent, $depth, $children, $unfold);
 }
 
 /**
  * Menu callback; prints a listing of all books.
  */
-function book_render() {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = 0 AND n.status = 1 ORDER BY b.weight, n.title'));
+function book_shelf() {
 
-  $books = array();
+  $breadcrumb = array (l( t('Home'),''));
+  drupal_set_breadcrumb($breadcrumb);
+
+  $result = db_query(db_rewrite_sql('SELECT bp.*, n.title FROM {book_pages} bp INNER JOIN {node} n ON n.nid = bp.nid WHERE bp.parent = 0 ORDER BY bp.weight ASC, n.title ASC'));
+  $all_books = array();
+  $all_independent = array();
   while ($node = db_fetch_object($result)) {
-    $books[] = l($node->title, 'node/'. $node->nid);
+    if ($node->book_id == $node->nid) {
+      $all_books[$node->nid] = $node->title;
+    }
+    else {
+      $all_independent[$node->nid] = $node->title;
+    }
+  }
+  $output = '';
+  $books = array();
+  foreach ($all_books as $nid => $title) {
+    $books[] = l($title, 'node/'. $nid);
+  }
+  if (count($books)) {
+      $output .= theme('item_list', $books, t('books'));
+  }
+ 
+  // Add to those the top-level book pages without a book_cover.
+  $books = array();
+  foreach ($all_independent as $nid => $title) {
+    $books[] = l($title, 'node/'. $nid);
+  }
+  if (count($books)) {
+    $output .= theme('item_list', $books, t('Independent top level book pages'));
   }
 
-  return theme('item_list', $books);
+  return $output;
 }
 
 /**
@@ -655,7 +1009,7 @@ function book_render() {
  */
 function book_export($type = 'html', $nid = 0) {
   $type = drupal_strtolower($type);
-  $node_result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), $nid);
+  $node_result = db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.parent, bp.book_id FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.nid = %d'), $nid);
   if (db_num_rows($node_result) > 0) {
       $node = db_fetch_object($node_result);
   }
@@ -727,7 +1081,9 @@ function theme_book_export_html($title, 
 }
 
 /**
- * Traverses the book tree. Applies the $visit_pre() callback to each
+ * Traverse the book tree and apply functions to each node. 
+ * 
+ * Applies the $visit_pre() callback to each
  * node, is called recursively for each child of the node (in weight,
  * title order). Finally appends the output of the $visit_post()
  * callback to the output before returning the generated output.
@@ -745,7 +1101,7 @@ function theme_book_export_html($title, 
  *  - the output generated in visiting each node
  */
 function book_recurse($nid = 0, $depth = 1, $visit_pre, $visit_post) {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND n.nid = %d ORDER BY b.weight, n.title'), $nid);
+  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.status = 1 AND n.nid = %d ORDER BY bp.weight ASC, n.title ASC'), $nid);
   while ($page = db_fetch_object($result)) {
     // Load the node:
     $node = node_load($page->nid);
@@ -758,7 +1114,7 @@ function book_recurse($nid = 0, $depth =
         $output .= book_node_visitor_html_pre($node, $depth, $nid);
       }
 
-      $children = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND b.parent = %d ORDER BY b.weight, n.title'), $node->nid);
+      $children = db_query(db_rewrite_sql('SELECT n.nid, n.title, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.status = 1 AND bp.parent = %d ORDER BY bp.weight ASC, n.title ASC'), $node->nid);
       while ($childpage = db_fetch_object($children)) {
           $childnode = node_load($childpage->nid);
           if ($childnode->nid != $node->nid) {
@@ -795,9 +1151,7 @@ function book_recurse($nid = 0, $depth =
  */
 function book_node_visitor_html_pre($node, $depth, $nid) {
   // Output the content:
-  if (node_hook($node, 'content')) {
-    $node = node_invoke($node, 'content');
-  }
+  $node = node_build_content($node, FALSE, FALSE);
   // Allow modules to change $node->body before viewing.
   node_invoke_nodeapi($node, 'print', $node->body, FALSE);
 
@@ -824,9 +1178,19 @@ function _book_admin_table($nodes = arra
     '#theme' => 'book_admin_table',
     '#tree' => TRUE,
   );
-
+  $book_types = variable_get('book_node_types', array('book'));
+  
   foreach ($nodes as $node) {
-    $form = array_merge($form, _book_admin_table_tree($node, 0));
+    if (in_array($node->type, $book_types)) {
+      $result = db_query('SELECT nid FROM {book_pages} WHERE parent = %d AND book_id = %d', $node->book_id, $node->book_id);
+      while ($chapters = db_fetch_object($result)) {
+        $chapter = node_load($chapters->nid);
+        $form = array_merge($form, _book_admin_table_tree($chapter, 0));
+      }
+    }
+    else {
+      $form = array_merge($form, _book_admin_table_tree($node, 0));
+    }
   }
 
   return $form;
@@ -850,16 +1214,20 @@ function _book_admin_table_tree($node, $
     ),
   );
 
-  $children = db_query(db_rewrite_sql('SELECT n.nid, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d ORDER BY b.weight, n.title'), $node->nid);
+  $children = db_query(db_rewrite_sql('SELECT n.nid, bp.weight FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE bp.parent = %d ORDER BY bp.weight ASC, n.title ASC'), $node->nid);
   while ($child = db_fetch_object($children)) {
     $form = array_merge($form, _book_admin_table_tree(node_load($child->nid), $depth + 1));
   }
 
   return $form;
 }
-
+/**
+ * Format the book administration form.
+ *
+ * @ingroup themeable
+ */
 function theme_book_admin_table($form) {
-  $header = array(t('Title'), t('Weight'), array('data' => t('Operations'), 'colspan' => '3'));
+  $header = array(t('Title'), t('Weight'), array('data' => t('Operations'), 'colspan' => '4'));
 
   $rows = array();
   foreach (element_children($form) as $key) {
@@ -870,11 +1238,14 @@ function theme_book_admin_table($form) {
       drupal_render($form[$key]['weight']),
       l(t('view'), 'node/'. $nid),
       l(t('edit'), 'node/'. $nid .'/edit'),
-      l(t('delete'), 'node/'. $nid .'/delete', NULL, 'destination=admin/content/book'. (arg(3) == 'orphan' ? '/orphan' : '') . ($pid != $nid ? '/'.$pid : ''))
+      l(t('delete'), 'node/'. $nid .'/delete', NULL, 'destination=admin/content/book'. (arg(3) == 'orphan' ? '/orphan' : '') . ($pid != $nid ? '/'.$pid : '')),
+      l(t('outline'), 'node/'. $nid .'/outline'),
     );
   }
 
-  return theme('table', $header, $rows);
+  if (count($rows)) {
+    return theme('table', $header, $rows);
+  }
 }
 
 /**
@@ -887,10 +1258,17 @@ function book_admin_edit($nid) {
     $form = array();
 
     $form['table'] = _book_admin_table(array($node));
-    $form['save'] = array(
-      '#type' => 'submit',
-      '#value' => t('Save book pages'),
-    );
+    if (count($form['table'][0]) > 1) {
+      $form['save'] = array(
+        '#type' => 'submit',
+        '#value' => t('Save book pages'),
+      );
+    }
+    else {
+      $form['message'] = array(
+        '#value' => '<p>'. t('There are no child pages for %book', array ('%book' => $node->title)). '</p>',
+      );
+    }
 
     return $form;
   }
@@ -903,7 +1281,7 @@ function book_admin_edit($nid) {
  * Menu callback; displays a listing of all orphaned book pages.
  */
 function book_admin_orphan() {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, n.status, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid'));
+  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, n.status, bp.parent FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid'));
 
   $pages = array();
   while ($page = db_fetch_object($result)) {
@@ -920,12 +1298,12 @@ function book_admin_orphan() {
   }
 
   if (count($orphans)) {
+ 
     $form['table'] = _book_admin_table($orphans);
     $form['save'] = array(
       '#type' => 'submit',
       '#value' => t('Save book pages'),
     );
-
   }
   else {
     $form['error'] = array('#value' => '<p>'. t('There are no orphan pages.') .'</p>');
@@ -963,7 +1341,7 @@ function book_admin_edit_submit($form_id
  */
 function book_admin($nid = 0) {
   if ($nid) {
-    return book_admin_edit($nid);
+    return drupal_get_form('book_admin_edit',$nid);
   }
   else {
     return book_admin_overview();
@@ -974,13 +1352,40 @@ function book_admin($nid = 0) {
  * Returns an administrative overview of all books.
  */
 function book_admin_overview() {
-  $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = 0 ORDER BY b.weight, n.title'));
-  while ($book = db_fetch_object($result)) {
-    $rows[] = array(l($book->title, "node/$book->nid"), l(t('outline'), "admin/content/book/$book->nid"));
-  }
-  $headers = array(t('Book'), t('Operations'));
+  $output = '';
 
-  return theme('table', $headers, $rows);
+  // List all books
+  $result = db_query(db_rewrite_sql('SELECT bp.*, n.title FROM {book_pages} bp INNER JOIN {node} n ON n.nid = bp.nid WHERE bp.parent = 0 ORDER BY bp.weight ASC, n.title ASC'));
+  $all_books = array();
+  $all_independent = array();
+  while ($node = db_fetch_object($result)) {
+    if ($node->book_id == $node->nid) {
+      $all_books[$node->nid] = $node->title;
+    }
+    else {
+      $all_independent[$node->nid] = $node->title;
+    }
+  }
+  $rows = array();
+  foreach ($all_books as $nid => $title) {
+    $rows[] = array(l($title, 'node/'. $nid), l(t('administer'), 'admin/content/book/'. $nid));
+  }
+  if (count($rows)) {
+    $headers = array(t('Book'), t('Operations'));
+    $output .= theme('table', $headers, $rows);
+    $output .= '<br />';
+  }
+  // List all independent top-level book pages.
+  $rows = array();
+  foreach ($all_independent as $nid => $title) {
+    $rows[] = array(l($title, 'node/'. $nid), l(t('administer'), 'admin/content/book/'. $nid));
+  }
+  if (count($rows)) {
+    $headers = array(t('Independent book pages'), t('Operations'));
+    $output .= theme('table', $headers, $rows);
+  }
+  
+  return $output;
 }
 
 /**
@@ -989,23 +1394,26 @@ function book_admin_overview() {
 function book_help($section) {
   switch ($section) {
     case 'admin/help#book':
-      $output = '<p>'. t('The <em>book</em> content type is suited for creating structured, multi-page hypertexts such as site resource guides, manuals, and Frequently Asked Questions (FAQs). It permits a document to have chapters, sections, subsections, etc. Authors with suitable permissions can add pages to a collaborative book,  placing them into the existing document by adding them to a table of contents menu. ') .'</p>';
-      $output .= '<p>'. t('Books have additional <em>previous</em>, <em>up</em>, and <em>next</em> navigation elements at the bottom of each page for moving through the text. Additional navigation may be provided by enabling the <em>book navigation block</em> on the <a href="@admin-block">block administration page</a>.', array('@admin-block' => url('admin/build/block'))) .'</p>';
-      $output .= '<p>'. t('Users can select the <em>printer-friendly version</em> link visible at the bottom of a book page to generate a printer-friendly display of the page and all of its subsections. ') .'</p>';
-      $output .= '<p>'. t('Administrators can view a book outline, from which is it possible to change the titles of sections, and their <i>weight</i> (thus reordering sections). From this outline, it is also possible to edit and/or delete book pages. Many content types besides pages (for example, blog entries, stories, and polls) can be added to a collaborative book by choosing the <em>outline</em> tab when viewing the post.') .'</p>';
+      $output = '<p>'. t("The <em>book</em> module is suited for creating structured, multi-page hypertexts such as site resource guides, manuals, and Frequently Asked Questions (FAQs). It permits a document to have chapters, sections, subsections, etc. This module provides two content types: the 'book and 'book_page' types.  A 'book' node can be thought of as the book's cover and table of contents, while book pages are the organized content associated with a book.");
+      $output .= '<p>'.  t("Users with the 'outline books' permission can also add nodes of any type to a book, placing them into the existing document by adding them to the book outline via the %outline tab. This tab also provides a means for reorganizing the book one page at a time, including associating it with a different book or changing its positon inthe book relative to other pages.", array('%outline' => t('outline'))) .'</p>';
+      $output .= '<p>'. t('Book pages have additional <em>previous</em>, %up, and <em>next</em> navigation elements at the bottom of each page for moving through the text. Additional navigation may be provided by enabling the %navigation block on the <a href="!admin-block">block administration page</a>.', array('%up' => t('up'), '%navigation' => t('Book navigation'),'!admin-block' => url('admin/build/block'))) .'</p>';
+      $output .= '<p>'. t('Users can click the %child-page link visible at the bottom of a book page to add a new page to the current book and automatically position it as a sub-page of the page they are viewing',array('%child-page' => t('add child page'))). '</p>';
+      $output .= '<p>'. t('Select the %printer-friendly link visible at the bottom of a book page to generate a printer-friendly display of the page and all of its subsections. ',array('%printer-friendly' => t('printer-friendly version'))) .'</p>';
+      $output .= '<p>'. t('Administrators can view the book outline, from which is it possible to change the titles of pages, and their <i>weight</i> (thus reordering sections). From this outline, it is also possible to edit and/or delete book pages. Many content types besides pages (for example, blog entries, stories, and polls) can be added to a collaborative book by choosing the <em>outline</em> tab when viewing the post.') .'</p>';
       $output .= t('<p>You can</p>
 <ul>
-<li>create new book pages: <a href="@node-add-book">create content &gt;&gt; book page</a>.</li>
-<li>administer individual books (choose a book from list): <a href="@admin-node-book">administer &gt;&gt; content management &gt;&gt; books</a>.</li>
-<li>set workflow and other global book settings on the book configuration page: <a href="@admin-settings-content-types-book-page" title="book page content type">administer &gt;&gt; content management &gt;&gt; content types &gt;&gt; book page</a>.</li>
-<li>enable the book navigation block: <a href="@admin-block">administer &gt;&gt; site building &gt;&gt; blocks</a>.</li>
-<li>control who can create, edit, and outline posts in books by setting access permissions: <a href="@admin-access">administer &gt;&gt; user management &gt;&gt; access control</a>.</li>
+<li>create new books: <a href="!node-add-book">create content &gt;&gt; book</a>.</li>
+<li>create new book pages that will be added to a previously created book: <a href="!node-add-book-page">create content &gt;&gt; book page</a>.</li>
+<li>administer individual books (choose a book from list): <a href="!admin-content-book">administer &gt;&gt; content management &gt;&gt; books</a>.</li>
+<li>set workflow and other global book settings through the content type configuration pages: <a href="!admin-content-types-book" title="book content type">administer &gt;&gt; content management &gt;&gt; content types &gt;&gt; book</a> and <a href="!admin-content-types-book-page" title="book page content type">administer &gt;&gt; content management &gt;&gt; content types &gt;&gt; book page</a>.</li>
+<li>enable the %navigation block: <a href="!admin-block">administer &gt;&gt; site building &gt;&gt; blocks</a>.</li>
+<li>control who can create, edit, and outline posts in books by setting access permissions: <a href="!admin-access">administer &gt;&gt; user management &gt;&gt; access control</a>.</li>
 </ul>
-', array('@node-add-book' => url('node/add/book'), '@admin-node-book' => url('admin/content/book'), '@admin-settings-content-types-book-page' => url('admin/content/types/book'), '@admin-block' => url('admin/build/block'), '@admin-access' => url('admin/user/access')));
-      $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="@book">Book page</a>.', array('@book' => 'http://drupal.org/handbook/modules/book/')) .'</p>';
+', array('!node-add-book' => url('node/add/book'), '!node-add-book-page' => url('node/add/book-page'), '!admin-content-book' => url('admin/content/book'), '!admin-content-types-book' => url('admin/content/types/book'), '!admin-content-types-book-page' => url('admin/content/types/book-page'), '%navigation' => t('Book navigation'), '!admin-block' => url('admin/build/block'), '!admin-access' => url('admin/user/access')));
+      $output .= '<p>'. t('For more information please read the <a href="!book">book module handbook section</a> on Drupal.org.', array('!book' => 'http://drupal.org/handbook/modules/book/')) .'</p>';
       return $output;
     case 'admin/settings/modules#description':
-      return t('Allows users to collaboratively author a book.');
+      return t('Allows users to create a structured collection of pages - a book.');
     case 'admin/content/book':
       return t('<p>The book module offers a means to organize content, authored by many users, in an online manual, outline or FAQ.</p>');
     case 'admin/content/book/orphan':
@@ -1013,8 +1421,99 @@ function book_help($section) {
   }
 
   if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'outline') {
-    return t('The outline feature allows you to include posts in the <a href="@book">book hierarchy</a>.', array('@book' => url('book')));
+    return t('The outline feature allows you to organize posts in the <a href="!book">book hierarchy</a>.', array('!book' => url('book')));
   }
 }
 
-
+/**
+ * Implementation of hook_form_alter()
+ */
+function book_form_alter($form_id, &$form) {
+  if ($form_id == 'node_delete_confirm') {
+    $node = node_load($form['nid']['#value']);
+    $book_types = variable_get('book_node_types', array('book'));
+    if (in_array($node->type, $book_types)) {
+      $form['book'] = array(
+        '#value' => t('Note that all book pages belonging to this book (if any) will no longer be associated with any book.'),
+      );
+    }
+    else {
+      if (isset($node->book_id)) {
+        $form['book'] = array(
+          '#value' => t('Note that child pages in the book outline (if any) will be orphaned. You may want to move any child pages first.'),
+        );
+      }
+    }
+  }
+  elseif (isset($form['type']) && $form['type']['#value'] .'_node_form' == $form_id) {
+    $node = $form['#node']; 
+    $book_types = variable_get('book_node_types', array('book'));
+    if (in_array($node->type, $book_types)) {
+      $form['weight'] = array(
+        '#type' => 'weight',
+        '#title' => t('Book weight'),
+        '#default_value' => (isset($node->weight) ? $node->weight : 0),
+        '#delta' => 15,
+        '#description' => t('Books are ordered first by weight and then by title.'),
+      ); 
+
+      $types = node_get_types();
+      $book_types = variable_get('book_node_types', array('book'));
+      $options = array();
+      foreach ($types as $nt) {
+        if (!in_array($nt->type,$book_types)) {
+          $options[$nt->type] = $nt->name;
+        }
+      }
+      $form['child_type'] = array(
+         '#type' => 'select',
+        '#title' => t('Default node type for child pages'),
+         '#default_value' => 'book_page',
+         '#options' => $options,
+      ); 
+      $form['toc_depth'] = array(
+        '#type' => 'select',
+        '#title' => t('Preferred depth for table of contents display'),
+        '#default_value' => (($node->toc_depth > 0) ? $node->toc_depth : 5),
+        '#options' => array(
+           1 => '1',
+           2 => '2',
+           3 => '3',
+           4 => '4',
+           5 => '5',
+           6 => '6',
+           7 => '7',
+           8 => '8',
+           9 => '9',
+           10 => '10',
+           15 => '15',
+           20 => '20', ),
+      '#description' => t('The table of contents on the book page will be displayed to this depth (depending upon your theme).'),
+      ); 
+    }
+    else {
+        // looking for url like node/add/book-page?book=$book_id/$parent
+      if ((arg(1) == 'add') && isset($_GET['book'])) { 
+        $book = explode('/', $_GET['book']);
+        if (is_numeric($book[0]) && is_numeric($book[1])){
+          $node->book_id = $book[0]; //needs to be validated below
+          $node->parent = $book[1];
+          if (!array_key_exists($node->book_id, _list_books())) {
+            $node->book_id = 0;
+            $node->parent = 0;
+          }
+        }
+      }
+      //see if node is part of the book outline
+      if (isset($node->book_id) && isset($node->parent)) { 
+   
+        _book_parent_and_log_form($node, $form);
+    
+        $form['book_id'] = array (
+          '#type' => 'value',
+          '#value' => $node->book_id,
+        );
+      }
+    }
+  }
+}
