? modules/book/.book.module.marks
? modules/book/book.module.beginner
Index: modules/book/book.install
===================================================================
RCS file: /cvs/drupal/drupal/modules/book/book.install,v
retrieving revision 1.3
diff -u -p -r1.3 book.install
--- modules/book/book.install	4 Aug 2006 06:58:44 -0000	1.3
+++ modules/book/book.install	19 Aug 2006 23:30:54 -0000
@@ -5,26 +5,86 @@ function book_install() {
   switch ($GLOBALS['db_type']) {
     case 'mysql':
     case 'mysqli':
-      db_query("CREATE TABLE {book} (
-        vid int(10) unsigned NOT NULL default '0',
-        nid int(10) unsigned NOT NULL default '0',
+      db_query("CREATE TABLE {book_pages} (
+        nid int(10) unsigned NOT NULL default '0' PRIMARY KEY,
+        bid int(10) unsigned NOT NULL default '0',
         parent int(10) NOT NULL default '0',
         weight tinyint(3) NOT NULL default '0',
-        PRIMARY KEY (vid),
-        KEY nid (nid),
+        KEY bid (bid),
         KEY parent (parent)
       ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
+      db_query("CREATE TABLE {book} (
+        bid INT( 10 ) UNSIGNED NOT NULL default '0',
+        nid INT( 10 ) UNSIGNED NOT NULL default '0',
+        vid INT(10) unsigned NOT NULL default '0' PRIMARY KEY,
+        book_author VARCHAR(255) NOT NULL default '',
+        book_license LONGTEXT NOT NULL default '',
+        weight TINYINT( 3 ) NOT NULL default '0',
+        KEY bid (bid),
+        KEY nid (nid)
+      ) /*!40100 DEFAULT CHARACTER SET UTF8 */ ");
       break;
     case 'pgsql':
-      db_query("CREATE TABLE {book} (
-        vid uint NOT NULL default '0',
+      db_query("CREATE TABLE {book_pages} (
         nid uint NOT NULL default '0',
+        bid uint NOT NULL default '0',
         parent int NOT NULL default '0',
         weight smallint NOT NULL default '0',
+        PRIMARY KEY (nid)
+      ");
+      db_query("CREATE TABLE {book} (
+        bid uint NOT NULL default '0',
+        nid uint NOT NULL default '0',
+        vid uint NOT NULL default '0',
+        book_author varchar(255) NOT NULL default '',
+        book_license text NOT NULL default '',
+        weight smallint NOT NULL default '',
         PRIMARY KEY (vid)
       )");
+      db_query("CREATE INDEX {book_pages}_xid_idx ON {book_pages} (bid)");
+      db_query("CREATE INDEX {book_pages}_parent_idx ON {book_pages} (parent)");
       db_query("CREATE INDEX {book}_nid_idx ON {book} (nid)");
-      db_query("CREATE INDEX {book}_parent_idx ON {book} (parent)");
+      db_query("CREATE INDEX {book}_bid_idx ON {book} (bid)");
+      break;
+  }
+}
+
+/**
+ * Update book table definitions.
+ */
+function book_update_1000() {
+  $ret = array();
+  return $ret;
+  
+  switch ($GLOBALS['db_type']) {
+    case 'mysql':
+    case 'mysqli':
+      $ret[] = update_sql("ALTER TABLE `{book}` RENAME `{book_pages}`;");
+      $ret[] = update_sql("CREATE TABLE `{book}` (
+        `bid` INT( 10 ) UNSIGNED NOT NULL default '0' PRIMARY KEY ,
+        `nid` INT( 10 ) UNSIGNED NOT NULL default '0' ,
+        `book_author` VARCHAR(255) NOT NULL default '' ,
+        `book_license` LONGTEXT NOT NULL default '' ,
+        `weight` TINYINT( 3 ) NOT NULL default '0',
+        KEY nid (nid)
+        ) TYPE = MYISAM");
+      $ret[] = update_sql("ALTER TABLE `{book_pages}` ADD `bid` INT( 10 ) UNSIGNED NOT NULL AFTER `nid` ;");
+      $ret[] = update_sql("ALTER TABLE `{book_pages}` ADD INDEX ( `bid` );");
+      break;
+    case 'pgsql':
+      $ret[] = update_sql("ALTER TABLE {book} RENAME {book_pages};");
+      $ret[] = update_sql("CREATE TABLE {book} (
+        bid integer NOT NULL default '0' ,
+        nid integer NOT NULL default '0' ,
+        book_author varchar(255) NOT NULL default '' ,
+        book_license text NOT NULL default '' ,
+        weight smallint NOT NULL default '0'
+        ");
+      $ret[] = update_sql("CREATE INDEX {book}_bid_idx ON {book}(bid);");
+      $ret[] = update_sql("CREATE INDEX {book}_uid_idx ON {book}(uid);");
+      db_add_column($ret, 'book_pages', 'bid', 'int', array('not null' => TRUE, 'default' => 0));
+      $ret[] = update_sql("CREATE INDEX {book_pages}_bid_idx ON {book_pages}(bid);");
       break;
   }
+  return $ret;
 }
Index: modules/book/book.module
===================================================================
RCS file: /cvs/drupal/drupal/modules/book/book.module,v
retrieving revision 1.382
diff -u -p -r1.382 book.module
--- modules/book/book.module	14 Aug 2006 07:14:49 -0000	1.382
+++ modules/book/book.module	19 Aug 2006 23:30:55 -0000
@@ -11,11 +11,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- this has a table of contents (for associated book pages), a list of authors, etc. Book pages (and other content) can then be added to this book'),
+    ),
   );
 }
 
@@ -26,25 +31,38 @@ function book_perm() {
     return array('outline posts in books', 'create book pages', 'create new books', 'edit book pages', 'edit own book pages', 'see printer-friendly version');
 }
 
+
 /**
- * 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;
     }
@@ -61,12 +79,22 @@ function book_link($type, $node = NULL, 
 
   $links = array();
 
+  if ($type == 'node' && $node->type == 'book') {
+    if (user_access('create new books', $node)) {
+      $links['book_add_child'] = array(
+        'title' => t('add child page'),
+        'href' => "node/add/book_page/$node->bid/0"
+      );
+    }
+    return $links;
+  }
+
   if ($type == 'node' && isset($node->parent)) {
     if (!$teaser) {
       if (book_access('create', $node)) {
         $links['book_add_child'] = array(
           'title' => t('add child page'),
-          'href' => "node/add/book/parent/$node->nid"
+          'href' => "node/add/book_page/$node->bid/$node->nid"
         );
       }
       if (user_access('see printer-friendly version')) {
@@ -107,10 +135,10 @@ function book_menu($may_cache) {
       'weight' => 8);
     $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',
@@ -122,21 +150,26 @@ 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' => '_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) {
-        $items[] = array(
-          'path' => 'node/'. arg(1) .'/outline',
-          'title' => t('outline'),
-          'callback' => 'book_outline',
-          'callback arguments' => array(arg(1)),
-          'access' => user_access('outline posts in books'),
-          'type' => MENU_LOCAL_TASK,
-          'weight' => 2);
-      }
+      // add outline tab
+      $items[] = array(
+        'path' => 'node/'. arg(1) .'/outline',
+        'title' => t('outline'),
+        'callback' => 'book_outline',
+        'callback arguments' => array(arg(1)),
+        'access' => user_access('outline posts in books'),
+        'type' => MENU_LOCAL_TASK,
+        'weight' => 2);
+    
     }
   }
 
@@ -152,13 +185,31 @@ function book_menu($may_cache) {
 function book_block($op = 'list', $delta = 0) {
   $block = array();
   if ($op == 'list') {
-    $block[0]['info'] = t('Book navigation');
+    $block['navigation']['info'] = t('Book navigation');
+    $block['license']['info'] = t('Book license');
     return $block;
   }
   else if ($op == 'view') {
+    // Book license block
+    // Only display this block when the user is browsing a book page:
+    // (the block will not appear on the book cover. Maybe it should but it's not implemented yet.
+    // being able to call global $node and check on $node->bid would be much more convenient.)
+    if ($delta == 'license') {
+      if (arg(0) == 'node' && is_numeric(arg(1))) {
+        $result = db_query('SELECT b.book_license, n.title, nr.format FROM {book} b JOIN {book_pages} bp ON bp.bid = b.bid INNER JOIN {node} n ON n.vid = b.vid JOIN {node_revisions} nr ON nr.vid = n.vid WHERE bp.nid = %d', arg(1));
+        if (db_num_rows($result) > 0) {
+          $book = db_fetch_object($result);
+          $block['subject'] = t('License for the book %book_title', array('%book_title' => theme('placeholder', check_plain($book->title))));
+          $block['content'] = check_markup($book->book_license, $book->format, FALSE);
+        }
+      }
+      return $block;
+    }
+
+    // Book navigation block
     // Only display this block when the user is browsing a book:
     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));
+      $result = db_query('SELECT n.nid, n.title, bp.parent, bp.bid FROM {node} n INNER JOIN {book_pages} bp ON n.nid = bp.nid WHERE n.nid = %d', arg(1));
       if (db_num_rows($result) > 0) {
         $node = db_fetch_object($result);
 
@@ -169,9 +220,10 @@ function book_block($op = 'list', $delta
         foreach ($path as $key => $node) {
           $expand[] = $node->nid;
         }
+        $children = book_page_tree($node->bid);
 
         $block['subject'] = check_plain($path[0]->title);
-        $block['content'] = book_tree($expand[0], 5, $expand);
+        $block['content'] = book_page_menu_tree($node->bid,0, 5, $expand);
       }
     }
 
@@ -180,68 +232,148 @@ function book_block($op = 'list', $delta
 }
 
 /**
- * Implementation of hook_load().
+ * Implementation of hook_load() for a book cover.
  */
 function book_load($node) {
-  return db_fetch_object(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
+  return db_fetch_array(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
 }
 
+
 /**
- * Implementation of hook_insert().
+ * Implementation of hook_load().
+ */
+function book_page_load($node) {
+  return db_fetch_array(db_query('SELECT * FROM {book_pages} WHERE nid = %d', $node->nid));
+}
+
+/**
+ * Implementation of hook_insert() for book pages.
  */
 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);
+  $bid = db_next_id('book_bid');
+  db_query('INSERT INTO {book} (bid, nid, vid, book_author, book_license, weight) VALUES (%d, %d, %d, "%s", "%s", %d)', $bid, $node->nid, $node->vid, $node->book_author, $node->book_license, $node->weight);
 }
 
 /**
- * Implementation of hook_update().
+ * Implementation of hook_insert() for book pages.
+ */
+function book_page_insert($node) {
+  db_query("INSERT INTO {book_pages} (nid, bid, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->bid, $node->parent, $node->weight);
+}
+
+/**
+ * Implementation of hook_update() for book covers.
  */
 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);
+    db_query('INSERT INTO {book} (bid, nid, vid, book_author, book_license, weight) VALUES (%d, %d, %d, "%s", "%s", %d)', $bid, $node->nid, $node->vid, $node->book_author, $node->book_license, $node->weight);
   }
   else {
-    db_query("UPDATE {book} SET parent = %d, weight = %d WHERE vid = %d", $node->parent, $node->weight, $node->vid);
+    db_query('UPDATE {book} SET book_author = "%s", weight = %d, book_license = "%s" WHERE vid = %d', $node->book_author, $node->weight, $node->book_license, $node->vid);
   }
 }
 
 /**
- * Implementation of hook_delete().
+ * Implementation of hook_update().
+ */
+function book_page_update($node) {
+  db_query("UPDATE {book_pages} SET parent = %d, weight = %d WHERE nid = %d", $node->parent, $node->weight, $node->nid);  
+}
+
+/**
+ * Implementation of hook_delete() for book covers.
  */
 function book_delete(&$node) {
+  db_query('UPDATE {book_pages} SET bid = 0 WHERE bid = %d', $node->bid);
   db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
 }
 
 /**
- * Implementation of hook_submit().
+ * Implementation of hook_delete().for book pages
  */
