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