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