Added icon toggle button for thumbnail mode
[bookreader.git] / GnuBook / GnuBook.js
index 607c0b4..e55d997 100644 (file)
@@ -66,6 +66,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];
@@ -138,6 +139,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');
             
@@ -164,14 +167,19 @@ GnuBook.prototype.init = function() {
     });
     
     $('.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 {
+    } else if (3 == this.mode) {
+               this.firstIndex = startIndex;
+               this.jumpToIndex(startIndex);
+               this.prepareThumbnailView();
+       } else {
         //this.resizePageView();
         
         this.displayedIndices=[0];
@@ -188,7 +196,7 @@ GnuBook.prototype.init = function() {
 
 GnuBook.prototype.setupKeyListeners = function() {
     var self = this;
-
+    
     var KEY_PGUP = 33;
     var KEY_PGDOWN = 34;
     var KEY_END = 35;
@@ -201,41 +209,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;
@@ -248,17 +263,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;
@@ -270,11 +289,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;
@@ -287,22 +307,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;
     });
 }
 
@@ -387,7 +510,7 @@ GnuBook.prototype.drawLeafsOnePage = function() {
             $(div).css('height', height+'px');
             //$(div).text('loading...');
             
-            this.setDragHandler1up(div);
+            this.setDragHandler(div);
             
             $('#GBpageview').append(div);
 
@@ -429,6 +552,139 @@ GnuBook.prototype.drawLeafsOnePage = function() {
     
 }
 
+// drawLeafsThumbnail()
+//______________________________________________________________________________
+GnuBook.prototype.drawLeafsThumbnail = function() {
+    //alert('drawing leafs!');
+    this.timer = null;
+
+
+    var scrollTop = $('#GBcontainer').attr('scrollTop');
+    var scrollBottom = scrollTop + $('#GBcontainer').height();
+    //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
+    
+    var indicesToDisplay = [];
+    
+    var i;
+    var leafTop = 0;
+    var leafBottom = 0;
+       var viewHeight = 0;
+       var width = 0;
+    for (i=0; i<this.numLeafs; i++) {
+        var height  = parseInt(this.getPageHeight(i)/this.thumbScale); 
+    
+        leafBottom += height;
+        //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
+        var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
+        var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
+        var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
+        if (topInView | bottomInView | middleInView) {
+            //console.log('displayed: ' + this.displayedIndices);
+            //console.log('to display: ' + i);
+            indicesToDisplay.push(i);
+        }
+        leafTop += height +10;      
+        leafBottom += 10;
+    }
+
+    var firstIndexToDraw  = indicesToDisplay[0];
+    this.firstIndex      = firstIndexToDraw;
+    
+    // Update hash, but only if we're currently displaying a leaf
+    // Hack that fixes #365790
+    if (this.displayedIndices.length > 0) {
+        this.updateLocationHash();
+    }
+
+    if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
+        firstIndexToDraw--;
+        indicesToDisplay.unshift(firstIndexToDraw);
+    }
+    
+    var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
+    if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
+        indicesToDisplay.push(lastIndexToDraw+1);
+    }
+    
+    leafTop = 0;
+    var i;
+    for (i=0; i<firstIndexToDraw; i++) {
+        leafTop += parseInt(this.getPageHeight(i)/this.thumbScale) +10;
+    }
+
+    //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
+    var viewWidth = $('#GBcontainer').attr('scrollWidth');
+
+
+    for (i=0; i<indicesToDisplay.length; i++) {
+        var index = indicesToDisplay[i];    
+        var height  = parseInt(this.getPageHeight(index)/this.thumbScale); 
+
+        if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
+            var width   = parseInt(this.getPageWidth(index)/this.thumbScale); 
+            //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
+            var div = document.createElement("div");
+            div.className = 'GBpagediv1up';
+            div.id = 'pagediv'+index;
+            div.style.position = "absolute";
+            $(div).css('top', leafTop + 'px');
+            var left = (viewWidth-width)>>1;
+            if (left<0) left = 0;
+            $(div).css('left', left+'px');
+            $(div).css('width', width+'px');
+            $(div).css('height', height+'px');
+            //$(div).text('loading...');
+
+                       // thumbnails are hyperlinked, do not need drag handler
+            //this.setDragHandler(div);
+            
+                       // link to page in single page mode
+                       var link = document.createElement("a");
+                       link.href = '#page/' + (this.getPageNum(index)) +'/mode/1up' ;
+            $(div).append(link);
+
+            $('#GBpageview').append(div);
+
+            var img = document.createElement("img");
+            img.src = this.getPageURI(index);
+            $(img).css('width', width+'px');
+            $(img).css('height', height+'px');
+                       img.style.border = "0";
+            $(link).append(img);
+
+
+        } else {
+            //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));            
+        }
+
+        leafTop += height +10;
+
+    }
+    
+    for (i=0; i<this.displayedIndices.length; i++) {
+        if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
+            var index = this.displayedIndices[i];
+            //console.log('Removing leaf ' + index);
+            //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
+            $('#pagediv'+index).remove();
+        } else {
+            //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
+        }
+    }
+    
+    this.displayedIndices = indicesToDisplay.slice();
+    this.updateSearchHilites();
+    
+    if (null != this.getPageNum(firstIndexToDraw))  {
+        $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
+    } else {
+        $("#GBpagenum").val('');
+    }
+            
+    this.updateToolbarZoom(this.reduce);
+    
+}
+
 // drawLeafsTwoPage()
 //______________________________________________________________________________
 GnuBook.prototype.drawLeafsTwoPage = function() {
@@ -451,49 +707,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
@@ -531,6 +790,8 @@ GnuBook.prototype.zoom = function(direction) {
             return this.zoom1up(direction);
         case this.constMode2up:
             return this.zoom2up(direction);
+        case this.constModeThumb:
+            return this.zoomThumb(direction);
     }
 }
 