-function book_submit(&$node) {
+function book_page_delete(&$node) {
+  db_query('DELETE FROM {book_pages} WHERE nid = %d', $node->nid);
+}
+
+/**
+ * Implementation of hook_submit() for book covers.
+ */
+
+/**
+ * Implementation of hook_submit() for book pages.
+ */
+function book_page_submit(&$node) {
   global $user;
   // Set default values for non-administrators.
   if (!user_access('administer nodes')) {
-    $node->weight = 0;
-    $node->revision = 1;
-    $book->uid = $user->uid;
-    $book->name = $user->uid ? $user->name : '';
+    $node->revision = TRUE;
+    $node->uid = $user->uid;
   }
 }
 
 /**
- * Implementation of hook_form().
+ * Implementation of hook_form() for a book.
  */
 function book_form(&$node) {
+
+  $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);
+  $form['book_author'] = array('#type' => 'textfield',
+    '#title' => t('Author'),
+    '#required' => FALSE,
+    '#default_value' => $node->book_author,
+    '#description' => t('The author of all the book pages that will be added to this book. The author can be a single person, or a collective. Leave blank if you do not wish to display the authoring information on the book cover.'),
+  );
+  $form['book_license'] = array('#type' => 'textarea',
+    '#title' => t('License'),
+    '#default_value' => $node->book_license,
+    '#rows' => 8,
+    '#required' => FALSE,
+    '#description' => t('The license of all the book pages within this book. This information can be displayed within a block on each relevant book page. Leave blank if you do not wish to display any license information. The input format is the same as the one selected for the body.'),
+  );
+
+  return $form;
+}
+
+
+/**
+ * Implementation of hook_form() for a book page.
+ */
+function book_page_form(&$node) {
+  
+  // looking for url like node/add/book-page/$bid/$parent
+  if ((arg(1)=='add') && is_numeric(arg(3)) && is_numeric(arg(4))) {
+      $node->bid = arg(3);
+      $node->parent = arg(4);
+  }
+  elseif (arg(2) == 'book-page') {
+    drupal_goto('node/add/book_page/select_book');
+  }
+
+  $form = _book_parent_and_log_form($node);
+  
+  $form['bid'] = array (
+    '#type' => 'value',
+    '#value' => $node->bid,
+  );
+
   $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.'),
-    );
+
+  if (!isset($node->parent)) {
+    $node->parent = 0;
   }
 
   $form['title'] = array('#type' => 'textfield',
@@ -258,69 +390,173 @@ function book_form(&$node) {
   );
   $form['body_filter']['format'] = filter_form($node->format);
 
+  return $form;
+}
+
+function _book_parent_and_log_form($node) {
+  $form=array();
+
+  if (!$result = db_result(db_query('SELECT n.title, n.nid FROM {book} AS b JOIN {node} AS n ON n.nid = b.nid WHERE b.bid = %d', $node->bid))) {
+    $node->bid = 0;
+    $form_parent_title = t('Parent');
+  }
+  else {
+    $form_parent_title = t('Position in the book %book', array('%book' => theme('placeholder', $result)));
+  }
+  
+  $form['parent'] = array(
+    '#type' => 'select',
+    '#title' => $form_parent_title,
+    '#default_value' => $node->parent,
+    '#options' => select_book_page_parent($node->nid, $node->bid),
+    '#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'),
     '#default_value' => $node->log,
+    '#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'),
+  if (user_access('outline posts in books')) {
+    $form['weight'] = array(
+      '#type' => 'weight',
+      '#title' => t('Book outline weight'),
       '#default_value' => $node->weight,
       '#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 create a new revision
-    // authored by that user:
-    $form['revision'] = array('#type' => 'hidden', '#value' => 1);
+  return $form;
+}
+
+
+/**
+ * helper function: generates a select form listing available books
+ * @param:
+ *  $default_bid: the default book in the select form.   0 corresponds to no
+ *  book (an independent top-level book page)
+  * @param
+ *  $nid: the Node ID (nid) of the node being acted upon
+ * @param
+ *  $note: a note to add to the form below the book select
+ */
+function _book_select_form($default_bid = 0, $nid, $note = NULL){
+  $result = db_query(db_rewrite_sql('SELECT b.bid, n.title FROM {book} b JOIN {node} n ON n.nid = b.nid ORDER BY b.weight, n.title'));
+  $books = array();
+  $books[0] = t('Independent, top-level book page');
+  while ($book = db_fetch_object($result)) {
+    $books[$book->bid] = $book->title;
   }
 
-  return $form;
+  $form = array();
+  $form['bid'] = array(
+    '#type' => 'select',
+    '#title' => t('Select a book'),
+    '#default_value' => $default_bid,
+    '#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; 
 }
 
+
+/**
+ * Helper function to recursively update $bid for each children
+ * when moving the parent to a new book.
+ */
+function book_update_children_bid($parent, $bid, $i=1) {
+  $sql = "SELECT DISTINCT(nid) FROM {book_pages} WHERE parent = %d";
+  $result[$i] = db_query($sql,$parent);
+  if (db_num_rows($result[$i]) > 0) {
+    while ($page = db_fetch_object($result[$i])) {
+      $sql = "UPDATE {book_pages} SET bid = %d WHERE nid = %d";
+      $result[$i+1] = db_query($sql, $bid, $page->nid);
+      book_update_children_bid($page->nid, $bid, $i+2);
+    }
+  }
+} 
+
 /**
  * Implementation of function book_outline()
  * Handles all book outline operations.
  */
 function book_outline($nid) {
   $node = node_load($nid);
-  $page = book_load($node);
 
-  $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.'),
-  );
-  $form['log'] = array('#type' => 'textarea',
-    '#title' => t('Log message'),
-    '#default_value' => $node->log,
-    '#description' => t('An explanation to help other authors understand your motivations to put this post into the book.'),
-  );
-
-  $form['nid'] = array('#type' => 'value', '#value' => $nid);
-  if ($page->nid) {
-    $form['update'] = array('#type' => 'submit',
+  if ($node->type == 'book') {
+    drupal_goto('admin/content/book/'. $node->nid); 
+  }
+  
+  if (isset($node->bid)) { // node is already part of the book outline
+    
+    $form = _book_parent_and_log_form($node);
+        
+    
+    $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,
+    );
+
+    if ($node->type != 'book_page') {
+      $form['may_remove'] = array(
+        '#value' => '<hr class="book_outline"/><h2 class="book_outline">'. t('This node may be removed from the book outline; it is not a %book_page.',array('%book_page' => node_get_types('name','book_page'))). '</h2>',
+        '#weight' => 20,
+      );
+      $form['remove'] = array(
+        '#type' => 'submit',
+        '#value' => t('Remove from book outline'),
+        '#weight' => 21,
+      );     
+    }
+
+    $form['move_page'] = array(
+      '#value' => '<hr class="book_outline"/><h2 class="book_outline">'. t('Move this post to a different book.'). '</h2>',
+      '#weight' => 40,
     );
-    $form['remove'] = array('#type' => 'submit',
-      '#value' => t('Remove from book outline'),
+      $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->bid, $node->nid, $children_note));
+    $form['select'] = array(
+      '#type' => 'submit',
+      '#value' => t('Select book'),
+      '#weight' => 55,
     );
   }
+
   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));
