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