Cleanup tabs in thumbnail feature for code guidelines
[bookreader.git] / GnuBook / GnuBook.js
index 72062ab..a654b5c 100644 (file)
@@ -24,19 +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().
 
 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
@@ -68,6 +76,7 @@ function GnuBook() {
     // Mode constants
     this.constMode1up = 1;
     this.constMode2up = 2;
+    this.constModeThumb = 3;
     
     // Zoom levels
     this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
@@ -90,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);
@@ -144,6 +154,8 @@ 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');
             
@@ -178,6 +190,10 @@ GnuBook.prototype.init = function() {
         this.resizePageView();
         this.firstIndex = startIndex;
         this.jumpToIndex(startIndex);
+    } else if (3 == this.mode) {
+        this.firstIndex = startIndex;
+        this.prepareThumbnailView();
+        this.jumpToIndex(startIndex);
     } else {
         //this.resizePageView();
         
@@ -257,6 +273,8 @@ GnuBook.prototype.setupKeyListeners = function() {
 GnuBook.prototype.drawLeafs = function() {
     if (1 == this.mode) {
         this.drawLeafsOnePage();
+    } else if(3 == this.mode) {
+        this.drawLeafsThumbnail();
     } else {
         this.drawLeafsTwoPage();
     }
@@ -438,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));
@@ -476,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
@@ -485,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';
@@ -507,7 +525,7 @@ GnuBook.prototype.drawLeafsOnePage = function() {
             $('#GBpageview').append(div);
 
             var img = document.createElement("img");
-            img.src = this.getPageURI(index, this.reduce, 0);
+            img.src = this._getPageURI(index, this.reduce, 0);
             $(img).css('width', width+'px');
             $(img).css('height', height+'px');
             $(div).append(img);
@@ -544,6 +562,172 @@ 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() {
@@ -554,8 +738,8 @@ GnuBook.prototype.drawLeafsTwoPage = function() {
     
     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;
@@ -584,8 +768,8 @@ GnuBook.prototype.drawLeafsTwoPage = function() {
     }).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;
@@ -656,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;
@@ -670,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()
@@ -678,6 +864,11 @@ GnuBook.prototype.zoom1up = function(dir) {
     this.loadLeafs();
     
     this.updateToolbarZoom(this.reduce);
+    
+    // Recalculate search hilites
+    this.removeSearchHilites(); 
+    this.updateSearchHilites();
+
 }
 
 // resizePageView()
@@ -703,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);
@@ -724,6 +915,9 @@ GnuBook.prototype.resizePageView = function() {
     //this.centerPageView();
     this.loadLeafs();
     
+    // Not really needed until there is 1up autofit
+    this.removeSearchHilites();
+    this.updateSearchHilites();
 }
 
 // centerX1up()
@@ -775,6 +969,7 @@ GnuBook.prototype.zoom2up = function(direction) {
     }
     this.twoPage.autofit = newZoom.autofit;
     this.reduce = newZoom.reduce;
+    this.pageScale = this.reduce; // preserve current reduce
 
     // Preserve view center position
     var oldCenter = this.twoPageGetViewCenter();
@@ -882,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();
@@ -895,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) {
@@ -926,15 +1167,21 @@ 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);
@@ -977,6 +1224,38 @@ GnuBook.prototype.prepareOnePageView = function() {
     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
+    gbPageView[0].onselectstart = function(e) { return false; };
+}
+
 // prepareTwoPageView()
 //______________________________________________________________________________
 // Some decisions about two page view:
@@ -1148,10 +1427,13 @@ GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercent
     //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
     
     this.drawLeafsTwoPage();
-    this.updateSearchHilites2UP();
     this.updateToolbarZoom(this.reduce);
     
     this.prefetch();
+
+    this.removeSearchHilites();
+    this.updateSearchHilites();
+
 }
 
 // prepareTwoPagePopUp()
@@ -1306,13 +1588,13 @@ 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;
@@ -1366,8 +1648,8 @@ GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, re
     spreadSize.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
 
     // $$$ Possibly incorrect -- we should make height "dominant"
-    var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
-    var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
+    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;
@@ -1403,7 +1685,7 @@ GnuBook.prototype.twoPageSetCursor = function() {
 // 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) {
+    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
@@ -1852,7 +2134,7 @@ GnuBook.prototype.setMouseHandlers2UP = function() {
 // prefetchImg()
 //______________________________________________________________________________
 GnuBook.prototype.prefetchImg = function(index) {
-    var pageURI = this.getPageURI(index);
+    var pageURI = this._getPageURI(index);
 
     // Load image if not loaded or URI has changed (e.g. due to scaling)
     var loadImage = false;
@@ -1887,8 +2169,8 @@ GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
     this.prefetchImg(prevL);
     this.prefetchImg(prevR);
     
-    var height  = this.getPageHeight(prevL); 
-    var width   = this.getPageWidth(prevL);    
+    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
@@ -1948,8 +2230,8 @@ GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
     this.prefetchImg(nextL);
     this.prefetchImg(nextR);
 
-    var height  = this.getPageHeight(nextR); 
-    var width   = this.getPageWidth(nextR);    
+    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;
@@ -1970,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);
@@ -2078,8 +2360,8 @@ GnuBook.prototype.prefetch = function() {
 //______________________________________________________________________________
 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
 }    
 
@@ -2152,14 +2434,16 @@ 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>');
@@ -2350,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);
             
@@ -2466,11 +2750,11 @@ GnuBook.prototype.getPrintURI = function() {
     
     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);
+        + '&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 += '&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));
@@ -2484,7 +2768,7 @@ 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 imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
     
     var rotate = 0;
     
@@ -2506,7 +2790,7 @@ GnuBook.prototype.getPrintFrameContent = function(index) {
         fitAttrs = 'height="95%"';
     }
 
-    var imageURL = this.getPageURI(index, 1, rotate);
+    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 + ' />';
@@ -2726,16 +3010,18 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
         +   "<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>"
-        +   " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
+        +   "<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>"
+        +   " <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'>"
@@ -2763,6 +3049,7 @@ 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',
@@ -2772,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';
@@ -2803,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');
     }
 }
 
@@ -2878,6 +3178,16 @@ 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)
@@ -3011,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)
@@ -3041,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
@@ -3094,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)) {
@@ -3113,6 +3425,8 @@ 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;
         }
@@ -3266,6 +3580,36 @@ GnuBook.prototype.getPageBackgroundColor = function(index) {
     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) {