Cleanup tabs in thumbnail feature for code guidelines
[bookreader.git] / GnuBook / GnuBook.js
index c924be6..a654b5c 100644 (file)
@@ -24,24 +24,27 @@ This file is part of GnuBook.
 // GnuBook()
 //______________________________________________________________________________
 // After you instantiate this object, you must supply the following
-// book-specific functions, before calling init():
+// book-specific functions, before calling init().  Some of these functions
+// can just be stubs for simple books.
 //  - getPageWidth()
 //  - getPageHeight()
 //  - getPageURI()
+//  - getPageSide()
+//  - canRotatePage()
+//  - getPageNum()
+//  - getSpreadIndices()
 // You must also add a numLeafs property before calling init().
 
-//XXX
-if (typeof(console) == 'undefined') {
-    console = { log: function(msg) { } };
-}
-
 function GnuBook() {
     this.reduce  = 4;
     this.padding = 10;
-    this.mode    = 1; //1 or 2
+    this.mode    = 1; //1, 2, 3
     this.ui = 'full'; // UI mode
-    
+    this.thumbScale = 10; // thumbnail default
+    this.thumbRowBuffer = 4; // number of rows to pre-cache out a view
+
     this.displayedIndices = [];        
+    this.displayedRows=[];
     //this.indicesToDisplay = [];
     this.imgs = {};
     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
@@ -55,7 +58,9 @@ function GnuBook() {
     this.twoPagePopUp = null;
     this.leafEdgeTmp  = null;
     this.embedPopup = null;
+    this.printPopup = null;
     
+    this.searchTerm = '';
     this.searchResults = {};
     
     this.firstIndex = null;
@@ -71,7 +76,11 @@ function GnuBook() {
     // Mode constants
     this.constMode1up = 1;
     this.constMode2up = 2;
+    this.constModeThumb = 3;
     
+    // Zoom levels
+    this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
+
     // Object to hold parameters related to 2up mode
     this.twoPage = {
         coverInternalPadding: 10, // Width of cover
@@ -79,6 +88,10 @@ function GnuBook() {
         bookSpineDivWidth: 30,    // Width of book spine  $$$ consider sizing based on book length
         autofit: true
     };
+    
+    // Background color for pages (e.g. when loading page image)
+    // $$$ TODO dynamically calculate based on page images
+    this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
 };
 
 // init()
@@ -86,6 +99,7 @@ function GnuBook() {
 GnuBook.prototype.init = function() {
 
     var startIndex = undefined;
+    this.pageScale = this.reduce; // preserve current reduce
     
     // Find start index and mode if set in location hash
     var params = this.paramsFromFragment(window.location.hash);
@@ -140,20 +154,46 @@ GnuBook.prototype.init = function() {
             e.data.displayedIndices = [];
             e.data.updateSearchHilites(); //deletes hilights but does not call remove()            
             e.data.loadLeafs();
+        } else if (3 == e.data.mode){
+            e.data.prepareThumbnailView();
         } else {
             //console.log('drawing 2 page view');
-            e.data.prepareTwoPageView();
+            
+            // We only need to prepare again in autofit (size of spread changes)
+            if (e.data.twoPage.autofit) {
+                e.data.prepareTwoPageView();
+            } else {
+                // Re-center if the scrollbars have disappeared
+                var center = e.data.twoPageGetViewCenter();
+                var doRecenter = false;
+                if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
+                    center.percentageX = 0.5;
+                    doRecenter = true;
+                }
+                if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
+                    center.percentageY = 0.5;
+                    doRecenter = true;
+                }
+                if (doRecenter) {
+                    e.data.twoPageCenterView(center.percentageX, center.percentageY);
+                }
+            }
         }
     });
     
     $('.GBpagediv1up').bind('mousedown', this, function(e) {
-        //console.log('mousedown!');
+        // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
+        //     but this also interferes with right-click.  See https://bugs.edge.launchpad.net/gnubook/+bug/362626
     });
 
     if (1 == this.mode) {
         this.resizePageView();
         this.firstIndex = startIndex;
         this.jumpToIndex(startIndex);
+    } else if (3 == this.mode) {
+        this.firstIndex = startIndex;
+        this.prepareThumbnailView();
+        this.jumpToIndex(startIndex);
     } else {
         //this.resizePageView();
         
@@ -163,7 +203,6 @@ GnuBook.prototype.init = function() {
         //console.log('titleLeaf: %d', this.titleLeaf);
         //console.log('displayedIndices: %s', this.displayedIndices);
         this.prepareTwoPageView();
-        //if (this.auto) this.nextPage();
     }
         
     // Enact other parts of initial params
@@ -172,7 +211,7 @@ GnuBook.prototype.init = function() {
 
 GnuBook.prototype.setupKeyListeners = function() {
     var self = this;
-
+    
     var KEY_PGUP = 33;
     var KEY_PGDOWN = 34;
     var KEY_END = 35;
@@ -185,44 +224,46 @@ GnuBook.prototype.setupKeyListeners = function() {
 
     // We use document here instead of window to avoid a bug in jQuery on IE7
     $(document).keydown(function(e) {
-        
+    
         // Keyboard navigation        
-        switch(e.keyCode) {
-            case KEY_PGUP:
-            case KEY_UP:            
-                // In 1up mode page scrolling is handled by browser
-                if (2 == self.mode) {
-                    self.prev();
-                }
-                break;
-            case KEY_DOWN:
-            case KEY_PGDOWN:
-                if (2 == self.mode) {
-                    self.next();
-                }
-                break;
-            case KEY_END:
-                self.last();
-                break;
-            case KEY_HOME:
-                self.first();
-                break;
-            case KEY_LEFT:
-                if (self.keyboardNavigationIsDisabled(e)) {
+        if (!self.keyboardNavigationIsDisabled(e)) {
+            switch(e.keyCode) {
+                case KEY_PGUP:
+                case KEY_UP:            
+                    // In 1up mode page scrolling is handled by browser
+                    if (2 == self.mode) {
+                        e.preventDefault();
+                        self.prev();
+                    }
                     break;
-                }
-                if (2 == self.mode) {
-                    self.left();
-                }
-                break;
-            case KEY_RIGHT:
-                if (self.keyboardNavigationIsDisabled(e)) {
+                case KEY_DOWN:
+                case KEY_PGDOWN:
+                    if (2 == self.mode) {
+                        e.preventDefault();
+                        self.next();
+                    }
                     break;
-                }
-                if (2 == self.mode) {
-                    self.right();
-                }
-                break;
+                case KEY_END:
+                    e.preventDefault();
+                    self.last();
+                    break;
+                case KEY_HOME:
+                    e.preventDefault();
+                    self.first();
+                    break;
+                case KEY_LEFT:
+                    if (2 == self.mode) {
+                        e.preventDefault();
+                        self.left();
+                    }
+                    break;
+                case KEY_RIGHT:
+                    if (2 == self.mode) {
+                        e.preventDefault();
+                        self.right();
+                    }
+                    break;
+            }
         }
     });
 }
@@ -232,17 +273,21 @@ GnuBook.prototype.setupKeyListeners = function() {
 GnuBook.prototype.drawLeafs = function() {
     if (1 == this.mode) {
         this.drawLeafsOnePage();
+    } else if(3 == this.mode) {
+        this.drawLeafsThumbnail();
     } else {
         this.drawLeafsTwoPage();
     }
 }
 
-// setDragHandler1up()
+// setDragHandler()
 //______________________________________________________________________________
-GnuBook.prototype.setDragHandler1up = function(div) {
+GnuBook.prototype.setDragHandler = function(div) {
     div.dragging = false;
 
-    $(div).bind('mousedown', function(e) {
+    $(div).unbind('mousedown').bind('mousedown', function(e) {
+        e.preventDefault();
+        
         //console.log('mousedown at ' + e.pageY);
 
         this.dragging = true;
@@ -254,11 +299,12 @@ GnuBook.prototype.setDragHandler1up = function(div) {
         var startTop  = $('#GBcontainer').attr('scrollTop');
         var startLeft =  $('#GBcontainer').attr('scrollLeft');
 
-        return false;
     });
         
-    $(div).bind('mousemove', function(ee) {
-        //console.log('mousemove ' + startY);
+    $(div).unbind('mousemove').bind('mousemove', function(ee) {
+        ee.preventDefault();
+
+        // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
         
         var offsetX = ee.pageX - this.prevMouseX;
         var offsetY = ee.pageY - this.prevMouseY;
@@ -271,22 +317,125 @@ GnuBook.prototype.setDragHandler1up = function(div) {
         this.prevMouseX = ee.pageX;
         this.prevMouseY = ee.pageY;
         
-        return false;
     });
     
-    $(div).bind('mouseup', function(ee) {
+    $(div).unbind('mouseup').bind('mouseup', function(ee) {
+        ee.preventDefault();
         //console.log('mouseup');
 
         this.dragging = false;
-        return false;
     });
     
-    $(div).bind('mouseleave', function(e) {
+    $(div).unbind('mouseleave').bind('mouseleave', function(e) {
+        e.preventDefault();
         //console.log('mouseleave');
 
-        //$(this).unbind('mousemove mouseup');
+        this.dragging = false;        
+    });
+    
+    $(div).unbind('mouseenter').bind('mouseenter', function(e) {
+        e.preventDefault();
+        //console.log('mouseenter');
+        
         this.dragging = false;
+    });
+}
+
+// setDragHandler2UP()
+//______________________________________________________________________________
+GnuBook.prototype.setDragHandler2UP = function(div) {
+    div.dragging = false;
+    
+    $(div).unbind('mousedown').bind('mousedown', function(e) {
+        e.preventDefault();
         
+        //console.log('mousedown at ' + e.pageY);
+
+        this.dragStart = {x: e.pageX, y: e.pageY };
+        this.mouseDown = true;
+        this.dragging = false; // wait until drag distance
+        this.prevMouseX = e.pageX;
+        this.prevMouseY = e.pageY;
+    
+        var startX    = e.pageX;
+        var startY    = e.pageY;
+        var startTop  = $('#GBcontainer').attr('scrollTop');
+        var startLeft =  $('#GBcontainer').attr('scrollLeft');
+
+    });
+        
+    $(div).unbind('mousemove').bind('mousemove', function(ee) {
+        ee.preventDefault();
+
+        // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
+        
+        var offsetX = ee.pageX - this.prevMouseX;
+        var offsetY = ee.pageY - this.prevMouseY;
+        
+        var minDragDistance = 5; // $$$ constant
+
+        var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
+                
+        if (this.mouseDown && (distance > minDragDistance)) {
+            //console.log('drag start!');
+            
+            this.dragging = true;
+        }
+        
+        if (this.dragging) {        
+            $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
+            $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
+            this.prevMouseX = ee.pageX;
+            this.prevMouseY = ee.pageY;
+        }
+        
+        
+    });
+    
+    /*
+    $(div).unbind('mouseup').bind('mouseup', function(ee) {
+        ee.preventDefault();
+        //console.log('mouseup');
+
+        this.dragging = false;
+        this.mouseDown = false;
+    });
+    */
+    
+    
+    $(div).unbind('mouseleave').bind('mouseleave', function(e) {
+        e.preventDefault();
+        //console.log('mouseleave');
+
+        this.dragging = false;  
+        this.mouseDown = false;
+    });
+    
+    $(div).unbind('mouseenter').bind('mouseenter', function(e) {
+        e.preventDefault();
+        //console.log('mouseenter');
+        
+        this.dragging = false;
+        this.mouseDown = false;
+    });
+}
+
+GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
+    //console.log('setting handler');
+    //console.log(element.tagName);
+    
+    $(element).unbind('click').bind('click', data, function(e) {
+        e.preventDefault();
+        
+        //console.log('click!');
+        
+        if (this.mouseDown && (!this.dragging)) {
+            //console.log('click not dragging!');
+            handler(e);
+        }
+        
+        this.dragging = false;
+        this.mouseDown = false;
     });
 }
 
@@ -307,7 +456,7 @@ GnuBook.prototype.drawLeafsOnePage = function() {
     var leafTop = 0;
     var leafBottom = 0;
     for (i=0; i<this.numLeafs; i++) {
-        var height  = parseInt(this.getPageHeight(i)/this.reduce); 
+        var height  = parseInt(this._getPageHeight(i)/this.reduce); 
     
         leafBottom += height;
         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
@@ -345,7 +494,7 @@ GnuBook.prototype.drawLeafsOnePage = function() {
     leafTop = 0;
     var i;
     for (i=0; i<firstIndexToDraw; i++) {
-        leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
+        leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
     }
 
     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
@@ -354,10 +503,10 @@ GnuBook.prototype.drawLeafsOnePage = function() {
 
     for (i=0; i<indicesToDisplay.length; i++) {
         var index = indicesToDisplay[i];    
-        var height  = parseInt(this.getPageHeight(index)/this.reduce); 
+        var height  = parseInt(this._getPageHeight(index)/this.reduce); 
 
         if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
-            var width   = parseInt(this.getPageWidth(index)/this.reduce); 
+            var width   = parseInt(this._getPageWidth(index)/this.reduce); 
             //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
             var div = document.createElement("div");
             div.className = 'GBpagediv1up';
@@ -371,12 +520,12 @@ GnuBook.prototype.drawLeafsOnePage = function() {
             $(div).css('height', height+'px');
             //$(div).text('loading...');
             
-            this.setDragHandler1up(div);
+            this.setDragHandler(div);
             
             $('#GBpageview').append(div);
 
             var img = document.createElement("img");
-            img.src = this.getPageURI(index);
+            img.src = this._getPageURI(index, this.reduce, 0);
             $(img).css('width', width+'px');
             $(img).css('height', height+'px');
             $(div).append(img);
@@ -413,19 +562,184 @@ GnuBook.prototype.drawLeafsOnePage = function() {
     
 }
 
+// drawLeafsThumbnail()
+//______________________________________________________________________________
+GnuBook.prototype.drawLeafsThumbnail = function() {
+    //alert('drawing leafs!');
+    this.timer = null;
+
+    var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
+
+    //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
+
+    var i;
+    var leafWidth;
+    var leafHeight;
+    var rightPos = 0;
+    var bottomPos = 0;
+    var maxRight = 0;
+    var currentRow = 0;
+    var leafIndex = 0;
+    var leafMap = [];
+
+    for (i=0; i<this.numLeafs; i++) {
+        leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
+        if (rightPos + (leafWidth + this.padding) > viewWidth){
+            currentRow++;
+            rightPos = 0;
+            leafIndex = 0;
+        }
+
+        if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
+        if (leafMap[currentRow].leafs===undefined) {
+            leafMap[currentRow].leafs = [];
+            leafMap[currentRow].height = 0;
+            leafMap[currentRow].top = 0;
+        }
+        leafMap[currentRow].leafs[leafIndex] = {};
+        leafMap[currentRow].leafs[leafIndex].num = i;
+        leafMap[currentRow].leafs[leafIndex].left = rightPos;
+
+        leafHeight = parseInt(this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)/this.reduce, 10);
+        if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
+        if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
+        rightPos += leafWidth + this.padding;
+        if (rightPos > maxRight) { maxRight = rightPos; }
+        leafIndex++;
+    }
+
+    // reset the bottom position based on thumbnails
+    $('#GBpageview').height(bottomPos);
+
+    var pageViewBuffer = Math.floor(($('#GBcontainer').attr('scrollWidth') - maxRight) / 2) - 14;      
+    var scrollTop = $('#GBcontainer').attr('scrollTop');
+    var scrollBottom = scrollTop + $('#GBcontainer').height();
+
+    var leafTop = 0;
+    var leafBottom = 0;
+    var rowsToDisplay = [];
+
+    for (i=0; i<leafMap.length; i++) {
+        leafBottom += this.padding + leafMap[i].height;
+        var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
+        var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
+        var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
+        if (topInView | bottomInView | middleInView) {
+            //console.log('row to display: ' + j);
+            rowsToDisplay.push(i);
+        }
+        if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
+        leafTop = leafBottom;
+    }
+
+    var firstRow = rowsToDisplay[0];
+    var lastRow = rowsToDisplay[rowsToDisplay.length-1];
+    for (i=1; i<this.thumbRowBuffer+1; i++) {
+        if (firstRow-i >= 0) { rowsToDisplay.unshift(firstRow-i); }
+        if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
+}
+
+    // Update hash, but only if we're currently displaying a leaf
+    // Hack that fixes #365790
+    if (this.displayedRows.length > 0) {
+        this.updateLocationHash();
+    }
+
+    var j;
+    var row;
+    var left;
+    var index;
+    var div;
+    var link;
+    var img;
+    for (i=0; i<rowsToDisplay.length; i++) {
+        if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {    
+            row = rowsToDisplay[i];
+
+            for (j=0; j<leafMap[row].leafs.length; j++) {
+                index = leafMap[row].leafs[j].num;
+
+                leafWidth = parseInt(this.getPageWidth(index)/this.reduce, 10);
+                leafHeight = parseInt(this.getPageHeight(index)/this.reduce, 10);
+                leafTop = leafMap[row].top;
+                left = leafMap[row].leafs[j].left + pageViewBuffer;
+
+                div = document.createElement("div");
+                div.id = 'pagediv'+index;
+                div.style.position = "absolute";
+                div.className = "GBpagedivthumb";                              
+
+                left += this.padding;
+                $(div).css('top', leafTop + 'px');
+                $(div).css('left', left+'px');
+                $(div).css('width', leafWidth+'px');
+                $(div).css('height', leafHeight+'px');
+                //$(div).text('loading...');
+
+                // link to page in single page mode
+                link = document.createElement("a");
+                link.href = '#page/' + (this.getPageNum(index)) +'/mode/1up' ;
+                $(div).append(link);
+
+                $('#GBpageview').append(div);
+
+                img = document.createElement("img");
+                img.src = this.getPageURI(index);
+                $(img).css('width', leafWidth+'px');
+                $(img).css('height', leafHeight+'px');
+                img.style.border = "0";
+                $(link).append(img);
+                //console.log('displaying thumbnail: ' + leafMap[j]);
+            }   
+        }
+    }
+
+    // remove previous highlights
+    if ($('.GBpagedivthumb_highlight').length>0) {
+        div = $('.GBpagedivthumb_highlight')
+        div.attr({className: 'GBpagedivthumb' });
+    }
+    // highlight current page
+    $('#pagediv'+this.currentIndex()).attr({className: 'GBpagedivthumb_highlight' });
+
+    var k;
+    for (i=0; i<this.displayedRows.length; i++) {
+        if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
+            row = this.displayedRows[i];
+            for (k=0; k<leafMap[row].leafs.length; k++) {
+                index = leafMap[row].leafs[k].num;
+                //console.log('Removing leaf ' + index);
+                $('#pagediv'+index).remove();
+            }
+        } else {
+
+            //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
+        }
+    }
+
+    this.displayedRows = rowsToDisplay.slice();
+
+    if (null !== this.getPageNum(this.currentIndex()))  {
+        $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
+    } else {
+        $("#GBpagenum").val('');
+    }
+
+    this.updateToolbarZoom(this.reduce); 
+}
+
 // drawLeafsTwoPage()
 //______________________________________________________________________________
 GnuBook.prototype.drawLeafsTwoPage = function() {
-    console.log('drawing two leafs!'); // XXX
-
     var scrollTop = $('#GBtwopageview').attr('scrollTop');
     var scrollBottom = scrollTop + $('#GBtwopageview').height();
     
-    console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.twoPage.currentIndexL); // XXX
+    // $$$ we should use calculated values in this.twoPage (recalc if necessary)
     
     var indexL = this.twoPage.currentIndexL;
-    var heightL  = this.getPageHeight(indexL); 
-    var widthL   = this.getPageWidth(indexL);
+        
+    var heightL  = this._getPageHeight(indexL); 
+    var widthL   = this._getPageWidth(indexL);
 
     var leafEdgeWidthL = this.leafEdgeWidth(indexL);
     var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
@@ -437,58 +751,59 @@ GnuBook.prototype.drawLeafsTwoPage = function() {
     var top = this.twoPageTop();
     var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
 
-    // $$$ should get getwidth2up?
-    //var scaledWL = parseInt(this.twoPage.height*widthL/heightL);
-    var scaledWL = this.getPageWidth2UP(indexL);
-    var gutter = this.twoPageGutter();
+    this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
+    this.twoPage.gutter = this.twoPageGutter();
     
     this.prefetchImg(indexL);
     $(this.prefetchedImgs[indexL]).css({
         position: 'absolute',
-        left: gutter-scaledWL+'px',
+        left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
         right: '',
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
+        backgroundColor: this.getPageBackgroundColor(indexL),
         height: this.twoPage.height +'px', // $$$ height forced the same for both pages
-        width:  scaledWL + 'px',
+        width:  this.twoPage.scaledWL + 'px',
         borderRight: '1px solid black',
         zIndex: 2
     }).appendTo('#GBtwopageview');
-
-
+    
     var indexR = this.twoPage.currentIndexR;
-    var heightR  = this.getPageHeight(indexR); 
-    var widthR   = this.getPageWidth(indexR);
+    var heightR  = this._getPageHeight(indexR); 
+    var widthR   = this._getPageWidth(indexR);
 
     // $$$ should use getwidth2up?
     //var scaledWR = this.twoPage.height*widthR/heightR;
-    var scaledWR = this.getPageWidth2UP(indexR);
+    this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
     this.prefetchImg(indexR);
     $(this.prefetchedImgs[indexR]).css({
         position: 'absolute',
-        left:   gutter+'px',
+        left:   this.twoPage.gutter+'px',
         right: '',
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
+        backgroundColor: this.getPageBackgroundColor(indexR),
         height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
-        width:  scaledWR + 'px',
+        width:  this.twoPage.scaledWR + 'px',
         borderLeft: '1px solid black',
         zIndex: 2
     }).appendTo('#GBtwopageview');
         
 
     this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
-    this.setClickHandlers();
+    this.setMouseHandlers2UP();
+    this.twoPageSetCursor();
 
     this.updatePageNumBox2UP();
     this.updateToolbarZoom(this.reduce);
+    
+    // this.twoPagePlaceFlipAreas();  // No longer used
+
 }
 
 // updatePageNumBox2UP
 //______________________________________________________________________________
 GnuBook.prototype.updatePageNumBox2UP = function() {
     if (null != this.getPageNum(this.twoPage.currentIndexL))  {
-        $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
+        $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
     } else {
         $("#GBpagenum").val('');
     }
@@ -525,6 +840,7 @@ GnuBook.prototype.zoom = function(direction) {
 // zoom1up(dir)
 //______________________________________________________________________________
 GnuBook.prototype.zoom1up = function(dir) {
+
     if (2 == this.mode) {     //can only zoom in 1-page mode
         this.switchMode(1);
         return;
@@ -539,7 +855,8 @@ GnuBook.prototype.zoom1up = function(dir) {
         if (this.reduce >= 8) return;
         this.reduce*=2;             //zoom out
     }
-    
+
+    this.pageScale = this.reduce; // preserve current reduce
     this.resizePageView();
 
     $('#GBpageview').empty()
@@ -547,6 +864,11 @@ GnuBook.prototype.zoom1up = function(dir) {
     this.loadLeafs();
     
     this.updateToolbarZoom(this.reduce);
+    
+    // Recalculate search hilites
+    this.removeSearchHilites(); 
+    this.updateSearchHilites();
+
 }
 
 // resizePageView()
@@ -572,8 +894,8 @@ GnuBook.prototype.resizePageView = function() {
     }
     
     for (i=0; i<this.numLeafs; i++) {
-        viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding; 
-        var width = parseInt(this.getPageWidth(i)/this.reduce);
+        viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding; 
+        var width = parseInt(this._getPageWidth(i)/this.reduce);
         if (width>viewWidth) viewWidth=width;
     }
     $('#GBpageview').height(viewHeight);
@@ -593,6 +915,9 @@ GnuBook.prototype.resizePageView = function() {
     //this.centerPageView();
     this.loadLeafs();
     
+    // Not really needed until there is 1up autofit
+    this.removeSearchHilites();
+    this.updateSearchHilites();
 }
 
 // centerX1up()
@@ -633,20 +958,102 @@ GnuBook.prototype.centerPageView = function() {
 // zoom2up(direction)
 //______________________________________________________________________________
 GnuBook.prototype.zoom2up = function(direction) {
-    // $$$ this is where we can e.g. snap to %2 sizes
-    if (0 == direction) { // autofit mode
-        this.twoPage.autofit = true;;
-    } else if (1 == direction) {
-        if (this.reduce <= 0.5) return;
-        this.reduce*=0.5;           //zoom in
-        this.twoPage.autofit = false;
-    } else {
-        if (this.reduce >= 8) return;
-        this.reduce *= 2; // zoom out
-        this.twoPage.autofit = false;
+
+    // Hard stop autoplay
+    this.stopFlipAnimations();
+    
+    // Get new zoom state    
+    var newZoom = this.twoPageNextReduce(this.reduce, direction);
+    if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
+        return;
+    }
+    this.twoPage.autofit = newZoom.autofit;
+    this.reduce = newZoom.reduce;
+    this.pageScale = this.reduce; // preserve current reduce
+
+    // Preserve view center position
+    var oldCenter = this.twoPageGetViewCenter();
+    
+    // If zooming in, reload imgs.  DOM elements will be removed by prepareTwoPageView
+    // $$$ An improvement would be to use the low res image until the larger one is loaded.
+    if (1 == direction) {
+        for (var img in this.prefetchedImgs) {
+            delete this.prefetchedImgs[img];
+        }
+    }
+    
+    // Prepare view with new center to minimize visual glitches
+    this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
+}
+
+
+// quantizeReduce(reduce)
+//______________________________________________________________________________
+// Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
+GnuBook.prototype.quantizeReduce = function(reduce) {
+    var quantized = this.reductionFactors[0];
+    var distance = Math.abs(reduce - quantized);
+    for (var i = 1; i < this.reductionFactors.length; i++) {
+        newDistance = Math.abs(reduce - this.reductionFactors[i]);
+        if (newDistance < distance) {
+            distance = newDistance;
+            quantized = this.reductionFactors[i];
+        }
+    }
+    
+    return quantized;
+}
+
+// twoPageNextReduce()
+//______________________________________________________________________________
+// Returns the next reduction level
+GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
+    var result = {};
+    var autofitReduce = this.twoPageGetAutofitReduce();
+
+    if (0 == direction) { // autofit
+        result.autofit = true;
+        result.reduce = autofitReduce;
+        
+    } else if (1 == direction) { // zoom in
+        var newReduce = this.reductionFactors[0];
+    
+        for (var i = 1; i < this.reductionFactors.length; i++) {
+            if (this.reductionFactors[i] < reduce) {
+                newReduce = this.reductionFactors[i];
+            }
+        }
+        
+        if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
+            // use autofit
+            result.autofit = true;
+            result.reduce = autofitReduce;
+        } else {        
+            result.autofit = false;
+            result.reduce = newReduce;
+        }
+        
+    } else { // zoom out
+        var lastIndex = this.reductionFactors.length - 1;
+        var newReduce = this.reductionFactors[lastIndex];
+        
+        for (var i = lastIndex; i >= 0; i--) {
+            if (this.reductionFactors[i] > reduce) {
+                newReduce = this.reductionFactors[i];
+            }
+        }
+         
+        if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
+            // use autofit
+            result.autofit = true;
+            result.reduce = autofitReduce;
+        } else {
+            result.autofit = false;
+            result.reduce = newReduce;
+        }
     }
     
-    this.prepareTwoPageView();
+    return result;
 }
 
 // jumpToPage()
@@ -670,7 +1077,7 @@ GnuBook.prototype.jumpToPage = function(pageNum) {
 
 // jumpToIndex()
 //______________________________________________________________________________
-GnuBook.prototype.jumpToIndex = function(index) {
+GnuBook.prototype.jumpToIndex = function(index, pageX, pageY) {
 
     if (2 == this.mode) {
         this.autoStop();
@@ -683,21 +1090,67 @@ GnuBook.prototype.jumpToIndex = function(index) {
             this.flipFwdToIndex(index);
         }
 
-    } else {        
+    } else if (3 == this.mode){        
+        var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
+        var i;
+        var leafWidth = 0;
+        var leafHeight = 0;
+        var rightPos = 0;
+        var bottomPos = 0;
+        var rowHeight = 0;
+        var leafTop = 0;
+        var leafIndex = 0;
+
+        for (i=0; i<(index+1); i++) {
+            leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
+            if (rightPos + (leafWidth + this.padding) > viewWidth){
+                rightPos = 0;
+                rowHeight = 0;
+                leafIndex = 0;
+            }
+            leafHeight = parseInt(this.getPageHeight(i)/this.reduce, 10);
+            if(leafHeight > rowHeight) { rowHeight = leafHeight; }
+            if (leafIndex==0) { leafTop = bottomPos; }
+            if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
+            rightPos += leafWidth + this.padding;
+            leafIndex++;
+        }
+        this.firstIndex=index;
+        if ($('#GBcontainer').attr('scrollTop') == leafTop) {
+            this.loadLeafs();
+        } else {
+            $('#GBcontainer').animate({scrollTop: leafTop },'fast');
+        }
+    } else {
         var i;
         var leafTop = 0;
+        var leafLeft = 0;
         var h;
         for (i=0; i<index; i++) {
-            h = parseInt(this.getPageHeight(i)/this.reduce); 
+            h = parseInt(this._getPageHeight(i)/this.reduce); 
             leafTop += h + this.padding;
         }
+
+        if (pageY) {
+            //console.log('pageY ' + pageY);
+            var offset = parseInt( (pageY) / this.reduce);
+            offset -= $('#GBcontainer').attr('clientHeight') >> 1;
+            //console.log( 'jumping to ' + leafTop + ' ' + offset);
+            leafTop += offset;
+        }
+
+        if (pageX) {
+            var offset = parseInt( (pageX) / this.reduce);
+            offset -= $('#GBcontainer').attr('clientWidth') >> 1;
+            leafLeft += offset;
+        }
+
         //$('#GBcontainer').attr('scrollTop', leafTop);
-        $('#GBcontainer').animate({scrollTop: leafTop },'fast');
+        $('#GBcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
     }
 }
 
 
-
 // switchMode()
 //______________________________________________________________________________
 GnuBook.prototype.switchMode = function(mode) {
@@ -714,13 +1167,26 @@ GnuBook.prototype.switchMode = function(mode) {
     this.removeSearchHilites();
 
     this.mode = mode;
-    
     this.switchToolbarMode(mode);
+
+    // reinstate scale if moving from thumbnail view
+    if (this.pageScale != this.reduce) this.reduce = this.pageScale;
     
+    // $$$ TODO preserve center of view when switching between mode
+    //     See https://bugs.edge.launchpad.net/gnubook/+bug/416682
+
     if (1 == mode) {
+        this.reduce = this.quantizeReduce(this.reduce);
         this.prepareOnePageView();
+    } else if (3 == mode) {
+        this.reduce = this.quantizeReduce(this.reduce);
+        this.prepareThumbnailView();
+        this.jumpToIndex(this.currentIndex());
     } else {
+        this.twoPage.autofit = false; // Take zoom level from other mode
+        this.reduce = this.quantizeReduce(this.reduce);
         this.prepareTwoPageView();
+        this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
     }
 
 }
@@ -750,6 +1216,40 @@ GnuBook.prototype.prepareOnePageView = function() {
     // Bind mouse handlers
     // Disable mouse click to avoid selected/highlighted page images - bug 354239
     gbPageView.bind('mousedown', function(e) {
+        // $$$ check here for right-click and don't disable.  Also use jQuery style
+        //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
+        return false;
+    })
+    // Special hack for IE7
+    gbPageView[0].onselectstart = function(e) { return false; };
+}
+
+//prepareThumbnailView()
+//______________________________________________________________________________
+GnuBook.prototype.prepareThumbnailView = function() {
+
+    // var startLeaf = this.displayedIndices[0];
+    var startLeaf = this.currentIndex();
+    this.reduce = this.thumbScale;
+
+    $('#GBcontainer').empty();
+    $('#GBcontainer').css({
+        overflowY: 'scroll',
+        overflowX: 'auto'
+    });
+    
+    var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
+    
+    this.resizePageView();
+    
+       this.displayedRows = [];
+    this.drawLeafsThumbnail();
+        
+    // Bind mouse handlers
+    // Disable mouse click to avoid selected/highlighted page images - bug 354239
+    gbPageView.bind('mousedown', function(e) {
+        // $$$ check here for right-click and don't disable.  Also use jQuery style
+        //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
         return false;
     })
     // Special hack for IE7
@@ -768,20 +1268,10 @@ GnuBook.prototype.prepareOnePageView = function() {
 // The two page view div is resized to keep the middle of the book in the middle of the div
 // even as the page sizes change.  To e.g. keep the middle of the book in the middle of the GBcontent
 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
-GnuBook.prototype.prepareTwoPageView = function() {
+GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
     $('#GBcontainer').empty();
     $('#GBcontainer').css('overflow', 'auto');
-
-    // Add the two page view
-    $('#GBcontainer').append('<div id="GBtwopageview"></div>');
-    // Explicitly set sizes the same
-    // $$$ calculate first then set
-    $('#GBtwopageview').css( {
-        height: $('#GBcontainer').height(),
-        width: $('#GBcontainer').width(),
-        position: 'absolute'
-        });
-
+        
     // We want to display two facing pages.  We may be missing
     // one side of the spread because it is the first/last leaf,
     // foldouts, missing pages, etc
@@ -797,21 +1287,46 @@ GnuBook.prototype.prepareTwoPageView = function() {
         targetLeaf = this.lastDisplayableIndex();
     }
     
-    this.twoPage.currentIndexL = null;
-    this.twoPage.currentIndexR = null;
-    this.pruneUnusedImgs();
+    //this.twoPage.currentIndexL = null;
+    //this.twoPage.currentIndexR = null;
+    //this.pruneUnusedImgs();
     
     var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
     this.twoPage.currentIndexL = currentSpreadIndices[0];
     this.twoPage.currentIndexR = currentSpreadIndices[1];
     this.firstIndex = this.twoPage.currentIndexL;
     
-    this.calculateSpreadSize(); //sets twoPage.width, twoPage.height, and twoPage.ratio
-        
-    $('#GBtwopageview').width(this.twoPage.totalWidth).height(this.twoPage.totalHeight);
+    this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
+
+    this.pruneUnusedImgs();
+    this.prefetch(); // Preload images or reload if scaling has changed
 
-    this.twoPageDiv = document.createElement('div');
-    $(this.twoPageDiv).attr('id', 'GBbookcover').css({
+    //console.dir(this.twoPage);
+    
+    // Add the two page view
+    // $$$ Can we get everything set up and then append?
+    $('#GBcontainer').append('<div id="GBtwopageview"></div>');
+
+    // $$$ calculate first then set
+    $('#GBtwopageview').css( {
+        height: this.twoPage.totalHeight + 'px',
+        width: this.twoPage.totalWidth + 'px',
+        position: 'absolute'
+        });
+        
+    // If there will not be scrollbars (e.g. when zooming out) we center the book
+    // since otherwise the book will be stuck off-center
+    if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
+        centerPercentageX = 0.5;
+    }
+    if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
+        centerPercentageY = 0.5;
+    }
+        
+    this.twoPageCenterView(centerPercentageX, centerPercentageY);
+    
+    this.twoPage.coverDiv = document.createElement('div');
+    $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
         border: '1px solid rgb(68, 25, 17)',
         width:  this.twoPage.bookCoverDivWidth + 'px',
         height: this.twoPage.bookCoverDivHeight+'px',
@@ -865,19 +1380,60 @@ GnuBook.prototype.prepareTwoPageView = function() {
         left:            this.twoPage.bookSpineDivLeft+'px',
         top:             this.twoPage.bookSpineDivTop+'px'
     }).appendTo('#GBtwopageview');
-
+    
+    var self = this; // for closure
+    
+    /* Flip areas no longer used
+    this.twoPage.leftFlipArea = document.createElement('div');
+    this.twoPage.leftFlipArea.className = 'GBfliparea';
+    $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
+        border: '0',
+        width:  this.twoPageFlipAreaWidth() + 'px',
+        height: this.twoPageFlipAreaHeight() + 'px',
+        position: 'absolute',
+        left:   this.twoPageLeftFlipAreaLeft() + 'px',
+        top:    this.twoPageFlipAreaTop() + 'px',
+        cursor: 'w-resize',
+        zIndex: 100
+    }).bind('click', function(e) {
+        self.left();
+    }).bind('mousedown', function(e) {
+        e.preventDefault();
+    }).appendTo('#GBtwopageview');
+    
+    this.twoPage.rightFlipArea = document.createElement('div');
+    this.twoPage.rightFlipArea.className = 'GBfliparea';
+    $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
+        border: '0',
+        width:  this.twoPageFlipAreaWidth() + 'px',
+        height: this.twoPageFlipAreaHeight() + 'px',
+        position: 'absolute',
+        left:   this.twoPageRightFlipAreaLeft() + 'px',
+        top:    this.twoPageFlipAreaTop() + 'px',
+        cursor: 'e-resize',
+        zIndex: 100
+    }).bind('click', function(e) {
+        self.right();
+    }).bind('mousedown', function(e) {
+        e.preventDefault();
+    }).appendTo('#GBtwopageview');
+    */
+    
     this.prepareTwoPagePopUp();
-
+    
     this.displayedIndices = [];
     
     //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
     //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
     
     this.drawLeafsTwoPage();
-    this.updateSearchHilites2UP();
     this.updateToolbarZoom(this.reduce);
     
     this.prefetch();
+
+    this.removeSearchHilites();
+    this.updateSearchHilites();
+
 }
 
 // prepareTwoPagePopUp()
@@ -952,19 +1508,15 @@ GnuBook.prototype.prepareTwoPagePopUp = function() {
 //______________________________________________________________________________
 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
 // this.twoPage.currentIndexR
-// This function sets this.twoPage.height, twoPage.width, and twoPage.ratio
+// This function sets this.twoPage.height, twoPage.width
 
 GnuBook.prototype.calculateSpreadSize = function() {
-    console.log('calculateSpreadSize ' + this.twoPage.currentIndexL); // XXX
 
-    // $$$ TODO Calculate the spread size based on the reduction factor.  If we are using
-    // fit mode we recalculate the reduction factor based on the current page sizes
-    // and display size first.
-    
     var firstIndex  = this.twoPage.currentIndexL;
     var secondIndex = this.twoPage.currentIndexR;
     //console.log('first page is ' + firstIndex);
 
+    // Calculate page sizes and total leaf width
     var spreadSize;
     if ( this.twoPage.autofit) {    
         spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
@@ -973,26 +1525,34 @@ GnuBook.prototype.calculateSpreadSize = function() {
         spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
     }
     
+    // Both pages together
     this.twoPage.height = spreadSize.height;
     this.twoPage.width = spreadSize.width;
-    this.twoPage.ratio = spreadSize.ratio;
-    this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
     
+    // Individual pages
     this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
     this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
+    
+    // Leaf edges
+    this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
     this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
     this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
     
+    
+    // Book cover
     // The width of the book cover div.  The combined width of both pages, twice the width
     // of the book cover internal padding (2*10) and the page edges
     this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
-    
     // The height of the book cover div
     this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
-        
-    // Total height and width -- makes the spine middle centered
+    
+    
+    // We calculate the total width and height for the div so that we can make the book
+    // spine centered
     var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
-    var largestWidthFromCenter = Math.max( (this.twoPage.scaledWL + leftGutterOffset), (this.twoPage.scaledWR - leftGutterOffset));
+    var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
+    var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
+    var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
     this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
     this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
         
@@ -1004,9 +1564,13 @@ GnuBook.prototype.calculateSpreadSize = function() {
     this.twoPage.middle = this.twoPage.totalWidth >> 1;
     this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
     
-    this.twoPage.bookCoverDivLeft = this.twoPage.coverExternalPadding; // $$$ Account for border?
-    this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding; // $$$ Account for border?
+    // The left edge of the book cover moves depending on the width of the pages
+    // $$$ change to getter
+    this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
+    // The top edge of the book cover stays a fixed distance from the top
+    this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
 
+    // Book spine
     this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
     this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
     this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
@@ -1024,24 +1588,25 @@ GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
     var canon5Dratio = 1.5;
     
     var first = {
-        height: this.getPageHeight(firstIndex),
-        width: this.getPageWidth(firstIndex)
+        height: this._getPageHeight(firstIndex),
+        width: this._getPageWidth(firstIndex)
     }
     
     var second = {
-        height: this.getPageHeight(secondIndex),
-        width: this.getPageWidth(secondIndex)
+        height: this._getPageHeight(secondIndex),
+        width: this._getPageWidth(secondIndex)
     }
     
     var firstIndexRatio  = first.height / first.width;
     var secondIndexRatio = second.height / second.width;
     //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
 
+    var ratio;
     if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
-        ideal.ratio = firstIndexRatio;
+        ratio = firstIndexRatio;
         //console.log('using firstIndexRatio ' + ratio);
     } else {
-        ideal.ratio = secondIndexRatio;
+        ratio = secondIndexRatio;
         //console.log('using secondIndexRatio ' + ratio);
     }
 
@@ -1049,51 +1614,82 @@ GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
     ideal.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
     
-    ideal.width  = ($('#GBcontainer').attr('clientWidth') - 30 - ideal.totalLeafEdgeWidth)>>1;
-    ideal.height = $('#GBcontainer').height() - 30;  // $$$ why - 30?  book edge width?
-    //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
+    var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
+    var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
+    
+    ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
+    ideal.width -= 10; // $$$ fudge factor
+    ideal.height = $('#GBcontainer').height() - heightOutsidePages;
+    ideal.height -= 20; // fudge factor
+    //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
 
-    if (ideal.height/ideal.ratio <= ideal.width) {
+    if (ideal.height/ratio <= ideal.width) {
         //use height
-        ideal.width = parseInt(ideal.height/ideal.ratio);
+        ideal.width = parseInt(ideal.height/ratio);
     } else {
         //use width
-        ideal.height = parseInt(ideal.width*ideal.ratio);
+        ideal.height = parseInt(ideal.width*ratio);
     }
     
-    // XXX check this logic with large spreads
+    // $$$ check this logic with large spreads
     ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
     
     return ideal;
 }
 
+// getSpreadSizeFromReduce()
+//______________________________________________________________________________
+// Returns the spread size calculated from the reduction factor for the given pages
 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
     var spreadSize = {};
     // $$$ Scale this based on reduce?
     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
-    var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
+    var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
     spreadSize.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
 
-    // $$$ this isn't quite right when the pages are different sizes
-    var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
-    var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
+    // $$$ Possibly incorrect -- we should make height "dominant"
+    var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
+    var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
     spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
     spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
     spreadSize.reduce = reduce;
     
-    // XXX
-    console.log('spread size: ' + firstIndex + ',' + secondIndex + ',' + reduce);
-
     return spreadSize;
 }
 
+// twoPageGetAutofitReduce()
+//______________________________________________________________________________
+// Returns the current ideal reduction factor
+GnuBook.prototype.twoPageGetAutofitReduce = function() {
+    var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
+    return spreadSize.reduce;
+}
+
+// twoPageSetCursor()
+//______________________________________________________________________________
+// Set the cursor for two page view
+GnuBook.prototype.twoPageSetCursor = function() {
+    // console.log('setting cursor');
+    if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
+         ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
+        $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
+        $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
+    } else {
+        $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
+        $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
+    }
+}
+
 // currentIndex()
 //______________________________________________________________________________
 // Returns the currently active index.
 GnuBook.prototype.currentIndex = function() {
     // $$$ we should be cleaner with our idea of which index is active in 1up/2up
-    if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
-        return this.firstIndex;
+    if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
+        return this.firstIndex; // $$$ TODO page in center of view would be better
+    } else if (this.mode == this.constMode2up) {
+        // Only allow indices that are actually present in book
+        return GnuBook.util.clamp(this.firstIndex, 0, this.numLeafs - 1);    
     } else {
         throw 'currentIndex called for unimplemented mode ' + this.mode;
     }
@@ -1174,34 +1770,22 @@ GnuBook.prototype.prev = function() {
 }
 
 GnuBook.prototype.first = function() {
-    if (2 == this.mode) {
-        this.jumpToIndex(2);
-    }
-    else {
-        this.jumpToIndex(0);
-    }
+    this.jumpToIndex(this.firstDisplayableIndex());
 }
 
 GnuBook.prototype.last = function() {
-    if (2 == this.mode) {
-        this.jumpToIndex(this.lastDisplayableIndex());
-    }
-    else {
-        this.jumpToIndex(this.lastDisplayableIndex());
-    }
+    this.jumpToIndex(this.lastDisplayableIndex());
 }
 
 // flipBackToIndex()
 //______________________________________________________________________________
 // to flip back one spread, pass index=null
 GnuBook.prototype.flipBackToIndex = function(index) {
+    
     if (1 == this.mode) return;
 
     var leftIndex = this.twoPage.currentIndexL;
     
-    // $$$ Need to change this to be able to see first spread.
-    //     See https://bugs.launchpad.net/gnubook/+bug/296788
-    if (leftIndex <= 2) return;
     if (this.animating) return;
 
     if (null != this.leafEdgeTmp) {
@@ -1216,19 +1800,16 @@ GnuBook.prototype.flipBackToIndex = function(index) {
     
     var previousIndices = this.getSpreadIndices(index);
     
-    if (previousIndices[0] < 0 || previousIndices[1] < 0) {
+    if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
         return;
     }
     
-    //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
-
     this.animating = true;
     
     if ('rl' != this.pageProgression) {
         // Assume LTR and we are going backward    
-        var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
-        this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
-        
+        this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
+        this.flipLeftToRight(previousIndices[0], previousIndices[1]);
     } else {
         // RTL and going backward
         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
@@ -1239,7 +1820,7 @@ GnuBook.prototype.flipBackToIndex = function(index) {
 // flipLeftToRight()
 //______________________________________________________________________________
 // Flips the page on the left towards the page on the right
-GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
+GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
 
     var leftLeaf = this.twoPage.currentIndexL;
     
@@ -1252,7 +1833,7 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
     var newWidthR    = this.getPageWidth2UP(newIndexR);
 
     var top  = this.twoPageTop();
-    var gutter = this.twoPageGutter();
+    var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
     
     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
@@ -1274,7 +1855,7 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
     //          and width=twoPage.edgeWidth-newLeafEdgeWidthL.
     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
     //          and width=newLeafEdgeWidthL.
-    //      - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
+    //      - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
     //          and width=newWidthL+newWidthR+twoPage.edgeWidth+20
     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
@@ -1309,18 +1890,15 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
     // Left gets the offset of the current left leaf from the document
     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
-    // XXX need to recalc
     var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
+    
     // We change the left leaf to right positioning
+    // $$$ This causes animation glitches during resize.  See https://bugs.edge.launchpad.net/gnubook/+bug/328327
     $(this.prefetchedImgs[leftLeaf]).css({
         right: right,
         left: ''
     });
 
-     left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
-     
-     right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
-
     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
     
@@ -1337,7 +1915,7 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
-
+            
             $(self.leafEdgeR).css({
                 // Moves the right leaf edge
                 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
@@ -1350,21 +1928,25 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
             });
 
-            
-            $(self.twoPageDiv).css({
-                // Resizes the brown border div
-                width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
-                left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
+            // Resizes the brown border div
+            $(self.twoPage.coverDiv).css({
+                width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
+                left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
             });
             
             $(self.leafEdgeTmp).remove();
             self.leafEdgeTmp = null;
+
+            // $$$ TODO refactor with opposite direction flip
             
             self.twoPage.currentIndexL = newIndexL;
             self.twoPage.currentIndexR = newIndexR;
+            self.twoPage.scaledWL = newWidthL;
+            self.twoPage.scaledWR = newWidthR;
+            self.twoPage.gutter = gutter;
+            
             self.firstIndex = self.twoPage.currentIndexL;
             self.displayedIndices = [newIndexL, newIndexR];
-            self.setClickHandlers();
             self.pruneUnusedImgs();
             self.prefetch();            
             self.animating = false;
@@ -1372,6 +1954,10 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
             self.updateSearchHilites2UP();
             self.updatePageNumBox2UP();
             
+            // self.twoPagePlaceFlipAreas(); // No longer used
+            self.setMouseHandlers2UP();
+            self.twoPageSetCursor();
+            
             if (self.animationFinishedCallback) {
                 self.animationFinishedCallback();
                 self.animationFinishedCallback = null;
@@ -1412,7 +1998,7 @@ GnuBook.prototype.flipFwdToIndex = function(index) {
     } else {
         // RTL
         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
-        this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
+        this.flipLeftToRight(nextIndices[0], nextIndices[1]);
     }
 }
 
@@ -1420,7 +2006,7 @@ GnuBook.prototype.flipFwdToIndex = function(index) {
 // $$$ better not to have to pass gutter in
 //______________________________________________________________________________
 // Flip from left to right and show the nextL and nextR indices on those sides
-GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
+GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
     var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
@@ -1428,16 +2014,12 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
 
     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
 
-    var top  = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;                
-
+    var top = this.twoPageTop();
     var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
 
-    var middle     = ($('#GBtwopageview').attr('clientWidth') >> 1);
-    var currGutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
+    var middle = this.twoPage.middle;
+    var gutter = middle + this.gutterOffsetForIndex(newIndexL);
     
-    // XXX
-    console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
-
     this.leafEdgeTmp = document.createElement('div');
     $(this.leafEdgeTmp).css({
         borderStyle: 'solid none solid solid',
@@ -1446,7 +2028,7 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
         width: leafEdgeTmpW + 'px',
         height: this.twoPage.height-1 + 'px',
-        left: currGutter+scaledW+'px',
+        left: gutter+scaledW+'px',
         top: top+'px',    
         position: 'absolute',
         zIndex:1000
@@ -1459,7 +2041,7 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
     var newWidthL = this.getPageWidth2UP(newIndexL);
     var newWidthR = this.getPageWidth2UP(newIndexR);
-
+    
     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
 
     var self = this; // closure-tastic!
@@ -1473,15 +2055,16 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
-
+            
             $(self.leafEdgeL).css({
                 width: newLeafEdgeWidthL+'px', 
                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
             });
             
-            $(self.twoPageDiv).css({
-                width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
-                left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
+            // Resizes the book cover
+            $(self.twoPage.coverDiv).css({
+                width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
+                left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
             });
             
             $(self.leafEdgeTmp).remove();
@@ -1489,9 +2072,12 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
             
             self.twoPage.currentIndexL = newIndexL;
             self.twoPage.currentIndexR = newIndexR;
+            self.twoPage.scaledWL = newWidthL;
+            self.twoPage.scaledWR = newWidthR;
+            self.twoPage.gutter = gutter;
+
             self.firstIndex = self.twoPage.currentIndexL;
             self.displayedIndices = [newIndexL, newIndexR];
-            self.setClickHandlers();            
             self.pruneUnusedImgs();
             self.prefetch();
             self.animating = false;
@@ -1500,6 +2086,10 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
             self.updateSearchHilites2UP();
             self.updatePageNumBox2UP();
             
+            // self.twoPagePlaceFlipAreas(); // No longer used
+            self.setMouseHandlers2UP();     
+            self.twoPageSetCursor();
+            
             if (self.animationFinishedCallback) {
                 self.animationFinishedCallback();
                 self.animationFinishedCallback = null;
@@ -1508,30 +2098,59 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
     });    
 }
 
-// setClickHandlers
+// setMouseHandlers2UP
 //______________________________________________________________________________
-GnuBook.prototype.setClickHandlers = function() {
-    var self = this;
-    // $$$ TODO don't set again if already set
-    $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
+GnuBook.prototype.setMouseHandlers2UP = function() {
+    /*
+    $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
         //self.prevPage();
         self.autoStop();
         self.left();
     });
-    $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
+    $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
         //self.nextPage();'
         self.autoStop();
         self.right();        
     });
+    */
+    
+    this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
+    this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
+        { self: this },
+        function(e) {
+            e.data.self.left();
+        }
+    );
+        
+    this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
+    this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
+        { self: this },
+        function(e) {
+            e.data.self.right();
+        }
+    );
 }
 
 // prefetchImg()
 //______________________________________________________________________________
 GnuBook.prototype.prefetchImg = function(index) {
-    if (undefined == this.prefetchedImgs[index]) {    
+    var pageURI = this._getPageURI(index);
+
+    // Load image if not loaded or URI has changed (e.g. due to scaling)
+    var loadImage = false;
+    if (undefined == this.prefetchedImgs[index]) {
+        //console.log('no image for ' + index);
+        loadImage = true;
+    } else if (pageURI != this.prefetchedImgs[index].uri) {
+        //console.log('uri changed for ' + index);
+        loadImage = true;
+    }
+    
+    if (loadImage) {
         //console.log('prefetching ' + index);
         var img = document.createElement("img");
-        img.src = this.getPageURI(index);
+        img.src = pageURI;
+        img.uri = pageURI; // browser may rewrite src so we stash raw URI here
         this.prefetchedImgs[index] = img;
     }
 }
@@ -1550,83 +2169,81 @@ GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
     this.prefetchImg(prevL);
     this.prefetchImg(prevR);
     
-    var height  = this.getPageHeight(prevL); 
-    var width   = this.getPageWidth(prevL);    
-    var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
-    var top  = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;                
-    var scaledW = this.twoPage.height*width/height;
+    var height  = this._getPageHeight(prevL); 
+    var width   = this._getPageWidth(prevL);    
+    var middle = this.twoPage.middle;
+    var top  = this.twoPageTop();                
+    var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
 
     // The gutter is the dividing line between the left and right pages.
     // It is offset from the middle to create the illusion of thickness to the pages
     var gutter = middle + this.gutterOffsetForIndex(prevL);
     
-    // XXX
-    console.log('    gutter for ' + prevL + ' is ' + gutter);
+    //console.log('    gutter for ' + prevL + ' is ' + gutter);
     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
     
-    $(this.prefetchedImgs[prevL]).css({
+    leftCSS = {
         position: 'absolute',
-        /*right:   middle+'px',*/
         left: gutter-scaledW+'px',
-        right: '',
+        right: '', // clear right property
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
         height: this.twoPage.height,
         width:  scaledW+'px',
+        backgroundColor: this.getPageBackgroundColor(prevL),
         borderRight: '1px solid black',
         zIndex: 1
-    });
+    }
+    
+    $(this.prefetchedImgs[prevL]).css(leftCSS);
 
     $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
 
     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
 
-    $(this.prefetchedImgs[prevR]).css({
+    rightCSS = {
         position: 'absolute',
         left:   gutter+'px',
         right: '',
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
         height: this.twoPage.height,
         width:  '0px',
+        backgroundColor: this.getPageBackgroundColor(prevR),
         borderLeft: '1px solid black',
         zIndex: 2
-    });
+    }
+    
+    $(this.prefetchedImgs[prevR]).css(rightCSS);
 
     $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
-
-
-    return gutter;
             
 }
 
-// XXXmang we're adding an extra pixel in the middle
+// $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
 // prepareFlipRightToLeft()
 //______________________________________________________________________________
 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
 
     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
 
+    // Prefetch images
     this.prefetchImg(nextL);
     this.prefetchImg(nextR);
 
-    var height  = this.getPageHeight(nextR); 
-    var width   = this.getPageWidth(nextR);    
-    var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
-    var top  = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;                
+    var height  = this._getPageHeight(nextR); 
+    var width   = this._getPageWidth(nextR);    
+    var middle = this.twoPage.middle;
+    var top  = this.twoPageTop();               
     var scaledW = this.twoPage.height*width/height;
 
     var gutter = middle + this.gutterOffsetForIndex(nextL);
-    
-    console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
-    
+        
     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
     $(this.prefetchedImgs[nextR]).css({
         position: 'absolute',
         left:   gutter+'px',
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
+        backgroundColor: this.getPageBackgroundColor(nextR),
         height: this.twoPage.height,
         width:  scaledW+'px',
         borderLeft: '1px solid black',
@@ -1635,8 +2252,8 @@ GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
 
     $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
 
-    height  = this.getPageHeight(nextL); 
-    width   = this.getPageWidth(nextL);      
+    height  = this._getPageHeight(nextL); 
+    width   = this._getPageWidth(nextL);      
     scaledW = this.twoPage.height*width/height;
 
     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
@@ -1644,16 +2261,14 @@ GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
         position: 'absolute',
         right:   $('#GBtwopageview').attr('clientWidth')-gutter+'px',
         top:    top+'px',
-        backgroundColor: 'rgb(234, 226, 205)',
+        backgroundColor: this.getPageBackgroundColor(nextL),
         height: this.twoPage.height,
-        width:  0+'px',
+        width:  0+'px', // Start at 0 width, then grow to the left
         borderRight: '1px solid black',
         zIndex: 2
     });
 
     $('#GBtwopageview').append(this.prefetchedImgs[nextL]);    
-
-    return gutter;
             
 }
 
@@ -1700,6 +2315,31 @@ GnuBook.prototype.pruneUnusedImgs = function() {
 //______________________________________________________________________________
 GnuBook.prototype.prefetch = function() {
 
+    // prefetch visible pages first
+    this.prefetchImg(this.twoPage.currentIndexL);
+    this.prefetchImg(this.twoPage.currentIndexR);
+    
+    var adjacentPagesToLoad = 3;
+    
+    var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
+    var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
+        
+    var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
+    var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
+    
+    // Load images spreading out from current
+    for (var i = 1; i <= adjacentPagesToLoad; i++) {
+        var goingDown = lowCurrent - i;
+        if (goingDown >= start) {
+            this.prefetchImg(goingDown);
+        }
+        var goingUp = highCurrent + i;
+        if (goingUp <= end) {
+            this.prefetchImg(goingUp);
+        }
+    }
+
+    /*
     var lim = this.twoPage.currentIndexL-4;
     var i;
     lim = Math.max(lim, 0);
@@ -1713,26 +2353,30 @@ GnuBook.prototype.prefetch = function() {
             this.prefetchImg(i);
         }
     }
+    */
 }
 
 // getPageWidth2UP()
 //______________________________________________________________________________
 GnuBook.prototype.getPageWidth2UP = function(index) {
     // We return the width based on the dominant height
-    var height  = this.getPageHeight(index); 
-    var width   = this.getPageWidth(index);    
+    var height  = this._getPageHeight(index); 
+    var width   = this._getPageWidth(index);    
     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
 }    
 
 // search()
 //______________________________________________________________________________
 GnuBook.prototype.search = function(term) {
+    term = term.replace(/\//g, ' '); // strip slashes
+    this.searchTerm = term;
     $('#GnuBookSearchScript').remove();
        var script  = document.createElement("script");
        script.setAttribute('id', 'GnuBookSearchScript');
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
        document.getElementsByTagName('head')[0].appendChild(script);
+       $('#GnuBookSearchBox').val(term);
        $('#GnuBookSearchResults').html('Searching...');
 }
 
@@ -1790,18 +2434,23 @@ GnuBook.prototype.GBSearchCallback = function(txt) {
                         //we'll skip baseline for now...
                         var coords = children[j].getAttribute('coords').split(',',4);
                         if (4 == coords.length) {
-                            this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
+                            this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
                         }
                     }
                 }
             }
             var pageName = this.getPageName(index);
+            var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
+            var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
             //TODO: remove hardcoded instance name
-            $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
+            $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
         }
     }
     $('#GnuBookSearchResults').append('</ul>');
 
+    // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
+       $('#GnuBookSearchBox').val(this.searchTerm);
+
     this.updateSearchHilites();
 }
 
@@ -1842,17 +2491,133 @@ GnuBook.prototype.updateSearchHilites1UP = function() {
     }
 }
 
-// XXX move, clean up, use everywhere
+// twoPageGutter()
+//______________________________________________________________________________
+// Returns the position of the gutter (line between the page images)
 GnuBook.prototype.twoPageGutter = function() {
-    var middle = ($('#GBtwopageview').width() >> 1);
-    return middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
+    return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
 }
 
-// XXX move, clean up, use everywhere
+// twoPageTop()
+//______________________________________________________________________________
+// Returns the offset for the top of the page images
 GnuBook.prototype.twoPageTop = function() {
     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
 }
-                        
+
+// twoPageCoverWidth()
+//______________________________________________________________________________
+// Returns the width of the cover div given the total page width
+GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
+    return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
+}
+
+// twoPageGetViewCenter()
+//______________________________________________________________________________
+// Returns the percentage offset into twopageview div at the center of container div
+// { percentageX: float, percentageY: float }
+GnuBook.prototype.twoPageGetViewCenter = function() {
+    var center = {};
+
+    var containerOffset = $('#GBcontainer').offset();
+    var viewOffset = $('#GBtwopageview').offset();
+    center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
+    center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
+    
+    return center;
+}
+
+// twoPageCenterView(percentageX, percentageY)
+//______________________________________________________________________________
+// Centers the point given by percentage from left,top of twopageview
+GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
+    if ('undefined' == typeof(percentageX)) {
+        percentageX = 0.5;
+    }
+    if ('undefined' == typeof(percentageY)) {
+        percentageY = 0.5;
+    }
+
+    var viewWidth = $('#GBtwopageview').width();
+    var containerClientWidth = $('#GBcontainer').attr('clientWidth');
+    var intoViewX = percentageX * viewWidth;
+    
+    var viewHeight = $('#GBtwopageview').height();
+    var containerClientHeight = $('#GBcontainer').attr('clientHeight');
+    var intoViewY = percentageY * viewHeight;
+    
+    if (viewWidth < containerClientWidth) {
+        // Can fit width without scrollbars - center by adjusting offset
+        $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
+    } else {
+        // Need to scroll to center
+        $('#GBtwopageview').css('left', 0);
+        $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
+    }
+    
+    if (viewHeight < containerClientHeight) {
+        // Fits with scrollbars - add offset
+        $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
+    } else {
+        $('#GBtwopageview').css('top', 0);
+        $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
+    }
+}
+
+// twoPageFlipAreaHeight
+//______________________________________________________________________________
+// Returns the integer height of the click-to-flip areas at the edges of the book
+GnuBook.prototype.twoPageFlipAreaHeight = function() {
+    return parseInt(this.twoPage.height);
+}
+
+// twoPageFlipAreaWidth
+//______________________________________________________________________________
+// Returns the integer width of the flip areas 
+GnuBook.prototype.twoPageFlipAreaWidth = function() {
+    var max = 100; // $$$ TODO base on view width?
+    var min = 10;
+    
+    var width = this.twoPage.width * 0.15;
+    return parseInt(GnuBook.util.clamp(width, min, max));
+}
+
+// twoPageFlipAreaTop
+//______________________________________________________________________________
+// Returns integer top offset for flip areas
+GnuBook.prototype.twoPageFlipAreaTop = function() {
+    return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
+}
+
+// twoPageLeftFlipAreaLeft
+//______________________________________________________________________________
+// Left offset for left flip area
+GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
+    return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
+}
+
+// twoPageRightFlipAreaLeft
+//______________________________________________________________________________
+// Left offset for right flip area
+GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
+    return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
+}
+
+// twoPagePlaceFlipAreas
+//______________________________________________________________________________
+// Readjusts position of flip areas based on current layout
+GnuBook.prototype.twoPagePlaceFlipAreas = function() {
+    // We don't set top since it shouldn't change relative to view
+    $(this.twoPage.leftFlipArea).css({
+        left: this.twoPageLeftFlipAreaLeft() + 'px',
+        width: this.twoPageFlipAreaWidth() + 'px'
+    });
+    $(this.twoPage.rightFlipArea).css({
+        left: this.twoPageRightFlipAreaLeft() + 'px',
+        width: this.twoPageFlipAreaWidth() + 'px'
+    });
+}
+    
 // showSearchHilites2UP()
 //______________________________________________________________________________
 GnuBook.prototype.updateSearchHilites2UP = function() {
@@ -1869,8 +2634,8 @@ GnuBook.prototype.updateSearchHilites2UP = function() {
 
             // We calculate the reduction factor for the specific page because it can be different
             // for each page in the spread
-            var height = this.getPageHeight(key);
-            var width  = this.getPageWidth(key)
+            var height = this._getPageHeight(key);
+            var width  = this._getPageWidth(key)
             var reduce = this.twoPage.height/height;
             var scaledW = parseInt(width*reduce);
             
@@ -1912,6 +2677,141 @@ GnuBook.prototype.removeSearchHilites = function() {
     }
 }
 
+// printPage
+//______________________________________________________________________________
+GnuBook.prototype.printPage = function() {
+    window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
+
+    /* iframe implementation
+
+    if (null != this.printPopup) { // check if already showing
+        return;
+    }
+    this.printPopup = document.createElement("div");
+    $(this.printPopup).css({
+        position: 'absolute',
+        top:      '20px',
+        left:     ($('#GBcontainer').width()-400)/2 + 'px',
+        width:    '400px',
+        padding:  "20px",
+        border:   "3px double #999999",
+        zIndex:   3,
+        backgroundColor: "#fff"
+    }).appendTo('#GnuBook');
+
+    var indexToPrint;
+    if (this.constMode1up == this.mode) {
+        indexToPrint = this.firstIndex;
+    } else {
+        indexToPrint = this.twoPage.currentIndexL;
+    }
+    
+    this.indexToPrint = indexToPrint;
+    
+    var htmlStr = '<div style="text-align: center;">';
+    htmlStr =  '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
+    htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
+    htmlStr +=   '<p style="text-align:right; margin: 0; font-size: 0.85em">';
+    //htmlStr +=     '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
+    //htmlStr +=     '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
+    htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
+    htmlStr +=   '</p>';
+    htmlStr += '</div>';
+    htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
+    htmlStr += '</div>';
+    
+    this.printPopup.innerHTML = htmlStr;
+    
+    var iframe = document.createElement('iframe');
+    iframe.id = 'printFrame';
+    iframe.name = 'printFrame';
+    iframe.width = '233px'; // 8.5 x 11 aspect
+    iframe.height = '300px';
+    
+    var self = this; // closure
+        
+    $(iframe).load(function() {
+        var doc = GnuBook.util.getIFrameDocument(this);
+        $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
+    });
+    
+    $('#printDiv').prepend(iframe);
+    */
+}
+
+// Get print URI from current indices and mode
+GnuBook.prototype.getPrintURI = function() {
+    var indexToPrint;
+    if (this.constMode2up == this.mode) {
+        indexToPrint = this.twoPage.currentIndexL;        
+    } else {
+        indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
+    }
+    
+    var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
+        + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
+        + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
+   
+    if (this.constMode2up == this.mode) {
+        options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
+        options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
+        options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
+    } else {
+        options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
+    }
+
+    return '/bookreader/print.php?' + options;
+}
+
+/* iframe implementation
+GnuBook.prototype.getPrintFrameContent = function(index) {    
+    // We fit the image based on an assumed A4 aspect ratio.  A4 is a bit taller aspect than
+    // 8.5x11 so we should end up not overflowing on either paper size.
+    var paperAspect = 8.5 / 11;
+    var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
+    
+    var rotate = 0;
+    
+    // Rotate if possible and appropriate, to get larger image size on printed page
+    if (this.canRotatePage(index)) {
+        if (imageAspect > 1 && imageAspect > paperAspect) {
+            // more wide than square, and more wide than paper
+            rotate = 90;
+            imageAspect = 1/imageAspect;
+        }
+    }
+    
+    var fitAttrs;
+    if (imageAspect > paperAspect) {
+        // wider than paper, fit width
+        fitAttrs = 'width="95%"';
+    } else {
+        // taller than paper, fit height
+        fitAttrs = 'height="95%"';
+    }
+
+    var imageURL = this._getPageURI(index, 1, rotate);
+    var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
+    iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
+    iframeStr +=   '<img src="' + imageURL + '" ' + fitAttrs + ' />';
+    iframeStr += '</div>';
+    iframeStr += '</body></html>';
+    
+    return iframeStr;
+}
+
+GnuBook.prototype.updatePrintFrame = function(delta) {
+    var newIndex = this.indexToPrint + delta;
+    newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
+    if (newIndex == this.indexToPrint) {
+        return;
+    }
+    this.indexToPrint = newIndex;
+    var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
+    $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
+}
+*/
+
 // showEmbedCode()
 //______________________________________________________________________________
 GnuBook.prototype.showEmbedCode = function() {
@@ -1951,6 +2851,11 @@ GnuBook.prototype.autoToggle = function() {
         bComingFrom1up = true;
         this.switchMode(2);
     }
+    
+    // Change to autofit if book is too large
+    if (this.reduce < this.twoPageGetAutofitReduce()) {
+        this.zoom2up(0);
+    }
 
     var self = this;
     if (null == this.autoTimer) {
@@ -1985,6 +2890,7 @@ GnuBook.prototype.autoToggle = function() {
 
 // autoStop()
 //______________________________________________________________________________
+// Stop autoplay mode, allowing animations to finish
 GnuBook.prototype.autoStop = function() {
     if (null != this.autoTimer) {
         clearInterval(this.autoTimer);
@@ -1995,6 +2901,31 @@ GnuBook.prototype.autoStop = function() {
     }
 }
 
+// stopFlipAnimations
+//______________________________________________________________________________
+// Immediately stop flip animations.  Callbacks are triggered.
+GnuBook.prototype.stopFlipAnimations = function() {
+
+    this.autoStop(); // Clear timers
+
+    // Stop animation, clear queue, trigger callbacks
+    if (this.leafEdgeTmp) {
+        $(this.leafEdgeTmp).stop(false, true);
+    }
+    jQuery.each(this.prefetchedImgs, function() {
+        $(this).stop(false, true);
+        });
+
+    // And again since animations also queued in callbacks
+    if (this.leafEdgeTmp) {
+        $(this.leafEdgeTmp).stop(false, true);
+    }
+    jQuery.each(this.prefetchedImgs, function() {
+        $(this).stop(false, true);
+        });
+   
+}
+
 // keyboardNavigationIsDisabled(event)
 //   - returns true if keyboard navigation should be disabled for the event
 //______________________________________________________________________________
@@ -2073,15 +3004,32 @@ GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
 
 GnuBook.prototype.initToolbar = function(mode, ui) {
 
-    $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
-        + "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
-        + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
-        + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
-        + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span>%</span>"
-        + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
-        + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
-        + "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
-        + "</span></div>");
+    $("#GnuBook").append("<div id='GBtoolbar'>"
+        + "<span id='GBtoolbarbuttons' style='float: right'>"
+        +   "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
+        +   "<form class='GBpageform' action='javascript:' onsubmit='gb.jumpToPage(this.elements[0].value)'> <span class='label'>Page:<input id='GBpagenum' type='text' size='3' onfocus='gb.autoStop();'></input></span></form>"
+        +   "<div class='GBtoolbarmode2' style='display: none'><button class='GBicon rollover book_leftmost' /><button class='GBicon rollover book_left' /><button class='GBicon rollover book_right' /><button class='GBicon rollover book_rightmost' /></div>"
+        +   "<div class='GBtoolbarmode1' style='display: none'><button class='GBicon rollover book_top' /><button class='GBicon rollover book_up' /> <button class='GBicon rollover book_down' /><button class='GBicon rollover book_bottom' /></div>"
+        +   "<div class='GBtoolbarmode3' style='display: none'><button class='GBicon rollover book_top' /><button class='GBicon rollover book_thumb_prev' /> <button class='GBicon rollover book_thumb_next' /><button class='GBicon rollover book_bottom' /></div>"
+        +   "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
+        + "</span>"
+        
+        + "<span>"
+        +   "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
+        +   "<div class='GBtoolbarzoom' style='display: none'><button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
+        +   "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
+        +   " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span></div>"
+        +   " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
+        +   " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
+        +   " <button class='GBicon rollover thumbnail_mode' onclick='gb.switchMode(3); return false;'/>"
+        + "</span>"
+        
+        + "<span id='#GBbooktitle'>"
+        +   "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
+        + "</span>"
+        + "</div>");
+    
+    this.updateToolbarZoom(this.reduce); // Pretty format
         
     if (ui == "embed") {
         $("#GnuBook a.logo").attr("target","_blank");
@@ -2091,12 +3039,7 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
     
     // We build in mode 2
-    jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
-        + "<button class='GBicon rollover embed' />"
-        + "<form class='GBpageform' action='javascript:' onsubmit='gb.jumpToPage(this.elements[0].value)'> <span class='label'>Page:<input id='GBpagenum' type='text' size='3' onfocus='gb.autoStop();'></input></span></form>"
-        + "<div class='GBtoolbarmode2' style='display: none'><button class='GBicon rollover book_leftmost' /><button class='GBicon rollover book_left' /><button class='GBicon rollover book_right' /><button class='GBicon rollover book_rightmost' /></div>"
-        + "<div class='GBtoolbarmode1' style='display: none'><button class='GBicon rollover book_top' /><button class='GBicon rollover book_up' /> <button class='GBicon rollover book_down' /><button class='GBicon rollover book_bottom' /></div>"
-        + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
+    jToolbar.append();
 
     this.bindToolbarNavHandlers(jToolbar);
     
@@ -2106,6 +3049,8 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
                    '.zoom_out': 'Zoom out',
                    '.one_page_mode': 'One-page view',
                    '.two_page_mode': 'Two-page view',
+                   '.thumbnail_mode': 'Thumbnail view',
+                   '.print': 'Print this page',
                    '.embed': 'Embed bookreader',
                    '.book_left': 'Flip left',
                    '.book_right': 'Flip right',
@@ -2114,7 +3059,9 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
                    '.play': 'Play',
                    '.pause': 'Pause',
                    '.book_top': 'First page',
-                   '.book_bottom': 'Last page'
+                   '.book_bottom': 'Last page',
+                   '.book_thumb_next': 'Next',
+                   '.book_thumb_prev': 'Previous'
                   };
     if ('rl' == this.pageProgression) {
         titles['.book_leftmost'] = 'Last page';
@@ -2136,7 +3083,7 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
 
     // Switch to requested mode -- binds other click handlers
     this.switchToolbarMode(mode);
-
+    
 }
 
 
@@ -2145,14 +3092,25 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
 // Update the toolbar for the given mode (changes navigation buttons)
 // $$$ we should soon split the toolbar out into its own module
 GnuBook.prototype.switchToolbarMode = function(mode) {
+              
     if (1 == mode) {
-        // 1-up     
+        // 1-up
+        $('#GBtoolbar .GBtoolbarzoom').show().css('display', 'inline');
         $('#GBtoolbar .GBtoolbarmode2').hide();
+        $('#GBtoolbar .GBtoolbarmode3').hide();
         $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
-    } else {
+    } else if (2 == mode) {
         // 2-up
+        $('#GBtoolbar .GBtoolbarzoom').show().css('display', 'inline');
         $('#GBtoolbar .GBtoolbarmode1').hide();
+        $('#GBtoolbar .GBtoolbarmode3').hide();
         $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
+    } else {
+        // 3-up    
+        $('#GBtoolbar .GBtoolbarzoom').hide();
+        $('#GBtoolbar .GBtoolbarmode2').hide();
+        $('#GBtoolbar .GBtoolbarmode1').hide();
+        $('#GBtoolbar .GBtoolbarmode3').show().css('display', 'inline');
     }
 }
 
@@ -2180,6 +3138,11 @@ GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
         gb.next();
         return false;
     });
+
+    jToolbar.find('.print').bind('click', function(e) {
+        gb.printPage();
+        return false;
+    });
         
     jToolbar.find('.embed').bind('click', function(e) {
         gb.showEmbedCode();
@@ -2215,14 +3178,33 @@ GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
         gb.rightmost();
         return false;
     });
+
+    jToolbar.find('.book_thumb_prev').bind('click', function(e) {
+        gb.prev();
+        return false;
+    });        
+        
+    jToolbar.find('.book_thumb_next').bind('click', function(e) {
+        gb.next();
+        return false;
+    });
 }
 
 // updateToolbarZoom(reduce)
 //______________________________________________________________________________
 // Update the displayed zoom factor based on reduction factor
 GnuBook.prototype.updateToolbarZoom = function(reduce) {
-    // $$$ TODO: Move toolbar to it's own object/plugin
-    $('#GBzoom').text(parseInt(100/reduce));
+    var value;
+    if (this.constMode2up == this.mode && this.twoPage.autofit) {
+        value = 'Auto';
+    } else {
+        value = (100 / reduce).toFixed(2);
+        // Strip trailing zeroes and decimal if all zeroes
+        value = value.replace(/0+$/,'');
+        value = value.replace(/\.$/,'');
+        value += '%';
+    }
+    $('#GBzoom').text(value);
 }
 
 // firstDisplayableIndex
@@ -2231,10 +3213,24 @@ GnuBook.prototype.updateToolbarZoom = function(reduce) {
 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
 GnuBook.prototype.firstDisplayableIndex = function() {
-    if (this.mode == 0) {
+    if (this.mode != this.constMode2up) {
         return 0;
+    }
+    
+    if ('rl' != this.pageProgression) {
+        // LTR
+        if (this.getPageSide(0) == 'L') {
+            return 0;
+        } else {
+            return -1;
+        }
     } else {
-        return 1; // $$$ we assume there are enough pages... we need logic for very short books
+        // RTL
+        if (this.getPageSide(0) == 'R') {
+            return 0;
+        } else {
+            return -1;
+        }
     }
 }
 
@@ -2244,21 +3240,27 @@ GnuBook.prototype.firstDisplayableIndex = function() {
 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
 GnuBook.prototype.lastDisplayableIndex = function() {
-    if (this.mode == 2) {
-        if (this.lastDisplayableIndex2up === null) {
-            // Calculate and cache
-            var candidate = this.numLeafs - 1;
-            for ( ; candidate >= 0; candidate--) {
-                var spreadIndices = this.getSpreadIndices(candidate);
-                if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
-                    break;
-                }
-            }
-            this.lastDisplayableIndex2up = candidate;
+
+    var lastIndex = this.numLeafs - 1;
+    
+    if (this.mode != this.constMode2up) {
+        return lastIndex;
+    }
+
+    if ('rl' != this.pageProgression) {
+        // LTR
+        if (this.getPageSide(lastIndex) == 'R') {
+            return lastIndex;
+        } else {
+            return lastIndex + 1;
         }
-        return this.lastDisplayableIndex2up;
     } else {
-        return this.numLeafs - 1;
+        // RTL
+        if (this.getPageSide(lastIndex) == 'L') {
+            return lastIndex;
+        } else {
+            return lastIndex + 1;
+        }
     }
 }
 
@@ -2275,8 +3277,6 @@ GnuBook.prototype.shortTitle = function(maximumCharacters) {
     return title;
 }
 
-
-
 // Parameter related functions
 
 // updateFromParams(params)
@@ -2289,7 +3289,13 @@ GnuBook.prototype.updateFromParams = function(params) {
         this.switchMode(params.mode);
     }
 
-    // $$$ process /search
+    // process /search
+    if ('undefined' != typeof(params.searchTerm)) {
+        if (this.searchTerm != params.searchTerm) {
+            this.search(params.searchTerm);
+        }
+    }
+    
     // $$$ process /zoom
     
     // We only respect page if index is not set
@@ -2315,7 +3321,7 @@ GnuBook.prototype.updateFromParams = function(params) {
 // E.g paramsFromFragment(window.location.hash)
 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
-    
+
     var params = {};
     
     // For convenience we allow an initial # character (as from window.location.hash)
@@ -2345,6 +3351,8 @@ GnuBook.prototype.paramsFromFragment = function(urlFragment) {
         params.mode = this.constMode1up;
     } else if ('2up' == urlHash['mode']) {
         params.mode = this.constMode2up;
+    } else if ('thumb' == urlHash['mode']) {
+        params.mode = this.constModeThumb;
     }
     
     // Index and page
@@ -2355,6 +3363,11 @@ GnuBook.prototype.paramsFromFragment = function(urlFragment) {
     
     // $$$ process /region
     // $$$ process /search
+    
+    if (urlHash['search'] != undefined) {
+        params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
+    }
+    
     // $$$ process /highlight
         
     return params;
@@ -2366,18 +3379,23 @@ GnuBook.prototype.paramsFromFragment = function(urlFragment) {
 GnuBook.prototype.paramsFromCurrent = function() {
 
     var params = {};
-
-    var pageNum = this.getPageNum(this.currentIndex());
+    
+    var index = this.currentIndex();
+    var pageNum = this.getPageNum(index);
     if ((pageNum === 0) || pageNum) {
         params.page = pageNum;
     }
     
-    params.index = this.currentIndex();
+    params.index = index;
     params.mode = this.mode;
     
     // $$$ highlight
     // $$$ region
-    // $$$ search
+
+    // search    
+    if (this.searchHighlightVisible()) {
+        params.searchTerm = this.searchTerm;
+    }
     
     return params;
 }
@@ -2388,7 +3406,7 @@ GnuBook.prototype.paramsFromCurrent = function() {
 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
 GnuBook.prototype.fragmentFromParams = function(params) {
     var separator = '/';
-    
+
     var fragments = [];
     
     if ('undefined' != typeof(params.page)) {
@@ -2400,7 +3418,6 @@ GnuBook.prototype.fragmentFromParams = function(params) {
     
     // $$$ highlight
     // $$$ region
-    // $$$ search
     
     // mode
     if ('undefined' != typeof(params.mode)) {    
@@ -2408,12 +3425,19 @@ GnuBook.prototype.fragmentFromParams = function(params) {
             fragments.push('mode', '1up');
         } else if (params.mode == this.constMode2up) {
             fragments.push('mode', '2up');
+        } else if (params.mode == this.constModeThumb) {
+            fragments.push('mode', 'thumb');
         } else {
             throw 'fragmentFromParams called with unknown mode ' + params.mode;
         }
     }
     
-    return fragments.join(separator);
+    // search
+    if (params.searchTerm) {
+        fragments.push('search', params.searchTerm);
+    }
+    
+    return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
 }
 
 // getPageIndex(pageNum)
@@ -2440,7 +3464,7 @@ GnuBook.prototype.getPageIndices = function(pageNum) {
         try {
             var pageIntStr = pageNum.slice(1, pageNum.length);
             var pageIndex = parseInt(pageIntStr);
-            indices.append(pageIndex);
+            indices.push(pageIndex);
             return indices;
         } catch(err) {
             // Do nothing... will run through page names and see if one matches
@@ -2510,21 +3534,6 @@ GnuBook.prototype.startLocationPolling = function() {
     }, 500);
 }
 
-// getEmbedURL
-//________
-// Returns a URL for an embedded version of the current book
-GnuBook.prototype.getEmbedURL = function() {
-    // We could generate a URL hash fragment here but for now we just leave at defaults
-    return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
-}
-
-// getEmbedCode
-//________
-// Returns the embed code HTML fragment suitable for copy and paste
-GnuBook.prototype.getEmbedCode = function() {
-    return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
-}
-
 // canSwitchToMode
 //________
 // Returns true if we can switch to the requested mode
@@ -2541,9 +3550,86 @@ GnuBook.prototype.canSwitchToMode = function(mode) {
     return true;
 }
 
+// searchHighlightVisible
+//________
+// Returns true if a search highlight is currently being displayed
+GnuBook.prototype.searchHighlightVisible = function() {
+    if (this.constMode2up == this.mode) {
+        if (this.searchResults[this.twoPage.currentIndexL]
+                || this.searchResults[this.twoPage.currentIndexR]) {
+            return true;
+        }
+    } else { // 1up
+        if (this.searchResults[this.currentIndex()]) {
+            return true;
+        }
+    }
+    return false;
+}
+
+// getPageBackgroundColor
+//--------
+// Returns a CSS property string for the background color for the given page
+// $$$ turn into regular CSS?
+GnuBook.prototype.getPageBackgroundColor = function(index) {
+    if (index >= 0 && index < this.numLeafs) {
+        // normal page
+        return this.pageDefaultBackgroundColor;
+    }
+    
+    return '';
+}
+
+// _getPageWidth
+//--------
+// Returns the page width for the given index, or first or last page if out of range
+GnuBook.prototype._getPageWidth = function(index) {
+    // Synthesize a page width for pages not actually present in book.
+    // May or may not be the best approach.
+    // If index is out of range we return the width of first or last page
+    index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
+    return this.getPageWidth(index);
+}
+
+// _getPageHeight
+//--------
+// Returns the page height for the given index, or first or last page if out of range
+GnuBook.prototype._getPageHeight= function(index) {
+    index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
+    return this.getPageHeight(index);
+}
+
+// _getPageURI
+//--------
+// Returns the page URI or transparent image if out of range
+GnuBook.prototype._getPageURI = function(index, reduce, rotate) {
+    if (index < 0 || index >= this.numLeafs) { // Synthesize page
+        return this.imagesBaseURL + "/transparent.png";
+    }
+    
+    return this.getPageURI(index, reduce, rotate);
+}
+
 // Library functions
 GnuBook.util = {
     clamp: function(value, min, max) {
         return Math.min(Math.max(value, min), max);
+    },
+
+    getIFrameDocument: function(iframe) {
+        // Adapted from http://xkr.us/articles/dom/iframe-document/
+        var outer = (iframe.contentWindow || iframe.contentDocument);
+        return (outer.document || outer);
+    },
+    
+    decodeURIComponentPlus: function(value) {
+        // Decodes a URI component and converts '+' to ' '
+        return decodeURIComponent(value).replace(/\+/g, ' ');
+    },
+    
+    encodeURIComponentPlus: function(value) {
+        // Encodes a URI component and converts ' ' to '+'
+        return encodeURIComponent(value).replace(/%20/g, '+');
     }
-}
\ No newline at end of file
+    // The final property here must NOT have a comma after it - IE7
+}