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