@@ -561,6 +822,15 @@ GnuBook.prototype.zoom1up = function(dir) {
     this.updateToolbarZoom(this.reduce);
 }
 
+// zoomThumb(dir)
+//______________________________________________________________________________
+GnuBook.prototype.zoomThumb = function(dir) {
+    if (3 == this.mode) {     //can only zoom in 1-page mode
+        this.switchMode(1);
+        return;
+    }
+}
+
 // resizePageView()
 //______________________________________________________________________________
 GnuBook.prototype.resizePageView = function() {
@@ -660,6 +930,14 @@ GnuBook.prototype.zoom2up = function(direction) {
     // 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);
 }
@@ -672,10 +950,10 @@ 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 - reductionFactors[i]);
+        newDistance = Math.abs(reduce - this.reductionFactors[i]);
         if (newDistance < distance) {
             distance = newDistance;
-            quantized = reductionFactors[i];
+            quantized = this.reductionFactors[i];
         }
     }
     
@@ -802,12 +1080,20 @@ GnuBook.prototype.switchMode = function(mode) {
     
     this.switchToolbarMode(mode);
     
+    // $$$ TODO preserve center of view when switching between mode
+    //     See https://bugs.edge.launchpad.net/gnubook/+bug/416682
+    
     if (1 == mode) {
-        this.reduce = this.twoPageQuantizeReduce(this.reduce);
+        this.reduce = this.quantizeReduce(this.reduce);
         this.prepareOnePageView();
+    } else if (3 == mode) {
+           this.reduce = this.quantizeReduce(this.reduce);
+        this.prepareThumbnailView();
     } 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
     }
 
 }
@@ -837,6 +1123,41 @@ 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();
+    
+    $('#GBcontainer').empty();
+    $('#GBcontainer').css({
+        overflowY: 'scroll',
+        overflowX: 'auto'
+    });
+    
+    var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
+    
+    this.resizePageView();
+    
+    this.jumpToIndex(startLeaf);
+    this.displayedIndices = [];
+    
+    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
@@ -874,17 +1195,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
@@ -964,9 +1288,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];
@@ -1055,10 +1417,6 @@ GnuBook.prototype.prepareTwoPagePopUp = function() {
 
 GnuBook.prototype.calculateSpreadSize = function() {
 
-    // $$$ 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);
@@ -1081,9 +1439,9 @@ GnuBook.prototype.calculateSpreadSize = function() {
     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;
-    this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
     
     
     // Book cover
@@ -1097,8 +1455,8 @@ GnuBook.prototype.calculateSpreadSize = function() {
     // 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 leftWidthFromCenter = this.twoPage.scaledWL + leftGutterOffset + this.twoPage.leafEdgeWidthL;
-    var rightWidthFromCenter = this.twoPage.scaledWR - leftGutterOffset + this.twoPage.leafEdgeWidthR;
+    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);
@@ -1161,8 +1519,13 @@ 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?
+    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/ratio <= ideal.width) {
@@ -1207,12 +1570,27 @@ GnuBook.prototype.twoPageGetAutofitReduce = function() {
     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) {
+    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;
@@ -1474,12 +1852,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.pruneUnusedImgs();
             self.prefetch();            
             self.animating = false;
@@ -1487,6 +1870,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;
@@ -1601,9 +1988,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.pruneUnusedImgs();
             self.prefetch();
             self.animating = false;
@@ -1612,6 +2002,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;
@@ -1620,30 +2014,59 @@ GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
     });    
 }
 
-// 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;
     }
 }
@@ -1804,6 +2227,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);
@@ -1817,6 +2265,7 @@ GnuBook.prototype.prefetch = function() {
             this.prefetchImg(i);
         }
     }
+    */
 }
 
 // getPageWidth2UP()
@@ -2018,6 +2467,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()
 //______________________________________________________________________________
@@ -2274,11 +2777,14 @@ GnuBook.prototype.initToolbar = function(mode, ui) {
         + "<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>"
+        + " <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(this.reduce); // Pretty format
         
     if (ui == "embed") {
         $("#GnuBook a.logo").attr("target","_blank");
@@ -2303,6 +2809,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',
@@ -2418,8 +2925,17 @@ GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
 //______________________________________________________________________________
 // 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
@@ -2542,6 +3058,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
@@ -2605,6 +3123,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;
         }