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