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