@@ -336,23 +572,36 @@ function book_outline_submit($form_id, $
 
   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, bid, parent, weight) VALUES (%d, %d, %d, %d)', $node->nid, $form_values['bid'], $form_values['parent'], $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.'));
+      drupal_goto('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.'));
       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.'));
+      break;
+    case t('Select book'):
+      if ($form_values['bid']  != $node->bid) {
+        db_query('UPDATE {book_pages} SET bid = %d, parent = 0 WHERE nid = %d', $form_values['bid'], $node->nid);
+        book_update_children_bid($node->nid, $form_values['bid']);
+        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.'));
+        drupal_goto('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
@@ -365,20 +614,27 @@ function book_outline_submit($form_id, $
  * 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;
+function book_location($node) {
+  
+  $nodes = array();
+  
+  $pages = pages_of_book_by_nid($node->bid);
+  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);
@@ -394,9 +650,11 @@ function book_prev($node) {
   if ($node->parent == 0) {
     return NULL;
   }
+  
+  $children = book_page_tree($node->bid);
 
   // 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);
@@ -405,7 +663,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;
   }
 }
@@ -415,17 +673,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->bid);  //= 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;
     }
@@ -438,50 +696,146 @@ function book_next($node) {
  * 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) {
+function book_page_content($node, $teaser = FALSE) {
   // Return the page body.
   return node_prepare($node, $teaser);
 }
 
 /**
+* Theme the name of the Author(s) on the book cover
+*/
+function theme_book_author($author) {
+  return '<h2 class="book_author">'. t('A book by %author', array('%author' =>  $author)) .'</h2>';
+}
+
+/**
+* Theme the book license on the cover. 
+*/
+function theme_book_license($license) {
+  $output = '<h3 class="book_license">'. t('License') .'</h3>
+    <p class="book_license">'. $license .'</p>';
+  return $output;
+}
+
+/**
+* Implementation of hook_view() for a book cover.
+*/
+//TODO: get rid of embedded HTML -> theme function
+function book_view(&$node, $teaser = FALSE, $page = FALSE) {
+  $node = node_prepare($node, $teaser);
+  if (!empty($node->book_author)) {
+    $node->content['book_author'] = array(
+      '#value' => theme('book_author', $node->book_author),
+      '#weight' => -1,
+    );
+    $node->teaser = '<div class="book_author">'. $node->book_author .'</div>'. $node->teaser;
+  }
+  if (!empty($node->book_license)) {
+    $node->book_license = check_markup($node->book_license, $node->format, FALSE); 
+    $node->content['book_license'] = array(
+      '#value' => theme('book_license', $node->book_license) ,
+      '#weight' => 100,
+    );
+  }
+  $node->content['book_toc'] = array(
+    '#value' => book_toc($node->bid),
+    '#weight' => 200,
+  );
+  return $node;
+}
+
+/**
+ * Creates the Table of contents printed on book cover $bid.
+ * Returns formatted html.
+ */
+function book_toc($bid) {
+
+  $children =  book_page_tree($bid); 
+  return theme('book_toc', $children);
+}
+
+/**
+ * Theme function returning nested list items.
+ */
+function theme_book_toc($children) {
+  $toc = '<hr /><div class="book_toc"><h3>' . t('Table of contents') . '</h3>';
+  $toc .= build_book_toc($children);
+  $toc .= '</div><hr />';
+  return $toc;
+}
+
+/**
+ * This is a helper function for theme_book_toc().
+ */
+function build_book_toc($children, $nid = 0) {
+  if ($children[$nid]) {
+    $toc = '<ol>';
+    foreach ($children[$nid] as $foo => $node) {
+      $toc .= '<li>'. l($node->title , 'node/'.$node->nid). '</li>';
+      $toc .= build_book_toc($children,$node->nid);
+    }
+    $toc .= '</ol>';
+  }
+  return $toc;
+}
+
+/**
  * Implementation of hook_nodeapi().
  *
  * Appends book navigation to all nodes in the book.
  */
 function book_nodeapi(&$node, $op, $teaser, $page) {
   switch ($op) {
+    case 'load':
+      if (($node->type != 'book') && ($node->type != 'book_page')){
+        return db_fetch_array(db_query('SELECT * FROM {book_pages} WHERE nid = %d', $node->nid));
+      }
+      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;
-          }
-
-          $path = book_location($node);
-          // Construct the breadcrumb:
+        if ($node->type == 'book') {
           $node->breadcrumb = array(); // Overwrite the trail with a book trail.
-          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);
+          $node->breadcrumb[] = array ('path' => 'book', 'title' => t('books'));
+          $node->breadcrumb[] = array ('path' => 'node/'. $node->nid, 'title' => $node->title);
+          menu_set_location($node->breadcrumb);
+        }
+        else { 
+          // check if it is a node added in the outline:
+          if (isset($node->bid)) {
+            $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'));
+            if (!empty($node->bid)) {
+              $cover = db_fetch_object(db_query('SELECT n.title, n.nid FROM {book} b INNER JOIN {node} n ON n.nid = b.nid WHERE b.bid = %d', $node->bid));
+              $node->breadcrumb[] = array ('path' => 'node/'. $cover->nid, 'title' => $cover->title);
+            }
+            
+            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_page_navigation', $node),
+              '#weight' => 100,
+            );
+
+            if ($page) {
+              menu_set_location($node->breadcrumb);
+            }
           }
         }
       }
