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