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