+      return $node;
       break;
     case 'delete revision':
-      db_query('DELETE FROM {book} WHERE vid = %d', $node->vid);
+      if ($node->type == 'book'){
+        db_query('DELETE FROM {book} WHERE vid = %d', $node->vid);
+      }
       break;
     case 'delete':
-      db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+      db_query('DELETE FROM {book_pages} WHERE nid = %d', $node->nid);
       break;
   }
 }
@@ -492,21 +846,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->bid, $node->nid);
 
     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')));
     }
+    elseif ($node->bid != 0) {
+      $cover_nid = db_result(db_query('SELECT nid FROM {book} WHERE bid = %d', $node->bid));
+      $links .= l(t('up'), 'node/'. $cover_nid, 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)));
       $links .= l($next->title . t(' ›'), 'node/'. $next->nid, array('class' => 'page-next', 'title' => t('Go to next page')));
@@ -530,12 +888,12 @@ function theme_book_navigation($node) {
 /**
  * This is a helper function for book_toc().
  */
-function book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
+function _book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
   if ($children[$nid]) {
     foreach ($children[$nid] as $foo => $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);
       }
     }
   }
@@ -543,59 +901,96 @@ function book_toc_recurse($nid, $indent,
   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 where the array keys are the nid values
  */
-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'));
+function pages_of_book_by_nid($bid) {
+ static $bynid = array();
+ 
+ if (!isset($bynid[$bid])){
+   $pages= pages_of_book($bid);
+   foreach ($pages as $node) {
+     $bynid[$bid][$node->nid] = $node;
+   }
+ }
+ return $bynid[$bid];
+}
+   
+/**
+ * Returns an array of titles and nid entries of book pages in table of contents order
+ */
+function pages_of_book($bid) {
+ static $book = array();
+ 
+ if (!isset($book[$bid])){
+   $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.bid = %d ORDER BY bp.weight ASC, n.title ASC'), $bid);
+
+   while ($node = db_fetch_object($result)) {
+   $book[$bid][] = $node;
+   }
+ }
+ return $book[$bid];
+}
 
-  $children = array();
-  while ($node = db_fetch_object($result)) {
-    if (!$children[$node->parent]) {
-      $children[$node->parent] = array();
+/**
+ * Returns an array corresponding to the tree of titles and nid entries of book pages in table of contents order
+ */
+function book_page_tree($bid){
+  static $children = array();
+  
+  if (!isset($children[$bid])) {
+    $pages=pages_of_book($bid);
+    $children[$bid] = array();
+    foreach ($pages as $node) {
+      if (!$children[$bid][$node->parent]) {
+        $children[$bid][$node->parent] = array();
+      }
+      $children[$bid][$node->parent][] = $node;
     }
-    $children[$node->parent][] = $node;
   }
+  return $children[$bid];
+}
 
+/**
+ * Returns an array of titles and nid entries of book pages in table of contents order
+ * for use in a form select.
+ */
+function select_book_page_parent($exclude = 0,  $bid) {
+  
+  $children = book_page_tree($bid);
   $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[0] = '<'. t('top-level') .'>';
 
-  $toc = book_toc_recurse(0, '', $toc, $children, $exclude);
+  $toc = _book_toc_recurse(0, '', $toc, $children, $exclude);
 
   return $toc;
 }
 
 /**
- * This is a helper function for book_tree()
+ * This is a default theme display function for book_tree()
  */
-function book_tree_recurse($nid, $depth, $children, $unfold = array()) {
+function theme_book_tree_display($nid, $depth, $children, $unfold = array()) {
   $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 (depth == 1 || !in_array($node->nid, $unfold)) {
+            $output .= '<li class="collapsed">'. l($node->title, 'node/'. $node->nid);
           }
           else {
-            $output .= '<li class="leaf">'. l($node->title, 'node/'. $node->nid) .'</li>';
+            $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>';
     }
   }
 
@@ -603,35 +998,41 @@ 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($bid, $parent = 0, $depth = 3, $unfold = array()) {
+  
+  $children = book_page_tree($bid);
+  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() {
+  $result = db_query(db_rewrite_sql('SELECT b.bid, b.nid, n.title FROM {book} b JOIN {node} n ON n.nid = b.nid ORDER BY b.weight ASC, n.title ASC'));
+  $breadcrumb = array (l( t('Home'),''));
+  drupal_set_breadcrumb($breadcrumb);
 
+  $output = '';
   $books = array();
   while ($node = db_fetch_object($result)) {
     $books[] = l($node->title, 'node/'. $node->nid);
   }
+  $output .= theme('item_list', $books, t('books'));
+  
+  // Add to those the top-level book pages without a book_cover.
+  $result = db_query(db_rewrite_sql('SELECT bp.nid, n.title FROM {book_pages} bp JOIN {node} n ON n.nid = bp.nid WHERE bp.parent = 0 AND bp.bid = 0 ORDER BY bp.weight ASC, n.title ASC'));
+  $books = array();
+  while ($node = db_fetch_object($result)) {
+    $books[] = l($node->title, 'node/'. $node->nid);
+  }
+  if (count($books)) {
+    $output .= theme('item_list', $books, t('Independent top level book pages'));
+  }
 
-  return theme('item_list', $books);
+  return $output;
 }
 
 /**
@@ -654,7 +1055,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.bid 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);
   }
@@ -744,7 +1145,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);
@@ -757,7 +1158,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) {
@@ -825,7 +1226,16 @@ function _book_admin_table($nodes = arra
   );
 
   foreach ($nodes as $node) {
-    $form = array_merge($form, _book_admin_table_tree($node, 0));
+    if ($node->type == 'book') {
+      $result = db_query('SELECT nid FROM {book_pages} WHERE parent = 0 AND bid = %d', $node->bid);
+      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;
@@ -849,7 +1259,7 @@ 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));
   }
@@ -902,7 +1312,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)) {
@@ -974,13 +1384,33 @@ 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'));
+  $output = '';
+
+  // List all book covers
+  $rows = array();
+  $result = db_query(db_rewrite_sql('SELECT b.bid, b.nid , n.title FROM {book} b JOIN {node} n ON n.nid = b.nid ORDER BY weight, 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'));
 
-  return theme('table', $headers, $rows);
+  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();
+  $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 bp.parent = 0 AND bp.bid = 0 ORDER BY bp.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"));
+  }
+  if (count($rows)) {
+    $headers = array(t('Independent book pages'), t('Operations'));
+    $output .= theme('table', $headers, $rows);
+  }
+  
+  return $output;
 }
 
 /**
@@ -1013,8 +1443,45 @@ 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')));
   }
 }
 
 
+
+/**
+ * Prints a list of books in which the user can add pages.
+ */
+function _add_page_select_book() {
+
+  $form = _book_select_form(0,0,t("After choosing a book, you will be able to edit your page and position it within the book."));
+  $form['submit'] = array(
+    '#type' => 'submit',
+    '#value' => t('Select book'),
+    '#weight' => 65,
+  );
+  return drupal_get_form('add_page_to_book', $form);;
+}
+
+/**
+ * Menu call back: Select a book to move a page to.
+ */
+function add_page_to_book_submit($form_id, $form) {
+
+   drupal_goto('node/add/book-page/'. $form['bid']. '/0');
+}
+
+/**
+ * Implementation of hook_form_alter()
+ */
+function book_form_alter($form_id, &$form) {
+  switch($form_id) {
+    case 'node_delete_confirm':
+      $node_type = db_result(db_query('SELECT type FROM {node} WHERE nid = %d ', $form['nid']['#value']));
+      if ($node_type == 'book') {
+        $form['book'] = array(
+          '#value' => t('Note that all book pages belonging to this book (if any) will no longer be associated to any book. You may want to move remaining book pages within this book to another book first. '),
+        );
+      }
+  }
+}
