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