Revert unintended "Merge branch 'read_aloud' of git@github.com:openlibrary/bookreader"
[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         if (index < 0 || index > (this.numLeafs - 1) ) {
2313             // Facing page at beginning or end, or beyond
2314             $(img).css({
2315                 'background-color': 'transparent'
2316             });
2317         }
2318         img.src = pageURI;
2319         img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2320         this.prefetchedImgs[index] = img;
2321     }
2322 }
2323
2324
2325 // prepareFlipLeftToRight()
2326 //
2327 //______________________________________________________________________________
2328 //
2329 // Prepare to flip the left page towards the right.  This corresponds to moving
2330 // backward when the page progression is left to right.
2331 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2332
2333     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
2334
2335     this.prefetchImg(prevL);
2336     this.prefetchImg(prevR);
2337     
2338     var height  = this._getPageHeight(prevL); 
2339     var width   = this._getPageWidth(prevL);    
2340     var middle = this.twoPage.middle;
2341     var top  = this.twoPageTop();                
2342     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2343
2344     // The gutter is the dividing line between the left and right pages.
2345     // It is offset from the middle to create the illusion of thickness to the pages
2346     var gutter = middle + this.gutterOffsetForIndex(prevL);
2347     
2348     //console.log('    gutter for ' + prevL + ' is ' + gutter);
2349     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
2350     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2351     
2352     leftCSS = {
2353         position: 'absolute',
2354         left: gutter-scaledW+'px',
2355         right: '', // clear right property
2356         top:    top+'px',
2357         height: this.twoPage.height,
2358         width:  scaledW+'px',
2359         borderRight: '1px solid black',
2360         zIndex: 1
2361     }
2362     
2363     $(this.prefetchedImgs[prevL]).css(leftCSS);
2364
2365     $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2366
2367     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2368
2369     rightCSS = {
2370         position: 'absolute',
2371         left:   gutter+'px',
2372         right: '',
2373         top:    top+'px',
2374         height: this.twoPage.height,
2375         width:  '0px',
2376         borderLeft: '1px solid black',
2377         zIndex: 2
2378     }
2379     
2380     $(this.prefetchedImgs[prevR]).css(rightCSS);
2381
2382     $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2383             
2384 }
2385
2386 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2387 // prepareFlipRightToLeft()
2388 //______________________________________________________________________________
2389 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2390
2391     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
2392
2393     // Prefetch images
2394     this.prefetchImg(nextL);
2395     this.prefetchImg(nextR);
2396
2397     var height  = this._getPageHeight(nextR); 
2398     var width   = this._getPageWidth(nextR);    
2399     var middle = this.twoPage.middle;
2400     var top  = this.twoPageTop();               
2401     var scaledW = this.twoPage.height*width/height;
2402
2403     var gutter = middle + this.gutterOffsetForIndex(nextL);
2404         
2405     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2406     $(this.prefetchedImgs[nextR]).css({
2407         position: 'absolute',
2408         left:   gutter+'px',
2409         top:    top+'px',
2410         height: this.twoPage.height,
2411         width:  scaledW+'px',
2412         borderLeft: '1px solid black',
2413         zIndex: 1
2414     });
2415
2416     $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2417
2418     height  = this._getPageHeight(nextL); 
2419     width   = this._getPageWidth(nextL);      
2420     scaledW = this.twoPage.height*width/height;
2421
2422     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2423     $(this.prefetchedImgs[nextL]).css({
2424         position: 'absolute',
2425         right:   $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2426         top:    top+'px',
2427         height: this.twoPage.height,
2428         width:  0+'px', // Start at 0 width, then grow to the left
2429         borderRight: '1px solid black',
2430         zIndex: 2
2431     });
2432
2433     $('#BRtwopageview').append(this.prefetchedImgs[nextL]);    
2434             
2435 }
2436
2437 // getNextLeafs() -- NOT RTL AWARE
2438 //______________________________________________________________________________
2439 // BookReader.prototype.getNextLeafs = function(o) {
2440 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2441 //     //For now, assume that leafs are contiguous.
2442 //     
2443 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2444 //     o.L = this.twoPage.currentIndexL+2;
2445 //     o.R = this.twoPage.currentIndexL+3;
2446 // }
2447
2448 // getprevLeafs() -- NOT RTL AWARE
2449 //______________________________________________________________________________
2450 // BookReader.prototype.getPrevLeafs = function(o) {
2451 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2452 //     //For now, assume that leafs are contiguous.
2453 //     
2454 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2455 //     o.L = this.twoPage.currentIndexL-2;
2456 //     o.R = this.twoPage.currentIndexL-1;
2457 // }
2458
2459 // pruneUnusedImgs()
2460 //______________________________________________________________________________
2461 BookReader.prototype.pruneUnusedImgs = function() {
2462     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2463     for (var key in this.prefetchedImgs) {
2464         //console.log('key is ' + key);
2465         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2466             //console.log('removing key '+ key);
2467             $(this.prefetchedImgs[key]).remove();
2468         }
2469         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2470             //console.log('deleting key '+ key);
2471             delete this.prefetchedImgs[key];
2472         }
2473     }
2474 }
2475
2476 // prefetch()
2477 //______________________________________________________________________________
2478 BookReader.prototype.prefetch = function() {
2479
2480     // $$$ We should check here if the current indices have finished
2481     //     loading (with some timeout) before loading more page images
2482     //     See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2483
2484     // prefetch visible pages first
2485     this.prefetchImg(this.twoPage.currentIndexL);
2486     this.prefetchImg(this.twoPage.currentIndexR);
2487         
2488     var adjacentPagesToLoad = 3;
2489     
2490     var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2491     var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2492         
2493     var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2494     var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2495     
2496     // Load images spreading out from current
2497     for (var i = 1; i <= adjacentPagesToLoad; i++) {
2498         var goingDown = lowCurrent - i;
2499         if (goingDown >= start) {
2500             this.prefetchImg(goingDown);
2501         }
2502         var goingUp = highCurrent + i;
2503         if (goingUp <= end) {
2504             this.prefetchImg(goingUp);
2505         }
2506     }
2507
2508     /*
2509     var lim = this.twoPage.currentIndexL-4;
2510     var i;
2511     lim = Math.max(lim, 0);
2512     for (i = lim; i < this.twoPage.currentIndexL; i++) {
2513         this.prefetchImg(i);
2514     }
2515     
2516     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2517         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2518         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2519             this.prefetchImg(i);
2520         }
2521     }
2522     */
2523 }
2524
2525 // getPageWidth2UP()
2526 //______________________________________________________________________________
2527 BookReader.prototype.getPageWidth2UP = function(index) {
2528     // We return the width based on the dominant height
2529     var height  = this._getPageHeight(index); 
2530     var width   = this._getPageWidth(index);    
2531     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2532 }    
2533
2534 // search()
2535 //______________________________________________________________________________
2536 BookReader.prototype.search = function(term) {
2537     term = term.replace(/\//g, ' '); // strip slashes
2538     this.searchTerm = term;
2539     $('#BookReaderSearchScript').remove();
2540     var script  = document.createElement("script");
2541     script.setAttribute('id', 'BookReaderSearchScript');
2542     script.setAttribute("type", "text/javascript");
2543     script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2544     document.getElementsByTagName('head')[0].appendChild(script);
2545     $('#BookReaderSearchBox').val(term);
2546     $('#BookReaderSearchResults').html('Searching...');
2547 }
2548
2549 // BRSearchCallback()
2550 //______________________________________________________________________________
2551 BookReader.prototype.BRSearchCallback = function(txt) {
2552     //alert(txt);
2553     if (jQuery.browser.msie) {
2554         var dom=new ActiveXObject("Microsoft.XMLDOM");
2555         dom.async="false";
2556         dom.loadXML(txt);    
2557     } else {
2558         var parser = new DOMParser();
2559         var dom = parser.parseFromString(txt, "text/xml");    
2560     }
2561     
2562     $('#BookReaderSearchResults').empty();    
2563     $('#BookReaderSearchResults').append('<ul>');
2564     
2565     for (var key in this.searchResults) {
2566         if (null != this.searchResults[key].div) {
2567             $(this.searchResults[key].div).remove();
2568         }
2569         delete this.searchResults[key];
2570     }
2571     
2572     var pages = dom.getElementsByTagName('PAGE');
2573     
2574     if (0 == pages.length) {
2575         // $$$ it would be nice to echo the (sanitized) search result here
2576         $('#BookReaderSearchResults').append('<li>No search results found</li>');
2577     } else {    
2578         for (var i = 0; i < pages.length; i++){
2579             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2580     
2581             
2582             var re = new RegExp (/_(\d{4})\.djvu/);
2583             var reMatch = re.exec(pages[i].getAttribute('file'));
2584             var index = parseInt(reMatch[1], 10);
2585             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2586             
2587             var children = pages[i].childNodes;
2588             var context = '';
2589             for (var j=0; j<children.length; j++) {
2590                 //console.log(j + ' - ' + children[j].nodeName);
2591                 //console.log(children[j].firstChild.nodeValue);
2592                 if ('CONTEXT' == children[j].nodeName) {
2593                     context += children[j].firstChild.nodeValue;
2594                 } else if ('WORD' == children[j].nodeName) {
2595                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2596                     
2597                     var index = this.leafNumToIndex(index);
2598                     if (null != index) {
2599                         //coordinates are [left, bottom, right, top, [baseline]]
2600                         //we'll skip baseline for now...
2601                         var coords = children[j].getAttribute('coords').split(',',4);
2602                         if (4 == coords.length) {
2603                             this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2604                         }
2605                     }
2606                 }
2607             }
2608             var pageName = this.getPageName(index);
2609             var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2610             var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2611             //TODO: remove hardcoded instance name
2612             $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2613         }
2614     }
2615     $('#BookReaderSearchResults').append('</ul>');
2616
2617     // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2618     $('#BookReaderSearchBox').val(this.searchTerm);
2619
2620     this.updateSearchHilites();
2621 }
2622
2623 // updateSearchHilites()
2624 //______________________________________________________________________________
2625 BookReader.prototype.updateSearchHilites = function() {
2626     if (2 == this.mode) {
2627         this.updateSearchHilites2UP();
2628     } else {
2629         this.updateSearchHilites1UP();
2630     }
2631 }
2632
2633 // showSearchHilites1UP()
2634 //______________________________________________________________________________
2635 BookReader.prototype.updateSearchHilites1UP = function() {
2636
2637     for (var key in this.searchResults) {
2638         
2639         if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2640             var result = this.searchResults[key];
2641             if (null == result.div) {
2642                 result.div = document.createElement('div');
2643                 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2644                 //console.log('appending ' + key);
2645             }    
2646             $(result.div).css({
2647                 width:  (result.r-result.l)/this.reduce + 'px',
2648                 height: (result.b-result.t)/this.reduce + 'px',
2649                 left:   (result.l)/this.reduce + 'px',
2650                 top:    (result.t)/this.reduce +'px'
2651             });
2652
2653         } else {
2654             //console.log(key + ' not displayed');
2655             this.searchResults[key].div=null;
2656         }
2657     }
2658 }
2659
2660 // twoPageGutter()
2661 //______________________________________________________________________________
2662 // Returns the position of the gutter (line between the page images)
2663 BookReader.prototype.twoPageGutter = function() {
2664     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2665 }
2666
2667 // twoPageTop()
2668 //______________________________________________________________________________
2669 // Returns the offset for the top of the page images
2670 BookReader.prototype.twoPageTop = function() {
2671     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2672 }
2673
2674 // twoPageCoverWidth()
2675 //______________________________________________________________________________
2676 // Returns the width of the cover div given the total page width
2677 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2678     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2679 }
2680
2681 // twoPageGetViewCenter()
2682 //______________________________________________________________________________
2683 // Returns the percentage offset into twopageview div at the center of container div
2684 // { percentageX: float, percentageY: float }
2685 BookReader.prototype.twoPageGetViewCenter = function() {
2686     var center = {};
2687
2688     var containerOffset = $('#BRcontainer').offset();
2689     var viewOffset = $('#BRtwopageview').offset();
2690     center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2691     center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2692     
2693     return center;
2694 }
2695
2696 // twoPageCenterView(percentageX, percentageY)
2697 //______________________________________________________________________________
2698 // Centers the point given by percentage from left,top of twopageview
2699 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2700     if ('undefined' == typeof(percentageX)) {
2701         percentageX = 0.5;
2702     }
2703     if ('undefined' == typeof(percentageY)) {
2704         percentageY = 0.5;
2705     }
2706
2707     var viewWidth = $('#BRtwopageview').width();
2708     var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2709     var intoViewX = percentageX * viewWidth;
2710     
2711     var viewHeight = $('#BRtwopageview').height();
2712     var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2713     var intoViewY = percentageY * viewHeight;
2714     
2715     if (viewWidth < containerClientWidth) {
2716         // Can fit width without scrollbars - center by adjusting offset
2717         $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2718     } else {
2719         // Need to scroll to center
2720         $('#BRtwopageview').css('left', 0);
2721         $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2722     }
2723     
2724     if (viewHeight < containerClientHeight) {
2725         // Fits with scrollbars - add offset
2726         $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2727     } else {
2728         $('#BRtwopageview').css('top', 0);
2729         $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2730     }
2731 }
2732
2733 // twoPageFlipAreaHeight
2734 //______________________________________________________________________________
2735 // Returns the integer height of the click-to-flip areas at the edges of the book
2736 BookReader.prototype.twoPageFlipAreaHeight = function() {
2737     return parseInt(this.twoPage.height);
2738 }
2739
2740 // twoPageFlipAreaWidth
2741 //______________________________________________________________________________
2742 // Returns the integer width of the flip areas 
2743 BookReader.prototype.twoPageFlipAreaWidth = function() {
2744     var max = 100; // $$$ TODO base on view width?
2745     var min = 10;
2746     
2747     var width = this.twoPage.width * 0.15;
2748     return parseInt(BookReader.util.clamp(width, min, max));
2749 }
2750
2751 // twoPageFlipAreaTop
2752 //______________________________________________________________________________
2753 // Returns integer top offset for flip areas
2754 BookReader.prototype.twoPageFlipAreaTop = function() {
2755     return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2756 }
2757
2758 // twoPageLeftFlipAreaLeft
2759 //______________________________________________________________________________
2760 // Left offset for left flip area
2761 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2762     return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2763 }
2764
2765 // twoPageRightFlipAreaLeft
2766 //______________________________________________________________________________
2767 // Left offset for right flip area
2768 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2769     return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2770 }
2771
2772 // twoPagePlaceFlipAreas
2773 //______________________________________________________________________________
2774 // Readjusts position of flip areas based on current layout
2775 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2776     // We don't set top since it shouldn't change relative to view
2777     $(this.twoPage.leftFlipArea).css({
2778         left: this.twoPageLeftFlipAreaLeft() + 'px',
2779         width: this.twoPageFlipAreaWidth() + 'px'
2780     });
2781     $(this.twoPage.rightFlipArea).css({
2782         left: this.twoPageRightFlipAreaLeft() + 'px',
2783         width: this.twoPageFlipAreaWidth() + 'px'
2784     });
2785 }
2786     
2787 // showSearchHilites2UP()
2788 //______________________________________________________________________________
2789 BookReader.prototype.updateSearchHilites2UP = function() {
2790
2791     for (var key in this.searchResults) {
2792         key = parseInt(key, 10);
2793         if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2794             var result = this.searchResults[key];
2795             if (null == result.div) {
2796                 result.div = document.createElement('div');
2797                 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2798                 //console.log('appending ' + key);
2799             }
2800
2801             // We calculate the reduction factor for the specific page because it can be different
2802             // for each page in the spread
2803             var height = this._getPageHeight(key);
2804             var width  = this._getPageWidth(key)
2805             var reduce = this.twoPage.height/height;
2806             var scaledW = parseInt(width*reduce);
2807             
2808             var gutter = this.twoPageGutter();
2809             var pageL;
2810             if ('L' == this.getPageSide(key)) {
2811                 pageL = gutter-scaledW;
2812             } else {
2813                 pageL = gutter;
2814             }
2815             var pageT  = this.twoPageTop();
2816             
2817             $(result.div).css({
2818                 width:  (result.r-result.l)*reduce + 'px',
2819                 height: (result.b-result.t)*reduce + 'px',
2820                 left:   pageL+(result.l)*reduce + 'px',
2821                 top:    pageT+(result.t)*reduce +'px'
2822             });
2823
2824         } else {
2825             //console.log(key + ' not displayed');
2826             if (null != this.searchResults[key].div) {
2827                 //console.log('removing ' + key);
2828                 $(this.searchResults[key].div).remove();
2829             }
2830             this.searchResults[key].div=null;
2831         }
2832     }
2833 }
2834
2835 // removeSearchHilites()
2836 //______________________________________________________________________________
2837 BookReader.prototype.removeSearchHilites = function() {
2838     for (var key in this.searchResults) {
2839         if (null != this.searchResults[key].div) {
2840             $(this.searchResults[key].div).remove();
2841             this.searchResults[key].div=null;
2842         }        
2843     }
2844 }
2845
2846 // printPage
2847 //______________________________________________________________________________
2848 BookReader.prototype.printPage = function() {
2849     window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2850 }
2851
2852 // Get print URI from current indices and mode
2853 BookReader.prototype.getPrintURI = function() {
2854     var indexToPrint;
2855     if (this.constMode2up == this.mode) {
2856         indexToPrint = this.twoPage.currentIndexL;        
2857     } else {
2858         indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2859     }
2860     
2861     var options = 'id=' + this.subPrefix + '&server=' + this.server + '&zip=' + this.zip
2862         + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2863         + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2864    
2865     if (this.constMode2up == this.mode) {
2866         options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2867         options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2868         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2869     } else {
2870         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2871     }
2872
2873     return '/bookreader/print.php?' + options;
2874 }
2875
2876 /* iframe implementation
2877 BookReader.prototype.getPrintFrameContent = function(index) {    
2878     // We fit the image based on an assumed A4 aspect ratio.  A4 is a bit taller aspect than
2879     // 8.5x11 so we should end up not overflowing on either paper size.
2880     var paperAspect = 8.5 / 11;
2881     var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2882     
2883     var rotate = 0;
2884     
2885     // Rotate if possible and appropriate, to get larger image size on printed page
2886     if (this.canRotatePage(index)) {
2887         if (imageAspect > 1 && imageAspect > paperAspect) {
2888             // more wide than square, and more wide than paper
2889             rotate = 90;
2890             imageAspect = 1/imageAspect;
2891         }
2892     }
2893     
2894     var fitAttrs;
2895     if (imageAspect > paperAspect) {
2896         // wider than paper, fit width
2897         fitAttrs = 'width="95%"';
2898     } else {
2899         // taller than paper, fit height
2900         fitAttrs = 'height="95%"';
2901     }
2902
2903     var imageURL = this._getPageURI(index, 1, rotate);
2904     var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2905     iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2906     iframeStr +=   '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2907     iframeStr += '</div>';
2908     iframeStr += '</body></html>';
2909     
2910     return iframeStr;
2911 }
2912
2913 BookReader.prototype.updatePrintFrame = function(delta) {
2914     var newIndex = this.indexToPrint + delta;
2915     newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2916     if (newIndex == this.indexToPrint) {
2917         return;
2918     }
2919     this.indexToPrint = newIndex;
2920     var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2921     $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2922 }
2923 */
2924
2925 // showEmbedCode()
2926 //______________________________________________________________________________
2927 BookReader.prototype.showEmbedCode = function() {
2928     if (null != this.embedPopup) { // check if already showing
2929         return;
2930     }
2931     this.autoStop();
2932     this.embedPopup = document.createElement("div");
2933     $(this.embedPopup).css({
2934         position: 'absolute',
2935         top:      '20px',
2936         left:     ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2937         width:    '400px',
2938         padding:  "20px",
2939         border:   "3px double #999999",
2940         zIndex:   3,
2941         backgroundColor: "#fff"
2942     }).appendTo('#BookReader');
2943
2944     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2945     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>';
2946     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2947     htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2948
2949     this.embedPopup.innerHTML = htmlStr;
2950     $(this.embedPopup).find('input').bind('click', function() {
2951         this.select();
2952     })
2953 }
2954
2955 // autoToggle()
2956 //______________________________________________________________________________
2957 BookReader.prototype.autoToggle = function() {
2958
2959     var bComingFrom1up = false;
2960     if (2 != this.mode) {
2961         bComingFrom1up = true;
2962         this.switchMode(2);
2963     }
2964     
2965     // Change to autofit if book is too large
2966     if (this.reduce < this.twoPageGetAutofitReduce()) {
2967         this.zoom2up('auto');
2968     }
2969
2970     var self = this;
2971     if (null == this.autoTimer) {
2972         this.flipSpeed = 2000;
2973         
2974         // $$$ Draw events currently cause layout problems when they occur during animation.
2975         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2976         //     we workaround for now by not triggering immediate animation in that case.
2977         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2978         if (('rl' == this.pageProgression) && bComingFrom1up) {
2979             // don't flip immediately -- wait until timer fires
2980         } else {
2981             // flip immediately
2982             this.flipFwdToIndex();        
2983         }
2984
2985         $('#BRtoolbar .play').hide();
2986         $('#BRtoolbar .pause').show();
2987         this.autoTimer=setInterval(function(){
2988             if (self.animating) {return;}
2989             
2990             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2991                 self.flipBackToIndex(1); // $$$ really what we want?
2992             } else {            
2993                 self.flipFwdToIndex();
2994             }
2995         },5000);
2996     } else {
2997         this.autoStop();
2998     }
2999 }
3000
3001 // autoStop()
3002 //______________________________________________________________________________
3003 // Stop autoplay mode, allowing animations to finish
3004 BookReader.prototype.autoStop = function() {
3005     if (null != this.autoTimer) {
3006         clearInterval(this.autoTimer);
3007         this.flipSpeed = 'fast';
3008         $('#BRtoolbar .pause').hide();
3009         $('#BRtoolbar .play').show();
3010         this.autoTimer = null;
3011     }
3012 }
3013
3014 // stopFlipAnimations
3015 //______________________________________________________________________________
3016 // Immediately stop flip animations.  Callbacks are triggered.
3017 BookReader.prototype.stopFlipAnimations = function() {
3018
3019     this.autoStop(); // Clear timers
3020
3021     // Stop animation, clear queue, trigger callbacks
3022     if (this.leafEdgeTmp) {
3023         $(this.leafEdgeTmp).stop(false, true);
3024     }
3025     jQuery.each(this.prefetchedImgs, function() {
3026         $(this).stop(false, true);
3027         });
3028
3029     // And again since animations also queued in callbacks
3030     if (this.leafEdgeTmp) {
3031         $(this.leafEdgeTmp).stop(false, true);
3032     }
3033     jQuery.each(this.prefetchedImgs, function() {
3034         $(this).stop(false, true);
3035         });
3036    
3037 }
3038
3039 // keyboardNavigationIsDisabled(event)
3040 //   - returns true if keyboard navigation should be disabled for the event
3041 //______________________________________________________________________________
3042 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3043     if (event.target.tagName == "INPUT") {
3044         return true;
3045     }   
3046     return false;
3047 }
3048
3049 // gutterOffsetForIndex
3050 //______________________________________________________________________________
3051 //
3052 // Returns the gutter offset for the spread containing the given index.
3053 // This function supports RTL
3054 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3055
3056     // To find the offset of the gutter from the middle we calculate our percentage distance
3057     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3058     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3059     
3060     // But then again for RTL it's the opposite
3061     if ('rl' == this.pageProgression) {
3062         offset = -offset;
3063     }
3064     
3065     return offset;
3066 }
3067
3068 // leafEdgeWidth
3069 //______________________________________________________________________________
3070 // Returns the width of the leaf edge div for the page with index given
3071 BookReader.prototype.leafEdgeWidth = function(pindex) {
3072     // $$$ could there be single pixel rounding errors for L vs R?
3073     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3074         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3075     } else {
3076         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3077     }
3078 }
3079
3080 // jumpIndexForLeftEdgePageX
3081 //______________________________________________________________________________
3082 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3083 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3084     if ('rl' != this.pageProgression) {
3085         // LTR - flipping backward
3086         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3087
3088         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
3089         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3090         return jumpIndex;
3091
3092     } else {
3093         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3094         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3095         return jumpIndex;
3096     }
3097 }
3098
3099 // jumpIndexForRightEdgePageX
3100 //______________________________________________________________________________
3101 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3102 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3103     if ('rl' != this.pageProgression) {
3104         // LTR
3105         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3106         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3107         return jumpIndex;
3108     } else {
3109         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3110         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3111         return jumpIndex;
3112     }
3113 }
3114
3115 BookReader.prototype.initToolbar = function(mode, ui) {
3116
3117     $("#BookReader").append("<div id='BRtoolbar'>"
3118         + "<span id='BRtoolbarbuttons' style='float: right'>"
3119         +   "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3120         +   "<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>"
3121         +   "<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>"
3122         +   "<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>"
3123         +   "<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>"
3124         +   "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3125         + "</span>"
3126         
3127         + "<span>"
3128         +   "<a class='BRicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
3129         +   " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>" 
3130         +   "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3131         +   " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3132         +   " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3133         +   " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3134         +   " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3135         + "</span>"
3136         
3137         + "<span id='#BRbooktitle'>"
3138         +   "&nbsp;&nbsp;<a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3139         + "</span>"
3140         + "</div>");
3141     
3142     this.updateToolbarZoom(this.reduce); // Pretty format
3143         
3144     if (ui == "embed" || ui == "touch") {
3145         $("#BookReader a.logo").attr("target","_blank");
3146     }
3147
3148     // $$$ turn this into a member variable
3149     var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3150     
3151     // We build in mode 2
3152     jToolbar.append();
3153
3154     this.bindToolbarNavHandlers(jToolbar);
3155     
3156     // Setup tooltips -- later we could load these from a file for i18n
3157     var titles = { '.logo': 'Go to Archive.org',
3158                    '.zoom_in': 'Zoom in',
3159                    '.zoom_out': 'Zoom out',
3160                    '.one_page_mode': 'One-page view',
3161                    '.two_page_mode': 'Two-page view',
3162                    '.thumbnail_mode': 'Thumbnail view',
3163                    '.print': 'Print this page',
3164                    '.embed': 'Embed bookreader',
3165                    '.book_left': 'Flip left',
3166                    '.book_right': 'Flip right',
3167                    '.book_up': 'Page up',
3168                    '.book_down': 'Page down',
3169                    '.play': 'Play',
3170                    '.pause': 'Pause',
3171                    '.book_top': 'First page',
3172                    '.book_bottom': 'Last page'
3173                   };
3174     if ('rl' == this.pageProgression) {
3175         titles['.book_leftmost'] = 'Last page';
3176         titles['.book_rightmost'] = 'First page';
3177     } else { // LTR
3178         titles['.book_leftmost'] = 'First page';
3179         titles['.book_rightmost'] = 'Last page';
3180     }
3181                   
3182     for (var icon in titles) {
3183         jToolbar.find(icon).attr('title', titles[icon]);
3184     }
3185     
3186     // Hide mode buttons and autoplay if 2up is not available
3187     // $$$ if we end up with more than two modes we should show the applicable buttons
3188     if ( !this.canSwitchToMode(this.constMode2up) ) {
3189         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3190     }
3191
3192     // Switch to requested mode -- binds other click handlers
3193     this.switchToolbarMode(mode);
3194     
3195 }
3196
3197
3198 // switchToolbarMode
3199 //______________________________________________________________________________
3200 // Update the toolbar for the given mode (changes navigation buttons)
3201 // $$$ we should soon split the toolbar out into its own module
3202 BookReader.prototype.switchToolbarMode = function(mode) { 
3203     if (1 == mode) {
3204         // 1-up
3205         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3206         $('#BRtoolbar .BRtoolbarmode2').hide();
3207         $('#BRtoolbar .BRtoolbarmode3').hide();
3208         $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3209     } else if (2 == mode) {
3210         // 2-up
3211         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3212         $('#BRtoolbar .BRtoolbarmode1').hide();
3213         $('#BRtoolbar .BRtoolbarmode3').hide();
3214         $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3215     } else {
3216         // 3-up    
3217         $('#BRtoolbar .BRtoolbarzoom').hide();
3218         $('#BRtoolbar .BRtoolbarmode2').hide();
3219         $('#BRtoolbar .BRtoolbarmode1').hide();
3220         $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3221     }
3222 }
3223
3224 // bindToolbarNavHandlers
3225 //______________________________________________________________________________
3226 // Binds the toolbar handlers
3227 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3228
3229     var self = this; // closure
3230
3231     jToolbar.find('.book_left').bind('click', function(e) {
3232         self.left();
3233         return false;
3234     });
3235          
3236     jToolbar.find('.book_right').bind('click', function(e) {
3237         self.right();
3238         return false;
3239     });
3240         
3241     jToolbar.find('.book_up').bind('click', function(e) {
3242         if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3243             self.scrollUp();
3244         } else {
3245             self.prev();
3246         }
3247         return false;
3248     });        
3249         
3250     jToolbar.find('.book_down').bind('click', function(e) {
3251         if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3252             self.scrollDown();
3253         } else {
3254             self.next();
3255         }
3256         return false;
3257     });
3258
3259     jToolbar.find('.print').bind('click', function(e) {
3260         self.printPage();
3261         return false;
3262     });
3263         
3264     jToolbar.find('.embed').bind('click', function(e) {
3265         self.showEmbedCode();
3266         return false;
3267     });
3268
3269     jToolbar.find('.play').bind('click', function(e) {
3270         self.autoToggle();
3271         return false;
3272     });
3273
3274     jToolbar.find('.pause').bind('click', function(e) {
3275         self.autoToggle();
3276         return false;
3277     });
3278     
3279     jToolbar.find('.book_top').bind('click', function(e) {
3280         self.first();
3281         return false;
3282     });
3283
3284     jToolbar.find('.book_bottom').bind('click', function(e) {
3285         self.last();
3286         return false;
3287     });
3288     
3289     jToolbar.find('.book_leftmost').bind('click', function(e) {
3290         self.leftmost();
3291         return false;
3292     });
3293   
3294     jToolbar.find('.book_rightmost').bind('click', function(e) {
3295         self.rightmost();
3296         return false;
3297     });
3298 }
3299
3300 // updateToolbarZoom(reduce)
3301 //______________________________________________________________________________
3302 // Update the displayed zoom factor based on reduction factor
3303 BookReader.prototype.updateToolbarZoom = function(reduce) {
3304     var value;
3305     var autofit = null;
3306
3307     // $$$ TODO preserve zoom/fit for each mode
3308     if (this.mode == this.constMode2up) {
3309         autofit = this.twoPage.autofit;
3310     } else {
3311         autofit = this.onePage.autofit;
3312     }
3313     
3314     if (autofit) {
3315         value = autofit.slice(0,1).toUpperCase() + autofit.slice(1);
3316     } else {
3317         value = (100 / reduce).toFixed(2);
3318         // Strip trailing zeroes and decimal if all zeroes
3319         value = value.replace(/0+$/,'');
3320         value = value.replace(/\.$/,'');
3321         value += '%';
3322     }
3323     $('#BRzoom').text(value);
3324 }
3325
3326 // firstDisplayableIndex
3327 //______________________________________________________________________________
3328 // Returns the index of the first visible page, dependent on the mode.
3329 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3330 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3331 BookReader.prototype.firstDisplayableIndex = function() {
3332     if (this.mode != this.constMode2up) {
3333         return 0;
3334     }
3335     
3336     if ('rl' != this.pageProgression) {
3337         // LTR
3338         if (this.getPageSide(0) == 'L') {
3339             return 0;
3340         } else {
3341             return -1;
3342         }
3343     } else {
3344         // RTL
3345         if (this.getPageSide(0) == 'R') {
3346             return 0;
3347         } else {
3348             return -1;
3349         }
3350     }
3351 }
3352
3353 // lastDisplayableIndex
3354 //______________________________________________________________________________
3355 // Returns the index of the last visible page, dependent on the mode.
3356 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3357 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
3358 BookReader.prototype.lastDisplayableIndex = function() {
3359
3360     var lastIndex = this.numLeafs - 1;
3361     
3362     if (this.mode != this.constMode2up) {
3363         return lastIndex;
3364     }
3365
3366     if ('rl' != this.pageProgression) {
3367         // LTR
3368         if (this.getPageSide(lastIndex) == 'R') {
3369             return lastIndex;
3370         } else {
3371             return lastIndex + 1;
3372         }
3373     } else {
3374         // RTL
3375         if (this.getPageSide(lastIndex) == 'L') {
3376             return lastIndex;
3377         } else {
3378             return lastIndex + 1;
3379         }
3380     }
3381 }
3382
3383 // shortTitle(maximumCharacters)
3384 //________
3385 // Returns a shortened version of the title with the maximum number of characters
3386 BookReader.prototype.shortTitle = function(maximumCharacters) {
3387     if (this.bookTitle.length < maximumCharacters) {
3388         return this.bookTitle;
3389     }
3390     
3391     var title = this.bookTitle.substr(0, maximumCharacters - 3);
3392     title += '...';
3393     return title;
3394 }
3395
3396 // Parameter related functions
3397
3398 // updateFromParams(params)
3399 //________
3400 // Update ourselves from the params object.
3401 //
3402 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3403 BookReader.prototype.updateFromParams = function(params) {
3404     if ('undefined' != typeof(params.mode)) {
3405         this.switchMode(params.mode);
3406     }
3407
3408     // process /search
3409     if ('undefined' != typeof(params.searchTerm)) {
3410         if (this.searchTerm != params.searchTerm) {
3411             this.search(params.searchTerm);
3412         }
3413     }
3414     
3415     // $$$ process /zoom
3416     
3417     // We only respect page if index is not set
3418     if ('undefined' != typeof(params.index)) {
3419         if (params.index != this.currentIndex()) {
3420             this.jumpToIndex(params.index);
3421         }
3422     } else if ('undefined' != typeof(params.page)) {
3423         // $$$ this assumes page numbers are unique
3424         if (params.page != this.getPageNum(this.currentIndex())) {
3425             this.jumpToPage(params.page);
3426         }
3427     }
3428     
3429     // $$$ process /region
3430     // $$$ process /highlight
3431 }
3432
3433 // paramsFromFragment(urlFragment)
3434 //________
3435 // Returns a object with configuration parametes from a URL fragment.
3436 //
3437 // E.g paramsFromFragment(window.location.hash)
3438 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3439     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3440
3441     var params = {};
3442     
3443     // For convenience we allow an initial # character (as from window.location.hash)
3444     // but don't require it
3445     if (urlFragment.substr(0,1) == '#') {
3446         urlFragment = urlFragment.substr(1);
3447     }
3448     
3449     // Simple #nn syntax
3450     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3451     if ( !isNaN(oldStyleLeafNum) ) {
3452         params.index = oldStyleLeafNum;
3453         
3454         // Done processing if using old-style syntax
3455         return params;
3456     }
3457     
3458     // Split into key-value pairs
3459     var urlArray = urlFragment.split('/');
3460     var urlHash = {};
3461     for (var i = 0; i < urlArray.length; i += 2) {
3462         urlHash[urlArray[i]] = urlArray[i+1];
3463     }
3464     
3465     // Mode
3466     if ('1up' == urlHash['mode']) {
3467         params.mode = this.constMode1up;
3468     } else if ('2up' == urlHash['mode']) {
3469         params.mode = this.constMode2up;
3470     } else if ('thumb' == urlHash['mode']) {
3471         params.mode = this.constModeThumb;
3472     }
3473     
3474     // Index and page
3475     if ('undefined' != typeof(urlHash['page'])) {
3476         // page was set -- may not be int
3477         params.page = urlHash['page'];
3478     }
3479     
3480     // $$$ process /region
3481     // $$$ process /search
3482     
3483     if (urlHash['search'] != undefined) {
3484         params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3485     }
3486     
3487     // $$$ process /highlight
3488         
3489     return params;
3490 }
3491
3492 // paramsFromCurrent()
3493 //________
3494 // Create a params object from the current parameters.
3495 BookReader.prototype.paramsFromCurrent = function() {
3496
3497     var params = {};
3498     
3499     var index = this.currentIndex();
3500     var pageNum = this.getPageNum(index);
3501     if ((pageNum === 0) || pageNum) {
3502         params.page = pageNum;
3503     }
3504     
3505     params.index = index;
3506     params.mode = this.mode;
3507     
3508     // $$$ highlight
3509     // $$$ region
3510
3511     // search    
3512     if (this.searchHighlightVisible()) {
3513         params.searchTerm = this.searchTerm;
3514     }
3515     
3516     return params;
3517 }
3518
3519 // fragmentFromParams(params)
3520 //________
3521 // Create a fragment string from the params object.
3522 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3523 BookReader.prototype.fragmentFromParams = function(params) {
3524     var separator = '/';
3525
3526     var fragments = [];
3527     
3528     if ('undefined' != typeof(params.page)) {
3529         fragments.push('page', params.page);
3530     } else {
3531         // Don't have page numbering -- use index instead
3532         fragments.push('page', 'n' + params.index);
3533     }
3534     
3535     // $$$ highlight
3536     // $$$ region
3537     
3538     // mode
3539     if ('undefined' != typeof(params.mode)) {    
3540         if (params.mode == this.constMode1up) {
3541             fragments.push('mode', '1up');
3542         } else if (params.mode == this.constMode2up) {
3543             fragments.push('mode', '2up');
3544         } else if (params.mode == this.constModeThumb) {
3545             fragments.push('mode', 'thumb');
3546         } else {
3547             throw 'fragmentFromParams called with unknown mode ' + params.mode;
3548         }
3549     }
3550     
3551     // search
3552     if (params.searchTerm) {
3553         fragments.push('search', params.searchTerm);
3554     }
3555     
3556     return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3557 }
3558
3559 // getPageIndex(pageNum)
3560 //________
3561 // Returns the *highest* index the given page number, or undefined
3562 BookReader.prototype.getPageIndex = function(pageNum) {
3563     var pageIndices = this.getPageIndices(pageNum);
3564     
3565     if (pageIndices.length > 0) {
3566         return pageIndices[pageIndices.length - 1];
3567     }
3568
3569     return undefined;
3570 }
3571
3572 // getPageIndices(pageNum)
3573 //________
3574 // Returns an array (possibly empty) of the indices with the given page number
3575 BookReader.prototype.getPageIndices = function(pageNum) {
3576     var indices = [];
3577
3578     // Check for special "nXX" page number
3579     if (pageNum.slice(0,1) == 'n') {
3580         try {
3581             var pageIntStr = pageNum.slice(1, pageNum.length);
3582             var pageIndex = parseInt(pageIntStr);
3583             indices.push(pageIndex);
3584             return indices;
3585         } catch(err) {
3586             // Do nothing... will run through page names and see if one matches
3587         }
3588     }
3589
3590     var i;
3591     for (i=0; i<this.numLeafs; i++) {
3592         if (this.getPageNum(i) == pageNum) {
3593             indices.push(i);
3594         }
3595     }
3596     
3597     return indices;
3598 }
3599
3600 // getPageName(index)
3601 //________
3602 // Returns the name of the page as it should be displayed in the user interface
3603 BookReader.prototype.getPageName = function(index) {
3604     return 'Page ' + this.getPageNum(index);
3605 }
3606
3607 // updateLocationHash
3608 //________
3609 // Update the location hash from the current parameters.  Call this instead of manually
3610 // using window.location.replace
3611 BookReader.prototype.updateLocationHash = function() {
3612     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3613     window.location.replace(newHash);
3614     
3615     // This is the variable checked in the timer.  Only user-generated changes
3616     // to the URL will trigger the event.
3617     this.oldLocationHash = newHash;
3618 }
3619
3620 // startLocationPolling
3621 //________
3622 // Starts polling of window.location to see hash fragment changes
3623 BookReader.prototype.startLocationPolling = function() {
3624     var self = this; // remember who I am
3625     self.oldLocationHash = window.location.hash;
3626     
3627     if (this.locationPollId) {
3628         clearInterval(this.locationPollID);
3629         this.locationPollId = null;
3630     }
3631     
3632     this.locationPollId = setInterval(function() {
3633         var newHash = window.location.hash;
3634         if (newHash != self.oldLocationHash) {
3635             if (newHash != self.oldUserHash) { // Only process new user hash once
3636                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3637                 
3638                 // Queue change if animating
3639                 if (self.animating) {
3640                     self.autoStop();
3641                     self.animationFinishedCallback = function() {
3642                         self.updateFromParams(self.paramsFromFragment(newHash));
3643                     }                        
3644                 } else { // update immediately
3645                     self.updateFromParams(self.paramsFromFragment(newHash));
3646                 }
3647                 self.oldUserHash = newHash;
3648             }
3649         }
3650     }, 500);
3651 }
3652
3653 // canSwitchToMode
3654 //________
3655 // Returns true if we can switch to the requested mode
3656 BookReader.prototype.canSwitchToMode = function(mode) {
3657     if (mode == this.constMode2up) {
3658         // check there are enough pages to display
3659         // $$$ this is a workaround for the mis-feature that we can't display
3660         //     short books in 2up mode
3661         if (this.numLeafs < 6) {
3662             return false;
3663         }
3664     }
3665     
3666     return true;
3667 }
3668
3669 // searchHighlightVisible
3670 //________
3671 // Returns true if a search highlight is currently being displayed
3672 BookReader.prototype.searchHighlightVisible = function() {
3673     if (this.constMode2up == this.mode) {
3674         if (this.searchResults[this.twoPage.currentIndexL]
3675                 || this.searchResults[this.twoPage.currentIndexR]) {
3676             return true;
3677         }
3678     } else { // 1up
3679         if (this.searchResults[this.currentIndex()]) {
3680             return true;
3681         }
3682     }
3683     return false;
3684 }
3685
3686 // _getPageWidth
3687 //--------
3688 // Returns the page width for the given index, or first or last page if out of range
3689 BookReader.prototype._getPageWidth = function(index) {
3690     // Synthesize a page width for pages not actually present in book.
3691     // May or may not be the best approach.
3692     // If index is out of range we return the width of first or last page
3693     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3694     return this.getPageWidth(index);
3695 }
3696
3697 // _getPageHeight
3698 //--------
3699 // Returns the page height for the given index, or first or last page if out of range
3700 BookReader.prototype._getPageHeight= function(index) {
3701     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3702     return this.getPageHeight(index);
3703 }
3704
3705 // _getPageURI
3706 //--------
3707 // Returns the page URI or transparent image if out of range
3708 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3709     if (index < 0 || index >= this.numLeafs) { // Synthesize page
3710         return this.imagesBaseURL + "/transparent.png";
3711     }
3712     
3713     if ('undefined' == typeof(reduce)) {
3714         // reduce not passed in
3715         // $$$ this probably won't work for thumbnail mode
3716         var ratio = this.getPageHeight(index) / this.twoPage.height;
3717         var scale;
3718         // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3719         if (ratio < 2) {
3720             scale = 1;
3721         } else if (ratio < 4) {
3722             scale = 2;
3723         } else if (ratio < 8) {
3724             scale = 4;
3725         } else if (ratio < 16) {
3726             scale = 8;
3727         } else  if (ratio < 32) {
3728             scale = 16;
3729         } else {
3730             scale = 32;
3731         }
3732         reduce = scale;
3733     }
3734     
3735     return this.getPageURI(index, reduce, rotate);
3736 }
3737
3738 // Library functions
3739 BookReader.util = {
3740     disableSelect: function(jObject) {        
3741         // Bind mouse handlers
3742         // Disable mouse click to avoid selected/highlighted page images - bug 354239
3743         jObject.bind('mousedown', function(e) {
3744             // $$$ check here for right-click and don't disable.  Also use jQuery style
3745             //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3746             return false;
3747         });
3748         // Special hack for IE7
3749         jObject[0].onselectstart = function(e) { return false; };
3750     },
3751     
3752     clamp: function(value, min, max) {
3753         return Math.min(Math.max(value, min), max);
3754     },
3755     
3756     notInArray: function(value, array) {
3757         // inArray returns -1 or undefined if value not in array
3758         return ! (jQuery.inArray(value, array) >= 0);
3759     },
3760
3761     getIFrameDocument: function(iframe) {
3762         // Adapted from http://xkr.us/articles/dom/iframe-document/
3763         var outer = (iframe.contentWindow || iframe.contentDocument);
3764         return (outer.document || outer);
3765     },
3766     
3767     decodeURIComponentPlus: function(value) {
3768         // Decodes a URI component and converts '+' to ' '
3769         return decodeURIComponent(value).replace(/\+/g, ' ');
3770     },
3771     
3772     encodeURIComponentPlus: function(value) {
3773         // Encodes a URI component and converts ' ' to '+'
3774         return encodeURIComponent(value).replace(/%20/g, '+');
3775     }
3776     // The final property here must NOT have a comma after it - IE7
3777 }