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