b5ce47e9046fb07a7130fd13ba02a436928050a5
[bookreader.git] / GnuBook / GnuBook.js
1 /*
2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
3
4 This file is part of GnuBook.
5
6     GnuBook is free software: you can redistribute it and/or modify
7     it under the terms of the GNU Affero General Public License as published by
8     the Free Software Foundation, either version 3 of the License, or
9     (at your option) any later version.
10
11     GnuBook is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU Affero General Public License for more details.
15
16     You should have received a copy of the GNU Affero General Public License
17     along with GnuBook.  If not, see <http://www.gnu.org/licenses/>.
18     
19     The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
20
21     archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
22 */
23
24 // GnuBook()
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
28 //  - getPageWidth()
29 //  - getPageHeight()
30 //  - getPageURI()
31 // You must also add a numLeafs property before calling init().
32
33 function GnuBook() {
34     this.reduce  = 4;
35     this.padding = 10;
36     this.mode    = 1; //1 or 2
37     this.ui = 'full'; // UI mode
38     
39     this.displayedIndices = []; 
40     //this.indicesToDisplay = [];
41     this.imgs = {};
42     this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
43     
44     this.timer     = null;
45     this.animating = false;
46     this.auto      = false;
47     this.autoTimer = null;
48     this.flipSpeed = 'fast';
49
50     this.twoPagePopUp = null;
51     this.leafEdgeTmp  = null;
52     this.embedPopup = null;
53     
54     this.searchResults = {};
55     
56     this.firstIndex = null;
57     
58     this.lastDisplayableIndex2up = null;
59     
60     // We link to index.php to avoid redirect which breaks back button
61     this.logoURL = 'http://www.archive.org/index.php';
62     
63     // Base URL for images
64     this.imagesBaseURL = '/bookreader/images/';
65     
66     // Mode constants
67     this.constMode1up = 1;
68     this.constMode2up = 2;
69     
70     // Zoom levels
71     this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
72
73     // Object to hold parameters related to 2up mode
74     this.twoPage = {
75         coverInternalPadding: 10, // Width of cover
76         coverExternalPadding: 10, // Padding outside of cover
77         bookSpineDivWidth: 30,    // Width of book spine  $$$ consider sizing based on book length
78         autofit: true
79     };
80 };
81
82 // init()
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
85
86     var startIndex = undefined;
87     
88     // Find start index and mode if set in location hash
89     var params = this.paramsFromFragment(window.location.hash);
90         
91     if ('undefined' != typeof(params.index)) {
92         startIndex = params.index;
93     } else if ('undefined' != typeof(params.page)) {
94         startIndex = this.getPageIndex(params.page);
95     }
96     
97     if ('undefined' == typeof(startIndex)) {
98         if ('undefined' != typeof(this.titleLeaf)) {
99             startIndex = this.leafNumToIndex(this.titleLeaf);
100         }
101     }
102     
103     if ('undefined' == typeof(startIndex)) {
104         startIndex = 0;
105     }
106     
107     if ('undefined' != typeof(params.mode)) {
108         this.mode = params.mode;
109     }
110     
111     // Set document title -- may have already been set in enclosing html for
112     // search engine visibility
113     document.title = this.shortTitle(50);
114     
115     // Sanitize parameters
116     if ( !this.canSwitchToMode( this.mode ) ) {
117         this.mode = this.constMode1up;
118     }
119     
120     $("#GnuBook").empty();
121     this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122     $("#GnuBook").append("<div id='GBcontainer'></div>");
123     $("#GBcontainer").append("<div id='GBpageview'></div>");
124
125     $("#GBcontainer").bind('scroll', this, function(e) {
126         e.data.loadLeafs();
127     });
128
129     this.setupKeyListeners();
130     this.startLocationPolling();
131
132     $(window).bind('resize', this, function(e) {
133         //console.log('resize!');
134         if (1 == e.data.mode) {
135             //console.log('centering 1page view');
136             e.data.centerPageView();
137             $('#GBpageview').empty()
138             e.data.displayedIndices = [];
139             e.data.updateSearchHilites(); //deletes hilights but does not call remove()            
140             e.data.loadLeafs();
141         } else {
142             //console.log('drawing 2 page view');
143             
144             // We only need to prepare again in autofit (size of spread changes)
145             if (e.data.twoPage.autofit) {
146                 e.data.prepareTwoPageView();
147             } else {
148                 // Re-center if the scrollbars have disappeared
149                 var center = e.data.twoPageGetViewCenter();
150                 var doRecenter = false;
151                 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
152                     center.percentageX = 0.5;
153                     doRecenter = true;
154                 }
155                 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
156                     center.percentageY = 0.5;
157                     doRecenter = true;
158                 }
159                 if (doRecenter) {
160                     e.data.twoPageCenterView(center.percentageX, center.percentageY);
161                 }
162             }
163         }
164     });
165     
166     $('.GBpagediv1up').bind('mousedown', this, function(e) {
167         // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
168         //     but this also interferes with right-click.  See https://bugs.edge.launchpad.net/gnubook/+bug/362626
169     });
170
171     if (1 == this.mode) {
172         this.resizePageView();
173         this.firstIndex = startIndex;
174         this.jumpToIndex(startIndex);
175     } else {
176         //this.resizePageView();
177         
178         this.displayedIndices=[0];
179         this.firstIndex = startIndex;
180         this.displayedIndices = [this.firstIndex];
181         //console.log('titleLeaf: %d', this.titleLeaf);
182         //console.log('displayedIndices: %s', this.displayedIndices);
183         this.prepareTwoPageView();
184     }
185         
186     // Enact other parts of initial params
187     this.updateFromParams(params);
188 }
189
190 GnuBook.prototype.setupKeyListeners = function() {
191     var self = this;
192
193     var KEY_PGUP = 33;
194     var KEY_PGDOWN = 34;
195     var KEY_END = 35;
196     var KEY_HOME = 36;
197
198     var KEY_LEFT = 37;
199     var KEY_UP = 38;
200     var KEY_RIGHT = 39;
201     var KEY_DOWN = 40;
202
203     // We use document here instead of window to avoid a bug in jQuery on IE7
204     $(document).keydown(function(e) {
205         
206         // Keyboard navigation        
207         switch(e.keyCode) {
208             case KEY_PGUP:
209             case KEY_UP:            
210                 // In 1up mode page scrolling is handled by browser
211                 if (2 == self.mode) {
212                     self.prev();
213                 }
214                 break;
215             case KEY_DOWN:
216             case KEY_PGDOWN:
217                 if (2 == self.mode) {
218                     self.next();
219                 }
220                 break;
221             case KEY_END:
222                 self.last();
223                 break;
224             case KEY_HOME:
225                 self.first();
226                 break;
227             case KEY_LEFT:
228                 if (self.keyboardNavigationIsDisabled(e)) {
229                     break;
230                 }
231                 if (2 == self.mode) {
232                     self.left();
233                 }
234                 break;
235             case KEY_RIGHT:
236                 if (self.keyboardNavigationIsDisabled(e)) {
237                     break;
238                 }
239                 if (2 == self.mode) {
240                     self.right();
241                 }
242                 break;
243         }
244     });
245 }
246
247 // drawLeafs()
248 //______________________________________________________________________________
249 GnuBook.prototype.drawLeafs = function() {
250     if (1 == this.mode) {
251         this.drawLeafsOnePage();
252     } else {
253         this.drawLeafsTwoPage();
254     }
255 }
256
257 // setDragHandler()
258 //______________________________________________________________________________
259 GnuBook.prototype.setDragHandler = function(div) {
260     div.dragging = false;
261
262     $(div).bind('mousedown', function(e) {
263         //console.log('mousedown at ' + e.pageY);
264
265         this.dragging = true;
266         this.prevMouseX = e.pageX;
267         this.prevMouseY = e.pageY;
268     
269         var startX    = e.pageX;
270         var startY    = e.pageY;
271         var startTop  = $('#GBcontainer').attr('scrollTop');
272         var startLeft =  $('#GBcontainer').attr('scrollLeft');
273
274         return false;
275     });
276         
277     $(div).bind('mousemove', function(ee) {
278         //console.log('mousemove ' + startY);
279         
280         var offsetX = ee.pageX - this.prevMouseX;
281         var offsetY = ee.pageY - this.prevMouseY;
282         
283         if (this.dragging) {
284             $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
285             $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
286         }
287         
288         this.prevMouseX = ee.pageX;
289         this.prevMouseY = ee.pageY;
290         
291         return false;
292     });
293     
294     $(div).bind('mouseup', function(ee) {
295         //console.log('mouseup');
296
297         this.dragging = false;
298         return false;
299     });
300     
301     $(div).bind('mouseleave', function(e) {
302         //console.log('mouseleave');
303
304         //$(this).unbind('mousemove mouseup');
305         this.dragging = false;
306         
307     });
308     
309     $(div).bind('mouseenter', function(e) {
310         // On FF/OSX we don't always receive the mouseleave event
311         this.dragging = false;
312     });
313 }
314
315 // drawLeafsOnePage()
316 //______________________________________________________________________________
317 GnuBook.prototype.drawLeafsOnePage = function() {
318     //alert('drawing leafs!');
319     this.timer = null;
320
321
322     var scrollTop = $('#GBcontainer').attr('scrollTop');
323     var scrollBottom = scrollTop + $('#GBcontainer').height();
324     //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
325     
326     var indicesToDisplay = [];
327     
328     var i;
329     var leafTop = 0;
330     var leafBottom = 0;
331     for (i=0; i<this.numLeafs; i++) {
332         var height  = parseInt(this.getPageHeight(i)/this.reduce); 
333     
334         leafBottom += height;
335         //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
336         var topInView    = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
337         var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
338         var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
339         if (topInView | bottomInView | middleInView) {
340             //console.log('displayed: ' + this.displayedIndices);
341             //console.log('to display: ' + i);
342             indicesToDisplay.push(i);
343         }
344         leafTop += height +10;      
345         leafBottom += 10;
346     }
347
348     var firstIndexToDraw  = indicesToDisplay[0];
349     this.firstIndex      = firstIndexToDraw;
350     
351     // Update hash, but only if we're currently displaying a leaf
352     // Hack that fixes #365790
353     if (this.displayedIndices.length > 0) {
354         this.updateLocationHash();
355     }
356
357     if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
358         firstIndexToDraw--;
359         indicesToDisplay.unshift(firstIndexToDraw);
360     }
361     
362     var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
363     if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
364         indicesToDisplay.push(lastIndexToDraw+1);
365     }
366     
367     leafTop = 0;
368     var i;
369     for (i=0; i<firstIndexToDraw; i++) {
370         leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
371     }
372
373     //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
374     var viewWidth = $('#GBcontainer').attr('scrollWidth');
375
376
377     for (i=0; i<indicesToDisplay.length; i++) {
378         var index = indicesToDisplay[i];    
379         var height  = parseInt(this.getPageHeight(index)/this.reduce); 
380
381         if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {            
382             var width   = parseInt(this.getPageWidth(index)/this.reduce); 
383             //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
384             var div = document.createElement("div");
385             div.className = 'GBpagediv1up';
386             div.id = 'pagediv'+index;
387             div.style.position = "absolute";
388             $(div).css('top', leafTop + 'px');
389             var left = (viewWidth-width)>>1;
390             if (left<0) left = 0;
391             $(div).css('left', left+'px');
392             $(div).css('width', width+'px');
393             $(div).css('height', height+'px');
394             //$(div).text('loading...');
395             
396             this.setDragHandler(div);
397             
398             $('#GBpageview').append(div);
399
400             var img = document.createElement("img");
401             img.src = this.getPageURI(index);
402             $(img).css('width', width+'px');
403             $(img).css('height', height+'px');
404             $(div).append(img);
405
406         } else {
407             //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));            
408         }
409
410         leafTop += height +10;
411
412     }
413     
414     for (i=0; i<this.displayedIndices.length; i++) {
415         if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
416             var index = this.displayedIndices[i];
417             //console.log('Removing leaf ' + index);
418             //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
419             $('#pagediv'+index).remove();
420         } else {
421             //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
422         }
423     }
424     
425     this.displayedIndices = indicesToDisplay.slice();
426     this.updateSearchHilites();
427     
428     if (null != this.getPageNum(firstIndexToDraw))  {
429         $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
430     } else {
431         $("#GBpagenum").val('');
432     }
433             
434     this.updateToolbarZoom(this.reduce);
435     
436 }
437
438 // drawLeafsTwoPage()
439 //______________________________________________________________________________
440 GnuBook.prototype.drawLeafsTwoPage = function() {
441     var scrollTop = $('#GBtwopageview').attr('scrollTop');
442     var scrollBottom = scrollTop + $('#GBtwopageview').height();
443     
444     // $$$ we should use calculated values in this.twoPage (recalc if necessary)
445     
446     var indexL = this.twoPage.currentIndexL;
447     var heightL  = this.getPageHeight(indexL); 
448     var widthL   = this.getPageWidth(indexL);
449
450     var leafEdgeWidthL = this.leafEdgeWidth(indexL);
451     var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
452     //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
453     var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
454     //console.log(leafEdgeWidthL);
455
456     var middle = this.twoPage.middle; // $$$ getter instead?
457     var top = this.twoPageTop();
458     var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
459
460     var scaledWL = this.getPageWidth2UP(indexL);
461     var gutter = this.twoPageGutter();
462     
463     this.prefetchImg(indexL);
464     $(this.prefetchedImgs[indexL]).css({
465         position: 'absolute',
466         left: gutter-scaledWL+'px',
467         right: '',
468         top:    top+'px',
469         backgroundColor: 'rgb(234, 226, 205)',
470         height: this.twoPage.height +'px', // $$$ height forced the same for both pages
471         width:  scaledWL + 'px',
472         borderRight: '1px solid black',
473         zIndex: 2
474     }).appendTo('#GBtwopageview');
475
476
477     var indexR = this.twoPage.currentIndexR;
478     var heightR  = this.getPageHeight(indexR); 
479     var widthR   = this.getPageWidth(indexR);
480
481     // $$$ should use getwidth2up?
482     //var scaledWR = this.twoPage.height*widthR/heightR;
483     var scaledWR = this.getPageWidth2UP(indexR);
484     this.prefetchImg(indexR);
485     $(this.prefetchedImgs[indexR]).css({
486         position: 'absolute',
487         left:   gutter+'px',
488         right: '',
489         top:    top+'px',
490         backgroundColor: 'rgb(234, 226, 205)',
491         height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
492         width:  scaledWR + 'px',
493         borderLeft: '1px solid black',
494         zIndex: 2
495     }).appendTo('#GBtwopageview');
496         
497
498     this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
499     this.setClickHandlers();
500     this.twoPageSetCursor();
501
502     this.updatePageNumBox2UP();
503     this.updateToolbarZoom(this.reduce);
504 }
505
506 // updatePageNumBox2UP
507 //______________________________________________________________________________
508 GnuBook.prototype.updatePageNumBox2UP = function() {
509     if (null != this.getPageNum(this.twoPage.currentIndexL))  {
510         $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
511     } else {
512         $("#GBpagenum").val('');
513     }
514     this.updateLocationHash();
515 }
516
517 // loadLeafs()
518 //______________________________________________________________________________
519 GnuBook.prototype.loadLeafs = function() {
520
521
522     var self = this;
523     if (null == this.timer) {
524         this.timer=setTimeout(function(){self.drawLeafs()},250);
525     } else {
526         clearTimeout(this.timer);
527         this.timer=setTimeout(function(){self.drawLeafs()},250);    
528     }
529 }
530
531 // zoom(direction)
532 //
533 // Pass 1 to zoom in, anything else to zoom out
534 //______________________________________________________________________________
535 GnuBook.prototype.zoom = function(direction) {
536     switch (this.mode) {
537         case this.constMode1up:
538             return this.zoom1up(direction);
539         case this.constMode2up:
540             return this.zoom2up(direction);
541     }
542 }
543
544 // zoom1up(dir)
545 //______________________________________________________________________________
546 GnuBook.prototype.zoom1up = function(dir) {
547     if (2 == this.mode) {     //can only zoom in 1-page mode
548         this.switchMode(1);
549         return;
550     }
551     
552     // $$$ with flexible zoom we could "snap" to /2 page reductions
553     //     for better scaling
554     if (1 == dir) {
555         if (this.reduce <= 0.5) return;
556         this.reduce*=0.5;           //zoom in
557     } else {
558         if (this.reduce >= 8) return;
559         this.reduce*=2;             //zoom out
560     }
561     
562     this.resizePageView();
563
564     $('#GBpageview').empty()
565     this.displayedIndices = [];
566     this.loadLeafs();
567     
568     this.updateToolbarZoom(this.reduce);
569 }
570
571 // resizePageView()
572 //______________________________________________________________________________
573 GnuBook.prototype.resizePageView = function() {
574     var i;
575     var viewHeight = 0;
576     //var viewWidth  = $('#GBcontainer').width(); //includes scrollBar
577     var viewWidth  = $('#GBcontainer').attr('clientWidth');   
578
579     var oldScrollTop  = $('#GBcontainer').attr('scrollTop');
580     var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
581     var oldPageViewHeight = $('#GBpageview').height();
582     var oldPageViewWidth = $('#GBpageview').width();
583     
584     var oldCenterY = this.centerY1up();
585     var oldCenterX = this.centerX1up();
586     
587     if (0 != oldPageViewHeight) {
588         var scrollRatio = oldCenterY / oldPageViewHeight;
589     } else {
590         var scrollRatio = 0;
591     }
592     
593     for (i=0; i<this.numLeafs; i++) {
594         viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding; 
595         var width = parseInt(this.getPageWidth(i)/this.reduce);
596         if (width>viewWidth) viewWidth=width;
597     }
598     $('#GBpageview').height(viewHeight);
599     $('#GBpageview').width(viewWidth);    
600
601     var newCenterY = scrollRatio*viewHeight;
602     var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
603     $('#GBcontainer').attr('scrollTop', newTop);
604     
605     // We use clientWidth here to avoid miscalculating due to scroll bar
606     var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
607     var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
608     newLeft = Math.max(newLeft, 0);
609     $('#GBcontainer').attr('scrollLeft', newLeft);
610     //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
611     
612     //this.centerPageView();
613     this.loadLeafs();
614     
615 }
616
617 // centerX1up()
618 //______________________________________________________________________________
619 // Returns the current offset of the viewport center in scaled document coordinates.
620 GnuBook.prototype.centerX1up = function() {
621     var centerX;
622     if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
623         centerX = $('#GBpageview').width();
624     } else {
625         centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
626     }
627     centerX = Math.floor(centerX);
628     return centerX;
629 }
630
631 // centerY1up()
632 //______________________________________________________________________________
633 // Returns the current offset of the viewport center in scaled document coordinates.
634 GnuBook.prototype.centerY1up = function() {
635     var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
636     return Math.floor(centerY);
637 }
638
639 // centerPageView()
640 //______________________________________________________________________________
641 GnuBook.prototype.centerPageView = function() {
642
643     var scrollWidth  = $('#GBcontainer').attr('scrollWidth');
644     var clientWidth  =  $('#GBcontainer').attr('clientWidth');
645     //console.log('sW='+scrollWidth+' cW='+clientWidth);
646     if (scrollWidth > clientWidth) {
647         $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
648     }
649
650 }
651
652 // zoom2up(direction)
653 //______________________________________________________________________________
654 GnuBook.prototype.zoom2up = function(direction) {
655
656     // Hard stop autoplay
657     this.stopFlipAnimations();
658     
659     // Get new zoom state    
660     var newZoom = this.twoPageNextReduce(this.reduce, direction);
661     if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
662         return;
663     }
664     this.twoPage.autofit = newZoom.autofit;
665     this.reduce = newZoom.reduce;
666
667     // Preserve view center position
668     var oldCenter = this.twoPageGetViewCenter();
669     
670     // Prepare view with new center to minimize visual glitches
671     this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
672 }
673
674
675 // quantizeReduce(reduce)
676 //______________________________________________________________________________
677 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
678 GnuBook.prototype.quantizeReduce = function(reduce) {
679     var quantized = this.reductionFactors[0];
680     var distance = Math.abs(reduce - quantized);
681     for (var i = 1; i < this.reductionFactors.length; i++) {
682         newDistance = Math.abs(reduce - this.reductionFactors[i]);
683         if (newDistance < distance) {
684             distance = newDistance;
685             quantized = this.reductionFactors[i];
686         }
687     }
688     
689     return quantized;
690 }
691
692 // twoPageNextReduce()
693 //______________________________________________________________________________
694 // Returns the next reduction level
695 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
696     var result = {};
697     var autofitReduce = this.twoPageGetAutofitReduce();
698
699     if (0 == direction) { // autofit
700         result.autofit = true;
701         result.reduce = autofitReduce;
702         
703     } else if (1 == direction) { // zoom in
704         var newReduce = this.reductionFactors[0];
705     
706         for (var i = 1; i < this.reductionFactors.length; i++) {
707             if (this.reductionFactors[i] < reduce) {
708                 newReduce = this.reductionFactors[i];
709             }
710         }
711         
712         if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
713             // use autofit
714             result.autofit = true;
715             result.reduce = autofitReduce;
716         } else {        
717             result.autofit = false;
718             result.reduce = newReduce;
719         }
720         
721     } else { // zoom out
722         var lastIndex = this.reductionFactors.length - 1;
723         var newReduce = this.reductionFactors[lastIndex];
724         
725         for (var i = lastIndex; i >= 0; i--) {
726             if (this.reductionFactors[i] > reduce) {
727                 newReduce = this.reductionFactors[i];
728             }
729         }
730          
731         if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
732             // use autofit
733             result.autofit = true;
734             result.reduce = autofitReduce;
735         } else {
736             result.autofit = false;
737             result.reduce = newReduce;
738         }
739     }
740     
741     return result;
742 }
743
744 // jumpToPage()
745 //______________________________________________________________________________
746 // Attempts to jump to page.  Returns true if page could be found, false otherwise.
747 GnuBook.prototype.jumpToPage = function(pageNum) {
748
749     var pageIndex = this.getPageIndex(pageNum);
750
751     if ('undefined' != typeof(pageIndex)) {
752         var leafTop = 0;
753         var h;
754         this.jumpToIndex(pageIndex);
755         $('#GBcontainer').attr('scrollTop', leafTop);
756         return true;
757     }
758     
759     // Page not found
760     return false;
761 }
762
763 // jumpToIndex()
764 //______________________________________________________________________________
765 GnuBook.prototype.jumpToIndex = function(index) {
766
767     if (2 == this.mode) {
768         this.autoStop();
769         
770         // By checking against min/max we do nothing if requested index
771         // is current
772         if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
773             this.flipBackToIndex(index);
774         } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
775             this.flipFwdToIndex(index);
776         }
777
778     } else {        
779         var i;
780         var leafTop = 0;
781         var h;
782         for (i=0; i<index; i++) {
783             h = parseInt(this.getPageHeight(i)/this.reduce); 
784             leafTop += h + this.padding;
785         }
786         //$('#GBcontainer').attr('scrollTop', leafTop);
787         $('#GBcontainer').animate({scrollTop: leafTop },'fast');
788     }
789 }
790
791
792
793 // switchMode()
794 //______________________________________________________________________________
795 GnuBook.prototype.switchMode = function(mode) {
796
797     //console.log('  asked to switch to mode ' + mode + ' from ' + this.mode);
798     
799     if (mode == this.mode) return;
800     
801     if (!this.canSwitchToMode(mode)) {
802         return;
803     }
804
805     this.autoStop();
806     this.removeSearchHilites();
807
808     this.mode = mode;
809     
810     this.switchToolbarMode(mode);
811     
812     if (1 == mode) {
813         this.reduce = this.quantizeReduce(this.reduce);
814         this.prepareOnePageView();
815     } else {
816         this.prepareTwoPageView();
817         this.twoPageCenterView(0.5, 0.5);
818     }
819
820 }
821
822 //prepareOnePageView()
823 //______________________________________________________________________________
824 GnuBook.prototype.prepareOnePageView = function() {
825
826     // var startLeaf = this.displayedIndices[0];
827     var startLeaf = this.currentIndex();
828     
829     $('#GBcontainer').empty();
830     $('#GBcontainer').css({
831         overflowY: 'scroll',
832         overflowX: 'auto'
833     });
834     
835     var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
836     
837     this.resizePageView();
838     
839     this.jumpToIndex(startLeaf);
840     this.displayedIndices = [];
841     
842     this.drawLeafsOnePage();
843         
844     // Bind mouse handlers
845     // Disable mouse click to avoid selected/highlighted page images - bug 354239
846     gbPageView.bind('mousedown', function(e) {
847         // $$$ check here for right-click and don't disable.  Also use jQuery style
848         //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
849         return false;
850     })
851     // Special hack for IE7
852     gbPageView[0].onselectstart = function(e) { return false; };
853 }
854
855 // prepareTwoPageView()
856 //______________________________________________________________________________
857 // Some decisions about two page view:
858 //
859 // Both pages will be displayed at the same height, even if they were different physical/scanned
860 // sizes.  This simplifies the animation (from a design as well as technical standpoint).  We
861 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
862 // aspect ratio to determine the height.
863 //
864 // The two page view div is resized to keep the middle of the book in the middle of the div
865 // even as the page sizes change.  To e.g. keep the middle of the book in the middle of the GBcontent
866 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
867 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
868     $('#GBcontainer').empty();
869     $('#GBcontainer').css('overflow', 'auto');
870         
871     // We want to display two facing pages.  We may be missing
872     // one side of the spread because it is the first/last leaf,
873     // foldouts, missing pages, etc
874
875     //var targetLeaf = this.displayedIndices[0];
876     var targetLeaf = this.firstIndex;
877
878     if (targetLeaf < this.firstDisplayableIndex()) {
879         targetLeaf = this.firstDisplayableIndex();
880     }
881     
882     if (targetLeaf > this.lastDisplayableIndex()) {
883         targetLeaf = this.lastDisplayableIndex();
884     }
885     
886     this.twoPage.currentIndexL = null;
887     this.twoPage.currentIndexR = null;
888     this.pruneUnusedImgs();
889     
890     var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
891     this.twoPage.currentIndexL = currentSpreadIndices[0];
892     this.twoPage.currentIndexR = currentSpreadIndices[1];
893     this.firstIndex = this.twoPage.currentIndexL;
894     
895     this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
896         
897     //console.dir(this.twoPage);
898     
899     // Add the two page view
900     // $$$ Can we get everything set up and then append?
901     $('#GBcontainer').append('<div id="GBtwopageview"></div>');
902
903     // $$$ calculate first then set
904     $('#GBtwopageview').css( {
905         height: this.twoPage.totalHeight + 'px',
906         width: this.twoPage.totalWidth + 'px',
907         position: 'absolute'
908         });
909         
910     // If there will not be scrollbars (e.g. when zooming out) we center the book
911     // since otherwise the book will be stuck off-center
912     if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
913         centerPercentageX = 0.5;
914     }
915     if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
916         centerPercentageY = 0.5;
917     }
918         
919     this.twoPageCenterView(centerPercentageX, centerPercentageY);
920     
921     this.twoPage.coverDiv = document.createElement('div');
922     $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
923         border: '1px solid rgb(68, 25, 17)',
924         width:  this.twoPage.bookCoverDivWidth + 'px',
925         height: this.twoPage.bookCoverDivHeight+'px',
926         visibility: 'visible',
927         position: 'absolute',
928         backgroundColor: '#663929',
929         left: this.twoPage.bookCoverDivLeft + 'px',
930         top: this.twoPage.bookCoverDivTop+'px',
931         MozBorderRadiusTopleft: '7px',
932         MozBorderRadiusTopright: '7px',
933         MozBorderRadiusBottomright: '7px',
934         MozBorderRadiusBottomleft: '7px'
935     }).appendTo('#GBtwopageview');
936     
937     this.leafEdgeR = document.createElement('div');
938     this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
939     $(this.leafEdgeR).css({
940         borderStyle: 'solid solid solid none',
941         borderColor: 'rgb(51, 51, 34)',
942         borderWidth: '1px 1px 1px 0px',
943         background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
944         width: this.twoPage.leafEdgeWidthR + 'px',
945         height: this.twoPage.height-1 + 'px',
946         /*right: '10px',*/
947         left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
948         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
949         position: 'absolute'
950     }).appendTo('#GBtwopageview');
951     
952     this.leafEdgeL = document.createElement('div');
953     this.leafEdgeL.className = 'leafEdgeL';
954     $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
955         borderStyle: 'solid none solid solid',
956         borderColor: 'rgb(51, 51, 34)',
957         borderWidth: '1px 0px 1px 1px',
958         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
959         width: this.twoPage.leafEdgeWidthL + 'px',
960         height: this.twoPage.height-1 + 'px',
961         left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
962         top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',    
963         position: 'absolute'
964     }).appendTo('#GBtwopageview');
965
966     div = document.createElement('div');
967     $(div).attr('id', 'GBbookspine').css({
968         border:          '1px solid rgb(68, 25, 17)',
969         width:           this.twoPage.bookSpineDivWidth+'px',
970         height:          this.twoPage.bookSpineDivHeight+'px',
971         position:        'absolute',
972         backgroundColor: 'rgb(68, 25, 17)',
973         left:            this.twoPage.bookSpineDivLeft+'px',
974         top:             this.twoPage.bookSpineDivTop+'px'
975     }).appendTo('#GBtwopageview');
976
977     this.prepareTwoPagePopUp();
978
979     this.displayedIndices = [];
980     
981     //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
982     //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
983     
984     this.drawLeafsTwoPage();
985     this.updateSearchHilites2UP();
986     this.updateToolbarZoom(this.reduce);
987     
988     this.prefetch();
989 }
990
991 // prepareTwoPagePopUp()
992 //
993 // This function prepares the "View Page n" popup that shows while the mouse is
994 // over the left/right "stack of sheets" edges.  It also binds the mouse
995 // events for these divs.
996 //______________________________________________________________________________
997 GnuBook.prototype.prepareTwoPagePopUp = function() {
998
999     this.twoPagePopUp = document.createElement('div');
1000     $(this.twoPagePopUp).css({
1001         border: '1px solid black',
1002         padding: '2px 6px',
1003         position: 'absolute',
1004         fontFamily: 'sans-serif',
1005         fontSize: '14px',
1006         zIndex: '1000',
1007         backgroundColor: 'rgb(255, 255, 238)',
1008         opacity: 0.85
1009     }).appendTo('#GBcontainer');
1010     $(this.twoPagePopUp).hide();
1011     
1012     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1013         $(e.data.twoPagePopUp).show();
1014     });
1015
1016     $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1017         $(e.data.twoPagePopUp).hide();
1018     });
1019
1020     $(this.leafEdgeL).bind('click', this, function(e) { 
1021         e.data.autoStop();
1022         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1023         e.data.jumpToIndex(jumpIndex);
1024     });
1025
1026     $(this.leafEdgeR).bind('click', this, function(e) { 
1027         e.data.autoStop();
1028         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1029         e.data.jumpToIndex(jumpIndex);    
1030     });
1031
1032     $(this.leafEdgeR).bind('mousemove', this, function(e) {
1033
1034         var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1035         $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1036         
1037         // $$$ TODO: Make sure popup is positioned so that it is in view
1038         // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1039         $(e.data.twoPagePopUp).css({
1040             left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1041             top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1042         });
1043     });
1044
1045     $(this.leafEdgeL).bind('mousemove', this, function(e) {
1046     
1047         var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1048         $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1049
1050         // $$$ TODO: Make sure popup is positioned so that it is in view
1051         //           (https://bugs.edge.launchpad.net/gnubook/+bug/327456)        
1052         $(e.data.twoPagePopUp).css({
1053             left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1054             top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1055         });
1056     });
1057 }
1058
1059 // calculateSpreadSize()
1060 //______________________________________________________________________________
1061 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1062 // this.twoPage.currentIndexR
1063 // This function sets this.twoPage.height, twoPage.width
1064
1065 GnuBook.prototype.calculateSpreadSize = function() {
1066
1067     var firstIndex  = this.twoPage.currentIndexL;
1068     var secondIndex = this.twoPage.currentIndexR;
1069     //console.log('first page is ' + firstIndex);
1070
1071     // Calculate page sizes and total leaf width
1072     var spreadSize;
1073     if ( this.twoPage.autofit) {    
1074         spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1075     } else {
1076         // set based on reduction factor
1077         spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1078     }
1079     
1080     // Both pages together
1081     this.twoPage.height = spreadSize.height;
1082     this.twoPage.width = spreadSize.width;
1083     
1084     // Individual pages
1085     this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1086     this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1087     
1088     // Leaf edges
1089     this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1090     this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1091     this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1092     
1093     
1094     // Book cover
1095     // The width of the book cover div.  The combined width of both pages, twice the width
1096     // of the book cover internal padding (2*10) and the page edges
1097     this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1098     // The height of the book cover div
1099     this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1100     
1101     
1102     // We calculate the total width and height for the div so that we can make the book
1103     // spine centered
1104     var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1105     var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1106     var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1107     var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1108     this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1109     this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1110         
1111     // We want to minimize the unused space in two-up mode (maximize the amount of page
1112     // shown).  We give width to the leaf edges and these widths change (though the sum
1113     // of the two remains constant) as we flip through the book.  With the book
1114     // cover centered and fixed in the GBcontainer div the page images will meet
1115     // at the "gutter" which is generally offset from the center.
1116     this.twoPage.middle = this.twoPage.totalWidth >> 1;
1117     this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1118     
1119     // The left edge of the book cover moves depending on the width of the pages
1120     // $$$ change to getter
1121     this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1122     // The top edge of the book cover stays a fixed distance from the top
1123     this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1124
1125     // Book spine
1126     this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1127     this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1128     this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1129
1130
1131     this.reduce = spreadSize.reduce; // $$$ really set this here?
1132 }
1133
1134 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1135     var ideal = {};
1136
1137     // We check which page is closest to a "normal" page and use that to set the height
1138     // for both pages.  This means that foldouts and other odd size pages will be displayed
1139     // smaller than the nominal zoom amount.
1140     var canon5Dratio = 1.5;
1141     
1142     var first = {
1143         height: this.getPageHeight(firstIndex),
1144         width: this.getPageWidth(firstIndex)
1145     }
1146     
1147     var second = {
1148         height: this.getPageHeight(secondIndex),
1149         width: this.getPageWidth(secondIndex)
1150     }
1151     
1152     var firstIndexRatio  = first.height / first.width;
1153     var secondIndexRatio = second.height / second.width;
1154     //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1155
1156     var ratio;
1157     if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1158         ratio = firstIndexRatio;
1159         //console.log('using firstIndexRatio ' + ratio);
1160     } else {
1161         ratio = secondIndexRatio;
1162         //console.log('using secondIndexRatio ' + ratio);
1163     }
1164
1165     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1166     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1167     ideal.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1168     
1169     var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1170     var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1171     
1172     ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1173     ideal.width -= 10; // $$$ fudge factor
1174     ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1175     ideal.height -= 20; // fudge factor
1176     //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1177
1178     if (ideal.height/ratio <= ideal.width) {
1179         //use height
1180         ideal.width = parseInt(ideal.height/ratio);
1181     } else {
1182         //use width
1183         ideal.height = parseInt(ideal.width*ratio);
1184     }
1185     
1186     // $$$ check this logic with large spreads
1187     ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1188     
1189     return ideal;
1190 }
1191
1192 // getSpreadSizeFromReduce()
1193 //______________________________________________________________________________
1194 // Returns the spread size calculated from the reduction factor for the given pages
1195 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1196     var spreadSize = {};
1197     // $$$ Scale this based on reduce?
1198     var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1199     var maxLeafEdgeWidth   = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1200     spreadSize.totalLeafEdgeWidth     = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1201
1202     // $$$ Possibly incorrect -- we should make height "dominant"
1203     var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1204     var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1205     spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1206     spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1207     spreadSize.reduce = reduce;
1208     
1209     return spreadSize;
1210 }
1211
1212 // twoPageGetAutofitReduce()
1213 //______________________________________________________________________________
1214 // Returns the current ideal reduction factor
1215 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1216     var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1217     return spreadSize.reduce;
1218 }
1219
1220 // twoPageSetCursor()
1221 //______________________________________________________________________________
1222 // Set the cursor for two page view
1223 GnuBook.prototype.twoPageSetCursor = function() {
1224     // console.log('setting cursor');
1225     if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1226          ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1227         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1228         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1229     } else {
1230         $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1231         $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1232     }
1233 }
1234
1235 // currentIndex()
1236 //______________________________________________________________________________
1237 // Returns the currently active index.
1238 GnuBook.prototype.currentIndex = function() {
1239     // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1240     if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1241         return this.firstIndex;
1242     } else {
1243         throw 'currentIndex called for unimplemented mode ' + this.mode;
1244     }
1245 }
1246
1247 // right()
1248 //______________________________________________________________________________
1249 // Flip the right page over onto the left
1250 GnuBook.prototype.right = function() {
1251     if ('rl' != this.pageProgression) {
1252         // LTR
1253         gb.next();
1254     } else {
1255         // RTL
1256         gb.prev();
1257     }
1258 }
1259
1260 // rightmost()
1261 //______________________________________________________________________________
1262 // Flip to the rightmost page
1263 GnuBook.prototype.rightmost = function() {
1264     if ('rl' != this.pageProgression) {
1265         gb.last();
1266     } else {
1267         gb.first();
1268     }
1269 }
1270
1271 // left()
1272 //______________________________________________________________________________
1273 // Flip the left page over onto the right.
1274 GnuBook.prototype.left = function() {
1275     if ('rl' != this.pageProgression) {
1276         // LTR
1277         gb.prev();
1278     } else {
1279         // RTL
1280         gb.next();
1281     }
1282 }
1283
1284 // leftmost()
1285 //______________________________________________________________________________
1286 // Flip to the leftmost page
1287 GnuBook.prototype.leftmost = function() {
1288     if ('rl' != this.pageProgression) {
1289         gb.first();
1290     } else {
1291         gb.last();
1292     }
1293 }
1294
1295 // next()
1296 //______________________________________________________________________________
1297 GnuBook.prototype.next = function() {
1298     if (2 == this.mode) {
1299         this.autoStop();
1300         this.flipFwdToIndex(null);
1301     } else {
1302         if (this.firstIndex < this.lastDisplayableIndex()) {
1303             this.jumpToIndex(this.firstIndex+1);
1304         }
1305     }
1306 }
1307
1308 // prev()
1309 //______________________________________________________________________________
1310 GnuBook.prototype.prev = function() {
1311     if (2 == this.mode) {
1312         this.autoStop();
1313         this.flipBackToIndex(null);
1314     } else {
1315         if (this.firstIndex >= 1) {
1316             this.jumpToIndex(this.firstIndex-1);
1317         }    
1318     }
1319 }
1320
1321 GnuBook.prototype.first = function() {
1322     if (2 == this.mode) {
1323         this.jumpToIndex(2);
1324     }
1325     else {
1326         this.jumpToIndex(0);
1327     }
1328 }
1329
1330 GnuBook.prototype.last = function() {
1331     if (2 == this.mode) {
1332         this.jumpToIndex(this.lastDisplayableIndex());
1333     }
1334     else {
1335         this.jumpToIndex(this.lastDisplayableIndex());
1336     }
1337 }
1338
1339 // flipBackToIndex()
1340 //______________________________________________________________________________
1341 // to flip back one spread, pass index=null
1342 GnuBook.prototype.flipBackToIndex = function(index) {
1343     if (1 == this.mode) return;
1344
1345     var leftIndex = this.twoPage.currentIndexL;
1346     
1347     // $$$ Need to change this to be able to see first spread.
1348     //     See https://bugs.launchpad.net/gnubook/+bug/296788
1349     if (leftIndex <= 2) return;
1350     if (this.animating) return;
1351
1352     if (null != this.leafEdgeTmp) {
1353         alert('error: leafEdgeTmp should be null!');
1354         return;
1355     }
1356     
1357     if (null == index) {
1358         index = leftIndex-2;
1359     }
1360     //if (index<0) return;
1361     
1362     var previousIndices = this.getSpreadIndices(index);
1363     
1364     if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1365         return;
1366     }
1367     
1368     //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1369
1370     this.animating = true;
1371     
1372     if ('rl' != this.pageProgression) {
1373         // Assume LTR and we are going backward    
1374         this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
1375         this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1376     } else {
1377         // RTL and going backward
1378         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1379         this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1380     }
1381 }
1382
1383 // flipLeftToRight()
1384 //______________________________________________________________________________
1385 // Flips the page on the left towards the page on the right
1386 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1387
1388     var leftLeaf = this.twoPage.currentIndexL;
1389     
1390     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1391     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);    
1392     var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1393     
1394     var currWidthL   = this.getPageWidth2UP(leftLeaf);
1395     var newWidthL    = this.getPageWidth2UP(newIndexL);
1396     var newWidthR    = this.getPageWidth2UP(newIndexR);
1397
1398     var top  = this.twoPageTop();
1399     var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1400     
1401     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1402     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1403     
1404     //animation strategy:
1405     // 0. remove search highlight, if any.
1406     // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge 
1407     //    of the left leaf and where the user clicked in the leaf edge.
1408     //    Note that if this function was triggered by left() and not a
1409     //    mouse click, the width of leafEdgeTmp is very small (zero px).
1410     // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1411     //    leftLeaf to width=0.
1412     // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1413     //    (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1414     //    its new full width.
1415     // 4. After step 3 is finished, do the following:
1416     //      - remove leafEdgeTmp from the dom.
1417     //      - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1418     //          and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1419     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1420     //          and width=newLeafEdgeWidthL.
1421     //      - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1422     //          and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1423     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1424     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
1425     //      - prefetch new adjacent leafs.
1426     //      - set up click handlers for both new left and right leafs.
1427     //      - redraw the search highlight.
1428     //      - update the pagenum box and the url.
1429     
1430     
1431     var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1432
1433     this.leafEdgeTmp = document.createElement('div');
1434     $(this.leafEdgeTmp).css({
1435         borderStyle: 'solid none solid solid',
1436         borderColor: 'rgb(51, 51, 34)',
1437         borderWidth: '1px 0px 1px 1px',
1438         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1439         width: leafEdgeTmpW + 'px',
1440         height: this.twoPage.height-1 + 'px',
1441         left: leftEdgeTmpLeft + 'px',
1442         top: top+'px',    
1443         position: 'absolute',
1444         zIndex:1000
1445     }).appendTo('#GBtwopageview');
1446     
1447     //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1448     $(this.leafEdgeL).css({
1449         width: newLeafEdgeWidthL+'px', 
1450         left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1451     });   
1452
1453     // Left gets the offset of the current left leaf from the document
1454     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1455     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
1456     var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1457     
1458     // We change the left leaf to right positioning
1459     // $$$ This causes animation glitches during resize.  See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1460     $(this.prefetchedImgs[leftLeaf]).css({
1461         right: right,
1462         left: ''
1463     });
1464
1465     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
1466     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1467     
1468     var self = this;
1469
1470     this.removeSearchHilites();
1471
1472     //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1473     $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1474     
1475         //console.log('     and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1476         $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1477
1478         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1479         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1480             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1481             
1482             $(self.leafEdgeR).css({
1483                 // Moves the right leaf edge
1484                 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1485                 left:  gutter+newWidthR+'px'
1486             });
1487
1488             $(self.leafEdgeL).css({
1489                 // Moves and resizes the left leaf edge
1490                 width: newLeafEdgeWidthL+'px',
1491                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
1492             });
1493
1494             // Resizes the brown border div
1495             $(self.twoPage.coverDiv).css({
1496                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1497                 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1498             });
1499             
1500             $(self.leafEdgeTmp).remove();
1501             self.leafEdgeTmp = null;
1502             
1503             self.twoPage.currentIndexL = newIndexL;
1504             self.twoPage.currentIndexR = newIndexR;
1505             self.firstIndex = self.twoPage.currentIndexL;
1506             self.displayedIndices = [newIndexL, newIndexR];
1507             self.setClickHandlers();
1508             self.twoPageSetCursor();
1509             self.pruneUnusedImgs();
1510             self.prefetch();            
1511             self.animating = false;
1512             
1513             self.updateSearchHilites2UP();
1514             self.updatePageNumBox2UP();
1515             
1516             if (self.animationFinishedCallback) {
1517                 self.animationFinishedCallback();
1518                 self.animationFinishedCallback = null;
1519             }
1520         });
1521     });        
1522     
1523 }
1524
1525 // flipFwdToIndex()
1526 //______________________________________________________________________________
1527 // Whether we flip left or right is dependent on the page progression
1528 // to flip forward one spread, pass index=null
1529 GnuBook.prototype.flipFwdToIndex = function(index) {
1530
1531     if (this.animating) return;
1532
1533     if (null != this.leafEdgeTmp) {
1534         alert('error: leafEdgeTmp should be null!');
1535         return;
1536     }
1537
1538     if (null == index) {
1539         index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1540     }
1541     if (index > this.lastDisplayableIndex()) return;
1542
1543     this.animating = true;
1544     
1545     var nextIndices = this.getSpreadIndices(index);
1546     
1547     //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1548
1549     if ('rl' != this.pageProgression) {
1550         // We did not specify RTL
1551         var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1552         this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1553     } else {
1554         // RTL
1555         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1556         this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1557     }
1558 }
1559
1560 // flipRightToLeft(nextL, nextR, gutter)
1561 // $$$ better not to have to pass gutter in
1562 //______________________________________________________________________________
1563 // Flip from left to right and show the nextL and nextR indices on those sides
1564 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1565     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1566     var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1567     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
1568     var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1569
1570     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1571
1572     var top = this.twoPageTop();
1573     var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1574
1575     var middle = this.twoPage.middle;
1576     var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1577     
1578     this.leafEdgeTmp = document.createElement('div');
1579     $(this.leafEdgeTmp).css({
1580         borderStyle: 'solid none solid solid',
1581         borderColor: 'rgb(51, 51, 34)',
1582         borderWidth: '1px 0px 1px 1px',
1583         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1584         width: leafEdgeTmpW + 'px',
1585         height: this.twoPage.height-1 + 'px',
1586         left: gutter+scaledW+'px',
1587         top: top+'px',    
1588         position: 'absolute',
1589         zIndex:1000
1590     }).appendTo('#GBtwopageview');
1591
1592     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1593     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1594     
1595     var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1596     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1597     var newWidthL = this.getPageWidth2UP(newIndexL);
1598     var newWidthR = this.getPageWidth2UP(newIndexR);
1599     
1600     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1601
1602     var self = this; // closure-tastic!
1603
1604     var speed = this.flipSpeed;
1605
1606     this.removeSearchHilites();
1607     
1608     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
1609     $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1610         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
1611         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1612             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1613             
1614             $(self.leafEdgeL).css({
1615                 width: newLeafEdgeWidthL+'px', 
1616                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1617             });
1618             
1619             // Resizes the book cover
1620             $(self.twoPage.coverDiv).css({
1621                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1622                 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1623             });
1624             
1625             $(self.leafEdgeTmp).remove();
1626             self.leafEdgeTmp = null;
1627             
1628             self.twoPage.currentIndexL = newIndexL;
1629             self.twoPage.currentIndexR = newIndexR;
1630             self.firstIndex = self.twoPage.currentIndexL;
1631             self.displayedIndices = [newIndexL, newIndexR];
1632             self.setClickHandlers();     
1633             self.twoPageSetCursor();
1634             self.pruneUnusedImgs();
1635             self.prefetch();
1636             self.animating = false;
1637
1638
1639             self.updateSearchHilites2UP();
1640             self.updatePageNumBox2UP();
1641             
1642             if (self.animationFinishedCallback) {
1643                 self.animationFinishedCallback();
1644                 self.animationFinishedCallback = null;
1645             }
1646         });
1647     });    
1648 }
1649
1650 // setClickHandlers
1651 //______________________________________________________________________________
1652 GnuBook.prototype.setClickHandlers = function() {
1653     var self = this;
1654     // $$$ TODO don't set again if already set
1655     $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1656         //self.prevPage();
1657         self.autoStop();
1658         self.left();
1659     });
1660     $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1661         //self.nextPage();'
1662         self.autoStop();
1663         self.right();        
1664     });
1665     
1666     this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1667     this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1668 }
1669
1670 // prefetchImg()
1671 //______________________________________________________________________________
1672 GnuBook.prototype.prefetchImg = function(index) {
1673     if (undefined == this.prefetchedImgs[index]) {    
1674         //console.log('prefetching ' + index);
1675         var img = document.createElement("img");
1676         img.src = this.getPageURI(index);
1677         this.prefetchedImgs[index] = img;
1678     }
1679 }
1680
1681
1682 // prepareFlipLeftToRight()
1683 //
1684 //______________________________________________________________________________
1685 //
1686 // Prepare to flip the left page towards the right.  This corresponds to moving
1687 // backward when the page progression is left to right.
1688 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1689
1690     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
1691
1692     this.prefetchImg(prevL);
1693     this.prefetchImg(prevR);
1694     
1695     var height  = this.getPageHeight(prevL); 
1696     var width   = this.getPageWidth(prevL);    
1697     var middle = this.twoPage.middle;
1698     var top  = this.twoPageTop();                
1699     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1700
1701     // The gutter is the dividing line between the left and right pages.
1702     // It is offset from the middle to create the illusion of thickness to the pages
1703     var gutter = middle + this.gutterOffsetForIndex(prevL);
1704     
1705     //console.log('    gutter for ' + prevL + ' is ' + gutter);
1706     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
1707     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1708     
1709     $(this.prefetchedImgs[prevL]).css({
1710         position: 'absolute',
1711         left: gutter-scaledW+'px',
1712         right: '', // clear right property
1713         top:    top+'px',
1714         backgroundColor: 'rgb(234, 226, 205)',
1715         height: this.twoPage.height,
1716         width:  scaledW+'px',
1717         borderRight: '1px solid black',
1718         zIndex: 1
1719     });
1720
1721     $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1722
1723     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1724
1725     $(this.prefetchedImgs[prevR]).css({
1726         position: 'absolute',
1727         left:   gutter+'px',
1728         right: '',
1729         top:    top+'px',
1730         backgroundColor: 'rgb(234, 226, 205)',
1731         height: this.twoPage.height,
1732         width:  '0px',
1733         borderLeft: '1px solid black',
1734         zIndex: 2
1735     });
1736
1737     $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1738             
1739 }
1740
1741 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1742 // prepareFlipRightToLeft()
1743 //______________________________________________________________________________
1744 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1745
1746     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
1747
1748     // Prefetch images
1749     this.prefetchImg(nextL);
1750     this.prefetchImg(nextR);
1751
1752     var height  = this.getPageHeight(nextR); 
1753     var width   = this.getPageWidth(nextR);    
1754     var middle = this.twoPage.middle;
1755     var top  = this.twoPageTop();               
1756     var scaledW = this.twoPage.height*width/height;
1757
1758     var gutter = middle + this.gutterOffsetForIndex(nextL);
1759         
1760     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1761     $(this.prefetchedImgs[nextR]).css({
1762         position: 'absolute',
1763         left:   gutter+'px',
1764         top:    top+'px',
1765         backgroundColor: 'rgb(234, 226, 205)',
1766         height: this.twoPage.height,
1767         width:  scaledW+'px',
1768         borderLeft: '1px solid black',
1769         zIndex: 1
1770     });
1771
1772     $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1773
1774     height  = this.getPageHeight(nextL); 
1775     width   = this.getPageWidth(nextL);      
1776     scaledW = this.twoPage.height*width/height;
1777
1778     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1779     $(this.prefetchedImgs[nextL]).css({
1780         position: 'absolute',
1781         right:   $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1782         top:    top+'px',
1783         backgroundColor: 'rgb(234, 226, 205)',
1784         height: this.twoPage.height,
1785         width:  0+'px', // Start at 0 width, then grow to the left
1786         borderRight: '1px solid black',
1787         zIndex: 2
1788     });
1789
1790     $('#GBtwopageview').append(this.prefetchedImgs[nextL]);    
1791             
1792 }
1793
1794 // getNextLeafs() -- NOT RTL AWARE
1795 //______________________________________________________________________________
1796 // GnuBook.prototype.getNextLeafs = function(o) {
1797 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1798 //     //For now, assume that leafs are contiguous.
1799 //     
1800 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1801 //     o.L = this.twoPage.currentIndexL+2;
1802 //     o.R = this.twoPage.currentIndexL+3;
1803 // }
1804
1805 // getprevLeafs() -- NOT RTL AWARE
1806 //______________________________________________________________________________
1807 // GnuBook.prototype.getPrevLeafs = function(o) {
1808 //     //TODO: we might have two left or two right leafs in a row (damaged book)
1809 //     //For now, assume that leafs are contiguous.
1810 //     
1811 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1812 //     o.L = this.twoPage.currentIndexL-2;
1813 //     o.R = this.twoPage.currentIndexL-1;
1814 // }
1815
1816 // pruneUnusedImgs()
1817 //______________________________________________________________________________
1818 GnuBook.prototype.pruneUnusedImgs = function() {
1819     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1820     for (var key in this.prefetchedImgs) {
1821         //console.log('key is ' + key);
1822         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1823             //console.log('removing key '+ key);
1824             $(this.prefetchedImgs[key]).remove();
1825         }
1826         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1827             //console.log('deleting key '+ key);
1828             delete this.prefetchedImgs[key];
1829         }
1830     }
1831 }
1832
1833 // prefetch()
1834 //______________________________________________________________________________
1835 GnuBook.prototype.prefetch = function() {
1836
1837     var lim = this.twoPage.currentIndexL-4;
1838     var i;
1839     lim = Math.max(lim, 0);
1840     for (i = lim; i < this.twoPage.currentIndexL; i++) {
1841         this.prefetchImg(i);
1842     }
1843     
1844     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1845         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1846         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1847             this.prefetchImg(i);
1848         }
1849     }
1850 }
1851
1852 // getPageWidth2UP()
1853 //______________________________________________________________________________
1854 GnuBook.prototype.getPageWidth2UP = function(index) {
1855     // We return the width based on the dominant height
1856     var height  = this.getPageHeight(index); 
1857     var width   = this.getPageWidth(index);    
1858     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1859 }    
1860
1861 // search()
1862 //______________________________________________________________________________
1863 GnuBook.prototype.search = function(term) {
1864     $('#GnuBookSearchScript').remove();
1865         var script  = document.createElement("script");
1866         script.setAttribute('id', 'GnuBookSearchScript');
1867         script.setAttribute("type", "text/javascript");
1868         script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1869         document.getElementsByTagName('head')[0].appendChild(script);
1870         $('#GnuBookSearchResults').html('Searching...');
1871 }
1872
1873 // GBSearchCallback()
1874 //______________________________________________________________________________
1875 GnuBook.prototype.GBSearchCallback = function(txt) {
1876     //alert(txt);
1877     if (jQuery.browser.msie) {
1878         var dom=new ActiveXObject("Microsoft.XMLDOM");
1879         dom.async="false";
1880         dom.loadXML(txt);    
1881     } else {
1882         var parser = new DOMParser();
1883         var dom = parser.parseFromString(txt, "text/xml");    
1884     }
1885     
1886     $('#GnuBookSearchResults').empty();    
1887     $('#GnuBookSearchResults').append('<ul>');
1888     
1889     for (var key in this.searchResults) {
1890         if (null != this.searchResults[key].div) {
1891             $(this.searchResults[key].div).remove();
1892         }
1893         delete this.searchResults[key];
1894     }
1895     
1896     var pages = dom.getElementsByTagName('PAGE');
1897     
1898     if (0 == pages.length) {
1899         // $$$ it would be nice to echo the (sanitized) search result here
1900         $('#GnuBookSearchResults').append('<li>No search results found</li>');
1901     } else {    
1902         for (var i = 0; i < pages.length; i++){
1903             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1904     
1905             
1906             var re = new RegExp (/_(\d{4})/);
1907             var reMatch = re.exec(pages[i].getAttribute('file'));
1908             var index = parseInt(reMatch[1], 10);
1909             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1910             
1911             var children = pages[i].childNodes;
1912             var context = '';
1913             for (var j=0; j<children.length; j++) {
1914                 //console.log(j + ' - ' + children[j].nodeName);
1915                 //console.log(children[j].firstChild.nodeValue);
1916                 if ('CONTEXT' == children[j].nodeName) {
1917                     context += children[j].firstChild.nodeValue;
1918                 } else if ('WORD' == children[j].nodeName) {
1919                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1920                     
1921                     var index = this.leafNumToIndex(index);
1922                     if (null != index) {
1923                         //coordinates are [left, bottom, right, top, [baseline]]
1924                         //we'll skip baseline for now...
1925                         var coords = children[j].getAttribute('coords').split(',',4);
1926                         if (4 == coords.length) {
1927                             this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1928                         }
1929                     }
1930                 }
1931             }
1932             var pageName = this.getPageName(index);
1933             //TODO: remove hardcoded instance name
1934             $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1935         }
1936     }
1937     $('#GnuBookSearchResults').append('</ul>');
1938
1939     this.updateSearchHilites();
1940 }
1941
1942 // updateSearchHilites()
1943 //______________________________________________________________________________
1944 GnuBook.prototype.updateSearchHilites = function() {
1945     if (2 == this.mode) {
1946         this.updateSearchHilites2UP();
1947     } else {
1948         this.updateSearchHilites1UP();
1949     }
1950 }
1951
1952 // showSearchHilites1UP()
1953 //______________________________________________________________________________
1954 GnuBook.prototype.updateSearchHilites1UP = function() {
1955
1956     for (var key in this.searchResults) {
1957         
1958         if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1959             var result = this.searchResults[key];
1960             if(null == result.div) {
1961                 result.div = document.createElement('div');
1962                 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1963                 //console.log('appending ' + key);
1964             }    
1965             $(result.div).css({
1966                 width:  (result.r-result.l)/this.reduce + 'px',
1967                 height: (result.b-result.t)/this.reduce + 'px',
1968                 left:   (result.l)/this.reduce + 'px',
1969                 top:    (result.t)/this.reduce +'px'
1970             });
1971
1972         } else {
1973             //console.log(key + ' not displayed');
1974             this.searchResults[key].div=null;
1975         }
1976     }
1977 }
1978
1979 // twoPageGutter()
1980 //______________________________________________________________________________
1981 // Returns the position of the gutter (line between the page images)
1982 GnuBook.prototype.twoPageGutter = function() {
1983     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1984 }
1985
1986 // twoPageTop()
1987 //______________________________________________________________________________
1988 // Returns the offset for the top of the page images
1989 GnuBook.prototype.twoPageTop = function() {
1990     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1991 }
1992
1993 // twoPageCoverWidth()
1994 //______________________________________________________________________________
1995 // Returns the width of the cover div given the total page width
1996 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
1997     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
1998 }
1999
2000 // twoPageGetViewCenter()
2001 //______________________________________________________________________________
2002 // Returns the percentage offset into twopageview div at the center of container div
2003 // { percentageX: float, percentageY: float }
2004 GnuBook.prototype.twoPageGetViewCenter = function() {
2005     var center = {};
2006
2007     var containerOffset = $('#GBcontainer').offset();
2008     var viewOffset = $('#GBtwopageview').offset();
2009     center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2010     center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2011     
2012     return center;
2013 }
2014
2015 // twoPageCenterView(percentageX, percentageY)
2016 //______________________________________________________________________________
2017 // Centers the point given by percentage from left,top of twopageview
2018 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2019     if ('undefined' == typeof(percentageX)) {
2020         percentageX = 0.5;
2021     }
2022     if ('undefined' == typeof(percentageY)) {
2023         percentageY = 0.5;
2024     }
2025
2026     var viewWidth = $('#GBtwopageview').width();
2027     var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2028     var intoViewX = percentageX * viewWidth;
2029     
2030     var viewHeight = $('#GBtwopageview').height();
2031     var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2032     var intoViewY = percentageY * viewHeight;
2033     
2034     if (viewWidth < containerClientWidth) {
2035         // Can fit width without scrollbars - center by adjusting offset
2036         $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2037     } else {
2038         // Need to scroll to center
2039         $('#GBtwopageview').css('left', 0);
2040         $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2041     }
2042     
2043     if (viewHeight < containerClientHeight) {
2044         // Fits with scrollbars - add offset
2045         $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2046     } else {
2047         $('#GBtwopageview').css('top', 0);
2048         $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2049     }
2050 }
2051     
2052 // showSearchHilites2UP()
2053 //______________________________________________________________________________
2054 GnuBook.prototype.updateSearchHilites2UP = function() {
2055
2056     for (var key in this.searchResults) {
2057         key = parseInt(key, 10);
2058         if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2059             var result = this.searchResults[key];
2060             if(null == result.div) {
2061                 result.div = document.createElement('div');
2062                 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2063                 //console.log('appending ' + key);
2064             }
2065
2066             // We calculate the reduction factor for the specific page because it can be different
2067             // for each page in the spread
2068             var height = this.getPageHeight(key);
2069             var width  = this.getPageWidth(key)
2070             var reduce = this.twoPage.height/height;
2071             var scaledW = parseInt(width*reduce);
2072             
2073             var gutter = this.twoPageGutter();
2074             var pageL;
2075             if ('L' == this.getPageSide(key)) {
2076                 pageL = gutter-scaledW;
2077             } else {
2078                 pageL = gutter;
2079             }
2080             var pageT  = this.twoPageTop();
2081             
2082             $(result.div).css({
2083                 width:  (result.r-result.l)*reduce + 'px',
2084                 height: (result.b-result.t)*reduce + 'px',
2085                 left:   pageL+(result.l)*reduce + 'px',
2086                 top:    pageT+(result.t)*reduce +'px'
2087             });
2088
2089         } else {
2090             //console.log(key + ' not displayed');
2091             if (null != this.searchResults[key].div) {
2092                 //console.log('removing ' + key);
2093                 $(this.searchResults[key].div).remove();
2094             }
2095             this.searchResults[key].div=null;
2096         }
2097     }
2098 }
2099
2100 // removeSearchHilites()
2101 //______________________________________________________________________________
2102 GnuBook.prototype.removeSearchHilites = function() {
2103     for (var key in this.searchResults) {
2104         if (null != this.searchResults[key].div) {
2105             $(this.searchResults[key].div).remove();
2106             this.searchResults[key].div=null;
2107         }        
2108     }
2109 }
2110
2111 // showEmbedCode()
2112 //______________________________________________________________________________
2113 GnuBook.prototype.showEmbedCode = function() {
2114     if (null != this.embedPopup) { // check if already showing
2115         return;
2116     }
2117     this.autoStop();
2118     this.embedPopup = document.createElement("div");
2119     $(this.embedPopup).css({
2120         position: 'absolute',
2121         top:      '20px',
2122         left:     ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2123         width:    '400px',
2124         padding:  "20px",
2125         border:   "3px double #999999",
2126         zIndex:   3,
2127         backgroundColor: "#fff"
2128     }).appendTo('#GnuBook');
2129
2130     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2131     htmlStr += '<p>The bookreader uses iframes for embedding. It will not work on web hosts that block iframes. The embed feature has been tested on blogspot.com blogs as well as self-hosted Wordpress blogs. This feature will NOT work on wordpress.com blogs.</p>';
2132     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2133     htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2134
2135     this.embedPopup.innerHTML = htmlStr;
2136     $(this.embedPopup).find('input').bind('click', function() {
2137         this.select();
2138     })
2139 }
2140
2141 // autoToggle()
2142 //______________________________________________________________________________
2143 GnuBook.prototype.autoToggle = function() {
2144
2145     var bComingFrom1up = false;
2146     if (2 != this.mode) {
2147         bComingFrom1up = true;
2148         this.switchMode(2);
2149     }
2150     
2151     // Change to autofit if book is too large
2152     if (this.reduce < this.twoPageGetAutofitReduce()) {
2153         this.zoom2up(0);
2154     }
2155
2156     var self = this;
2157     if (null == this.autoTimer) {
2158         this.flipSpeed = 2000;
2159         
2160         // $$$ Draw events currently cause layout problems when they occur during animation.
2161         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2162         //     we workaround for now by not triggering immediate animation in that case.
2163         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2164         if (('rl' == this.pageProgression) && bComingFrom1up) {
2165             // don't flip immediately -- wait until timer fires
2166         } else {
2167             // flip immediately
2168             this.flipFwdToIndex();        
2169         }
2170
2171         $('#GBtoolbar .play').hide();
2172         $('#GBtoolbar .pause').show();
2173         this.autoTimer=setInterval(function(){
2174             if (self.animating) {return;}
2175             
2176             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2177                 self.flipBackToIndex(1); // $$$ really what we want?
2178             } else {            
2179                 self.flipFwdToIndex();
2180             }
2181         },5000);
2182     } else {
2183         this.autoStop();
2184     }
2185 }
2186
2187 // autoStop()
2188 //______________________________________________________________________________
2189 // Stop autoplay mode, allowing animations to finish
2190 GnuBook.prototype.autoStop = function() {
2191     if (null != this.autoTimer) {
2192         clearInterval(this.autoTimer);
2193         this.flipSpeed = 'fast';
2194         $('#GBtoolbar .pause').hide();
2195         $('#GBtoolbar .play').show();
2196         this.autoTimer = null;
2197     }
2198 }
2199
2200 // stopFlipAnimations
2201 //______________________________________________________________________________
2202 // Immediately stop flip animations.  Callbacks are triggered.
2203 GnuBook.prototype.stopFlipAnimations = function() {
2204
2205     this.autoStop(); // Clear timers
2206
2207     // Stop animation, clear queue, trigger callbacks
2208     if (this.leafEdgeTmp) {
2209         $(this.leafEdgeTmp).stop(false, true);
2210     }
2211     jQuery.each(this.prefetchedImgs, function() {
2212         $(this).stop(false, true);
2213         });
2214
2215     // And again since animations also queued in callbacks
2216     if (this.leafEdgeTmp) {
2217         $(this.leafEdgeTmp).stop(false, true);
2218     }
2219     jQuery.each(this.prefetchedImgs, function() {
2220         $(this).stop(false, true);
2221         });
2222    
2223 }
2224
2225 // keyboardNavigationIsDisabled(event)
2226 //   - returns true if keyboard navigation should be disabled for the event
2227 //______________________________________________________________________________
2228 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2229     if (event.target.tagName == "INPUT") {
2230         return true;
2231     }   
2232     return false;
2233 }
2234
2235 // gutterOffsetForIndex
2236 //______________________________________________________________________________
2237 //
2238 // Returns the gutter offset for the spread containing the given index.
2239 // This function supports RTL
2240 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2241
2242     // To find the offset of the gutter from the middle we calculate our percentage distance
2243     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2244     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2245     
2246     // But then again for RTL it's the opposite
2247     if ('rl' == this.pageProgression) {
2248         offset = -offset;
2249     }
2250     
2251     return offset;
2252 }
2253
2254 // leafEdgeWidth
2255 //______________________________________________________________________________
2256 // Returns the width of the leaf edge div for the page with index given
2257 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2258     // $$$ could there be single pixel rounding errors for L vs R?
2259     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2260         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2261     } else {
2262         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2263     }
2264 }
2265
2266 // jumpIndexForLeftEdgePageX
2267 //______________________________________________________________________________
2268 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2269 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2270     if ('rl' != this.pageProgression) {
2271         // LTR - flipping backward
2272         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2273
2274         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
2275         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2276         return jumpIndex;
2277
2278     } else {
2279         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2280         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2281         return jumpIndex;
2282     }
2283 }
2284
2285 // jumpIndexForRightEdgePageX
2286 //______________________________________________________________________________
2287 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2288 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2289     if ('rl' != this.pageProgression) {
2290         // LTR
2291         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2292         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2293         return jumpIndex;
2294     } else {
2295         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2296         jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2297         return jumpIndex;
2298     }
2299 }
2300
2301 GnuBook.prototype.initToolbar = function(mode, ui) {
2302
2303     $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2304         + "<a class='GBicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
2305         + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>" 
2306         + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2307         + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2308         + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2309         + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2310         + "&nbsp;&nbsp;<a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2311         + "</span></div>");
2312     
2313     this.updateToolbarZoom(); // Pretty format
2314         
2315     if (ui == "embed") {
2316         $("#GnuBook a.logo").attr("target","_blank");
2317     }
2318
2319     // $$$ turn this into a member variable
2320     var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2321     
2322     // We build in mode 2
2323     jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2324         + "<button class='GBicon rollover embed' />"
2325         + "<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>"
2326         + "<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>"
2327         + "<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>"
2328         + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2329
2330     this.bindToolbarNavHandlers(jToolbar);
2331     
2332     // Setup tooltips -- later we could load these from a file for i18n
2333     var titles = { '.logo': 'Go to Archive.org',
2334                    '.zoom_in': 'Zoom in',
2335                    '.zoom_out': 'Zoom out',
2336                    '.one_page_mode': 'One-page view',
2337                    '.two_page_mode': 'Two-page view',
2338                    '.embed': 'Embed bookreader',
2339                    '.book_left': 'Flip left',
2340                    '.book_right': 'Flip right',
2341                    '.book_up': 'Page up',
2342                    '.book_down': 'Page down',
2343                    '.play': 'Play',
2344                    '.pause': 'Pause',
2345                    '.book_top': 'First page',
2346                    '.book_bottom': 'Last page'
2347                   };
2348     if ('rl' == this.pageProgression) {
2349         titles['.book_leftmost'] = 'Last page';
2350         titles['.book_rightmost'] = 'First page';
2351     } else { // LTR
2352         titles['.book_leftmost'] = 'First page';
2353         titles['.book_rightmost'] = 'Last page';
2354     }
2355                   
2356     for (var icon in titles) {
2357         jToolbar.find(icon).attr('title', titles[icon]);
2358     }
2359     
2360     // Hide mode buttons and autoplay if 2up is not available
2361     // $$$ if we end up with more than two modes we should show the applicable buttons
2362     if ( !this.canSwitchToMode(this.constMode2up) ) {
2363         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2364     }
2365
2366     // Switch to requested mode -- binds other click handlers
2367     this.switchToolbarMode(mode);
2368
2369 }
2370
2371
2372 // switchToolbarMode
2373 //______________________________________________________________________________
2374 // Update the toolbar for the given mode (changes navigation buttons)
2375 // $$$ we should soon split the toolbar out into its own module
2376 GnuBook.prototype.switchToolbarMode = function(mode) {
2377     if (1 == mode) {
2378         // 1-up     
2379         $('#GBtoolbar .GBtoolbarmode2').hide();
2380         $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2381     } else {
2382         // 2-up
2383         $('#GBtoolbar .GBtoolbarmode1').hide();
2384         $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2385     }
2386 }
2387
2388 // bindToolbarNavHandlers
2389 //______________________________________________________________________________
2390 // Binds the toolbar handlers
2391 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2392
2393     jToolbar.find('.book_left').bind('click', function(e) {
2394         gb.left();
2395         return false;
2396     });
2397          
2398     jToolbar.find('.book_right').bind('click', function(e) {
2399         gb.right();
2400         return false;
2401     });
2402         
2403     jToolbar.find('.book_up').bind('click', function(e) {
2404         gb.prev();
2405         return false;
2406     });        
2407         
2408     jToolbar.find('.book_down').bind('click', function(e) {
2409         gb.next();
2410         return false;
2411     });
2412         
2413     jToolbar.find('.embed').bind('click', function(e) {
2414         gb.showEmbedCode();
2415         return false;
2416     });
2417
2418     jToolbar.find('.play').bind('click', function(e) {
2419         gb.autoToggle();
2420         return false;
2421     });
2422
2423     jToolbar.find('.pause').bind('click', function(e) {
2424         gb.autoToggle();
2425         return false;
2426     });
2427     
2428     jToolbar.find('.book_top').bind('click', function(e) {
2429         gb.first();
2430         return false;
2431     });
2432
2433     jToolbar.find('.book_bottom').bind('click', function(e) {
2434         gb.last();
2435         return false;
2436     });
2437     
2438     jToolbar.find('.book_leftmost').bind('click', function(e) {
2439         gb.leftmost();
2440         return false;
2441     });
2442   
2443     jToolbar.find('.book_rightmost').bind('click', function(e) {
2444         gb.rightmost();
2445         return false;
2446     });
2447 }
2448
2449 // updateToolbarZoom(reduce)
2450 //______________________________________________________________________________
2451 // Update the displayed zoom factor based on reduction factor
2452 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2453     var value;
2454     if (this.twoPage.autofit) {
2455         value = 'Auto';
2456     } else {
2457         value = (100 / reduce).toFixed(2);
2458         // Strip trailing zeroes and decimal if all zeroes
2459         value = value.replace(/0+$/,'');
2460         value = value.replace(/\.$/,'');
2461         value += '%';
2462     }
2463     $('#GBzoom').text(value);
2464 }
2465
2466 // firstDisplayableIndex
2467 //______________________________________________________________________________
2468 // Returns the index of the first visible page, dependent on the mode.
2469 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2470 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2471 GnuBook.prototype.firstDisplayableIndex = function() {
2472     if (this.mode == 0) {
2473         return 0;
2474     } else {
2475         return 1; // $$$ we assume there are enough pages... we need logic for very short books
2476     }
2477 }
2478
2479 // lastDisplayableIndex
2480 //______________________________________________________________________________
2481 // Returns the index of the last visible page, dependent on the mode.
2482 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2483 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
2484 GnuBook.prototype.lastDisplayableIndex = function() {
2485     if (this.mode == 2) {
2486         if (this.lastDisplayableIndex2up === null) {
2487             // Calculate and cache
2488             var candidate = this.numLeafs - 1;
2489             for ( ; candidate >= 0; candidate--) {
2490                 var spreadIndices = this.getSpreadIndices(candidate);
2491                 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2492                     break;
2493                 }
2494             }
2495             this.lastDisplayableIndex2up = candidate;
2496         }
2497         return this.lastDisplayableIndex2up;
2498     } else {
2499         return this.numLeafs - 1;
2500     }
2501 }
2502
2503 // shortTitle(maximumCharacters)
2504 //________
2505 // Returns a shortened version of the title with the maximum number of characters
2506 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2507     if (this.bookTitle.length < maximumCharacters) {
2508         return this.bookTitle;
2509     }
2510     
2511     var title = this.bookTitle.substr(0, maximumCharacters - 3);
2512     title += '...';
2513     return title;
2514 }
2515
2516
2517
2518 // Parameter related functions
2519
2520 // updateFromParams(params)
2521 //________
2522 // Update ourselves from the params object.
2523 //
2524 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2525 GnuBook.prototype.updateFromParams = function(params) {
2526     if ('undefined' != typeof(params.mode)) {
2527         this.switchMode(params.mode);
2528     }
2529
2530     // $$$ process /search
2531     // $$$ process /zoom
2532     
2533     // We only respect page if index is not set
2534     if ('undefined' != typeof(params.index)) {
2535         if (params.index != this.currentIndex()) {
2536             this.jumpToIndex(params.index);
2537         }
2538     } else if ('undefined' != typeof(params.page)) {
2539         // $$$ this assumes page numbers are unique
2540         if (params.page != this.getPageNum(this.currentIndex())) {
2541             this.jumpToPage(params.page);
2542         }
2543     }
2544     
2545     // $$$ process /region
2546     // $$$ process /highlight
2547 }
2548
2549 // paramsFromFragment(urlFragment)
2550 //________
2551 // Returns a object with configuration parametes from a URL fragment.
2552 //
2553 // E.g paramsFromFragment(window.location.hash)
2554 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2555     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2556     
2557     var params = {};
2558     
2559     // For convenience we allow an initial # character (as from window.location.hash)
2560     // but don't require it
2561     if (urlFragment.substr(0,1) == '#') {
2562         urlFragment = urlFragment.substr(1);
2563     }
2564     
2565     // Simple #nn syntax
2566     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2567     if ( !isNaN(oldStyleLeafNum) ) {
2568         params.index = oldStyleLeafNum;
2569         
2570         // Done processing if using old-style syntax
2571         return params;
2572     }
2573     
2574     // Split into key-value pairs
2575     var urlArray = urlFragment.split('/');
2576     var urlHash = {};
2577     for (var i = 0; i < urlArray.length; i += 2) {
2578         urlHash[urlArray[i]] = urlArray[i+1];
2579     }
2580     
2581     // Mode
2582     if ('1up' == urlHash['mode']) {
2583         params.mode = this.constMode1up;
2584     } else if ('2up' == urlHash['mode']) {
2585         params.mode = this.constMode2up;
2586     }
2587     
2588     // Index and page
2589     if ('undefined' != typeof(urlHash['page'])) {
2590         // page was set -- may not be int
2591         params.page = urlHash['page'];
2592     }
2593     
2594     // $$$ process /region
2595     // $$$ process /search
2596     // $$$ process /highlight
2597         
2598     return params;
2599 }
2600
2601 // paramsFromCurrent()
2602 //________
2603 // Create a params object from the current parameters.
2604 GnuBook.prototype.paramsFromCurrent = function() {
2605
2606     var params = {};
2607
2608     var pageNum = this.getPageNum(this.currentIndex());
2609     if ((pageNum === 0) || pageNum) {
2610         params.page = pageNum;
2611     }
2612     
2613     params.index = this.currentIndex();
2614     params.mode = this.mode;
2615     
2616     // $$$ highlight
2617     // $$$ region
2618     // $$$ search
2619     
2620     return params;
2621 }
2622
2623 // fragmentFromParams(params)
2624 //________
2625 // Create a fragment string from the params object.
2626 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2627 GnuBook.prototype.fragmentFromParams = function(params) {
2628     var separator = '/';
2629     
2630     var fragments = [];
2631     
2632     if ('undefined' != typeof(params.page)) {
2633         fragments.push('page', params.page);
2634     } else {
2635         // Don't have page numbering -- use index instead
2636         fragments.push('page', 'n' + params.index);
2637     }
2638     
2639     // $$$ highlight
2640     // $$$ region
2641     // $$$ search
2642     
2643     // mode
2644     if ('undefined' != typeof(params.mode)) {    
2645         if (params.mode == this.constMode1up) {
2646             fragments.push('mode', '1up');
2647         } else if (params.mode == this.constMode2up) {
2648             fragments.push('mode', '2up');
2649         } else {
2650             throw 'fragmentFromParams called with unknown mode ' + params.mode;
2651         }
2652     }
2653     
2654     return fragments.join(separator);
2655 }
2656
2657 // getPageIndex(pageNum)
2658 //________
2659 // Returns the *highest* index the given page number, or undefined
2660 GnuBook.prototype.getPageIndex = function(pageNum) {
2661     var pageIndices = this.getPageIndices(pageNum);
2662     
2663     if (pageIndices.length > 0) {
2664         return pageIndices[pageIndices.length - 1];
2665     }
2666
2667     return undefined;
2668 }
2669
2670 // getPageIndices(pageNum)
2671 //________
2672 // Returns an array (possibly empty) of the indices with the given page number
2673 GnuBook.prototype.getPageIndices = function(pageNum) {
2674     var indices = [];
2675
2676     // Check for special "nXX" page number
2677     if (pageNum.slice(0,1) == 'n') {
2678         try {
2679             var pageIntStr = pageNum.slice(1, pageNum.length);
2680             var pageIndex = parseInt(pageIntStr);
2681             indices.append(pageIndex);
2682             return indices;
2683         } catch(err) {
2684             // Do nothing... will run through page names and see if one matches
2685         }
2686     }
2687
2688     var i;
2689     for (i=0; i<this.numLeafs; i++) {
2690         if (this.getPageNum(i) == pageNum) {
2691             indices.push(i);
2692         }
2693     }
2694     
2695     return indices;
2696 }
2697
2698 // getPageName(index)
2699 //________
2700 // Returns the name of the page as it should be displayed in the user interface
2701 GnuBook.prototype.getPageName = function(index) {
2702     return 'Page ' + this.getPageNum(index);
2703 }
2704
2705 // updateLocationHash
2706 //________
2707 // Update the location hash from the current parameters.  Call this instead of manually
2708 // using window.location.replace
2709 GnuBook.prototype.updateLocationHash = function() {
2710     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2711     window.location.replace(newHash);
2712     
2713     // This is the variable checked in the timer.  Only user-generated changes
2714     // to the URL will trigger the event.
2715     this.oldLocationHash = newHash;
2716 }
2717
2718 // startLocationPolling
2719 //________
2720 // Starts polling of window.location to see hash fragment changes
2721 GnuBook.prototype.startLocationPolling = function() {
2722     var self = this; // remember who I am
2723     self.oldLocationHash = window.location.hash;
2724     
2725     if (this.locationPollId) {
2726         clearInterval(this.locationPollID);
2727         this.locationPollId = null;
2728     }
2729     
2730     this.locationPollId = setInterval(function() {
2731         var newHash = window.location.hash;
2732         if (newHash != self.oldLocationHash) {
2733             if (newHash != self.oldUserHash) { // Only process new user hash once
2734                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2735                 
2736                 // Queue change if animating
2737                 if (self.animating) {
2738                     self.autoStop();
2739                     self.animationFinishedCallback = function() {
2740                         self.updateFromParams(self.paramsFromFragment(newHash));
2741                     }                        
2742                 } else { // update immediately
2743                     self.updateFromParams(self.paramsFromFragment(newHash));
2744                 }
2745                 self.oldUserHash = newHash;
2746             }
2747         }
2748     }, 500);
2749 }
2750
2751 // getEmbedURL
2752 //________
2753 // Returns a URL for an embedded version of the current book
2754 GnuBook.prototype.getEmbedURL = function() {
2755     // We could generate a URL hash fragment here but for now we just leave at defaults
2756     return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2757 }
2758
2759 // getEmbedCode
2760 //________
2761 // Returns the embed code HTML fragment suitable for copy and paste
2762 GnuBook.prototype.getEmbedCode = function() {
2763     return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2764 }
2765
2766 // canSwitchToMode
2767 //________
2768 // Returns true if we can switch to the requested mode
2769 GnuBook.prototype.canSwitchToMode = function(mode) {
2770     if (mode == this.constMode2up) {
2771         // check there are enough pages to display
2772         // $$$ this is a workaround for the mis-feature that we can't display
2773         //     short books in 2up mode
2774         if (this.numLeafs < 6) {
2775             return false;
2776         }
2777     }
2778     
2779     return true;
2780 }
2781
2782 // Library functions
2783 GnuBook.util = {
2784     clamp: function(value, min, max) {
2785         return Math.min(Math.max(value, min), max);
2786     }
2787 }