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