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