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