Add the functionality of a thumbnail view
[bookreader.git] / GnuBook / GnuBook.js
index b5ce47e..1700035 100644 (file)
@@ -33,10 +33,12 @@ This file is part of GnuBook.
 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.displayedIndices = [];        
+       this.displayedRows=[];
     //this.indicesToDisplay = [];
     this.imgs = {};
     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
@@ -50,7 +52,7 @@ function GnuBook() {
     this.twoPagePopUp = null;
     this.leafEdgeTmp  = null;
     this.embedPopup = null;
-    
+
     this.searchResults = {};
     
     this.firstIndex = null;
@@ -66,6 +68,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];
@@ -84,6 +87,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);
@@ -138,6 +142,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');
             
@@ -172,7 +178,11 @@ GnuBook.prototype.init = function() {
         this.resizePageView();
         this.firstIndex = startIndex;
         this.jumpToIndex(startIndex);
-    } else {
+    } else if (3 == this.mode) {
+               this.firstIndex = startIndex;
+               this.prepareThumbnailView();
+               this.jumpToIndex(startIndex);
+       } else {
         //this.resizePageView();
         
         this.displayedIndices=[0];
@@ -189,7 +199,7 @@ GnuBook.prototype.init = function() {
 
 GnuBook.prototype.setupKeyListeners = function() {
     var self = this;
-
+    
     var KEY_PGUP = 33;
     var KEY_PGDOWN = 34;
     var KEY_END = 35;
@@ -202,41 +212,48 @@ 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) {
+                    e.preventDefault();
                     self.prev();
                 }
                 break;
             case KEY_DOWN:
             case KEY_PGDOWN:
                 if (2 == self.mode) {
+                    e.preventDefault();
                     self.next();
                 }
                 break;
             case KEY_END:
+                e.preventDefault();
                 self.last();
                 break;
             case KEY_HOME:
+                e.preventDefault();
                 self.first();
                 break;
             case KEY_LEFT:
                 if (self.keyboardNavigationIsDisabled(e)) {
+                    e.preventDefault();
                     break;
                 }
                 if (2 == self.mode) {
+                    e.preventDefault();
                     self.left();
                 }
                 break;
             case KEY_RIGHT:
                 if (self.keyboardNavigationIsDisabled(e)) {
+                    e.preventDefault();
                     break;
                 }
                 if (2 == self.mode) {
+                    e.preventDefault();
                     self.right();
                 }
                 break;
@@ -249,6 +266,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();
     }
@@ -259,7 +278,9 @@ GnuBook.prototype.drawLeafs = function() {
 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;
@@ -271,11 +292,12 @@ GnuBook.prototype.setDragHandler = 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;
@@ -288,27 +310,125 @@ GnuBook.prototype.setDragHandler = 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);
     
-    $(div).bind('mouseenter', function(e) {
-        // On FF/OSX we don't always receive the mouseleave event
+    $(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;
     });
 }
 
@@ -435,6 +555,175 @@ 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];
+       var rowBuffer = 4;
+       for (i=1; i<rowBuffer+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() {
@@ -457,50 +746,52 @@ GnuBook.prototype.drawLeafsTwoPage = function() {
     var top = this.twoPageTop();
     var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
 
-    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)',
         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);
 
     // $$$ 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)',
         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
@@ -558,7 +849,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()
@@ -663,10 +955,19 @@ 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();
     
+    // 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);
 }
@@ -775,7 +1076,38 @@ 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 h;
@@ -806,15 +1138,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);
+        this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
     }
 
 }
@@ -852,6 +1195,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:
@@ -883,17 +1258,20 @@ GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercent
         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
-        
+    this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
+
+    this.pruneUnusedImgs();
+    this.prefetch(); // Preload images or reload if scaling has changed
+
     //console.dir(this.twoPage);
     
     // Add the two page view
@@ -973,9 +1351,47 @@ GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercent
         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];
@@ -1169,9 +1585,9 @@ GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
     var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
     var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
     
-    ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
+    ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
     ideal.width -= 10; // $$$ fudge factor
-    ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
+    ideal.height = $('#GBcontainer').height() - heightOutsidePages;
     ideal.height -= 20; // fudge factor
     //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
 
@@ -1237,7 +1653,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 || this.mode == this.constMode2up) {
+    if (this.mode == this.constMode1up || this.mode == this.constMode2up || this.mode == this.constModeThumb) {
         return this.firstIndex;
     } else {
         throw 'currentIndex called for unimplemented mode ' + this.mode;
@@ -1499,13 +1915,17 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
             
             $(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.twoPageSetCursor();
             self.pruneUnusedImgs();
             self.prefetch();            
             self.animating = false;
@@ -1513,6 +1933,10 @@ GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
             self.updateSearchHilites2UP();
             self.updatePageNumBox2UP();
             
+            // self.twoPagePlaceFlipAreas(); // No longer used
+            self.setMouseHandlers2UP();
+            self.twoPageSetCursor();
+            
             if (self.animationFinishedCallback) {
                 self.animationFinishedCallback();
                 self.animationFinishedCallback = null;
@@ -1627,10 +2051,12 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
             
             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.twoPageSetCursor();
             self.pruneUnusedImgs();
             self.prefetch();
             self.animating = false;
@@ -1639,6 +2065,10 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
             self.updateSearchHilites2UP();
             self.updatePageNumBox2UP();
             
+            // self.twoPagePlaceFlipAreas(); // No longer used
+            self.setMouseHandlers2UP();     
+            self.twoPageSetCursor();
+            
             if (self.animationFinishedCallback) {
                 self.animationFinishedCallback();
                 self.animationFinishedCallback = null;
@@ -1647,11 +2077,10 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
     });    
 }
 
-// setClickHandlers
+// setMouseHandlers2UP
 //______________________________________________________________________________
-GnuBook.prototype.setClickHandlers = function() {
-    var self = this;
-    // $$$ TODO don't set again if already set
+GnuBook.prototype.setMouseHandlers2UP = function() {
+    /*
     $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
         //self.prevPage();
         self.autoStop();
@@ -1662,18 +2091,45 @@ GnuBook.prototype.setClickHandlers = function() {
         self.autoStop();
         self.right();        
     });
+    */
     
-    this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
-    this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
+    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;
     }
 }
@@ -1834,6 +2290,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);
@@ -1847,6 +2328,7 @@ GnuBook.prototype.prefetch = function() {
             this.prefetchImg(i);
         }
     }
+    */
 }
 
 // getPageWidth2UP()
@@ -2048,6 +2530,60 @@ GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
         $('#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()
 //______________________________________________________________________________
@@ -2307,10 +2843,11 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
         + " <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;'/>"
+               + " <button class='GBicon rollover thumbnail_mode' onclick='gb.switchMode(3); return false;'/>"
         + "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
         + "</span></div>");
     
-    this.updateToolbarZoom(); // Pretty format
+    this.updateToolbarZoom(this.reduce); // Pretty format
         
     if (ui == "embed") {
         $("#GnuBook a.logo").attr("target","_blank");
@@ -2335,6 +2872,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',
                    '.embed': 'Embed bookreader',
                    '.book_left': 'Flip left',
                    '.book_right': 'Flip right',
@@ -2451,7 +2989,7 @@ GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
 // Update the displayed zoom factor based on reduction factor
 GnuBook.prototype.updateToolbarZoom = function(reduce) {
     var value;
-    if (this.twoPage.autofit) {
+    if (this.constMode2up == this.mode && this.twoPage.autofit) {
         value = 'Auto';
     } else {
         value = (100 / reduce).toFixed(2);
@@ -2553,7 +3091,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)
@@ -2583,6 +3121,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
@@ -2626,7 +3166,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)) {
@@ -2646,6 +3186,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;
         }