Request thumbnail at next larger integer reduction
[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 // flipBackToIndex()
1793 //______________________________________________________________________________
1794 // to flip back one spread, pass index=null
1795 BookReader.prototype.flipBackToIndex = function(index) {
1796     
1797     if (1 == this.mode) return;
1798
1799     var leftIndex = this.twoPage.currentIndexL;
1800     
1801     if (this.animating) return;
1802
1803     if (null != this.leafEdgeTmp) {
1804         alert('error: leafEdgeTmp should be null!');
1805         return;
1806     }
1807     
1808     if (null == index) {
1809         index = leftIndex-2;
1810     }
1811     //if (index<0) return;
1812     
1813     var previousIndices = this.getSpreadIndices(index);
1814     
1815     if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1816         return;
1817     }
1818     
1819     this.animating = true;
1820     
1821     if ('rl' != this.pageProgression) {
1822         // Assume LTR and we are going backward    
1823         this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);        
1824         this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1825     } else {
1826         // RTL and going backward
1827         var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1828         this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1829     }
1830 }
1831
1832 // flipLeftToRight()
1833 //______________________________________________________________________________
1834 // Flips the page on the left towards the page on the right
1835 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1836
1837     var leftLeaf = this.twoPage.currentIndexL;
1838     
1839     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1840     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);    
1841     var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1842     
1843     var currWidthL   = this.getPageWidth2UP(leftLeaf);
1844     var newWidthL    = this.getPageWidth2UP(newIndexL);
1845     var newWidthR    = this.getPageWidth2UP(newIndexR);
1846
1847     var top  = this.twoPageTop();
1848     var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1849     
1850     //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1851     //console.log('  gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1852     
1853     //animation strategy:
1854     // 0. remove search highlight, if any.
1855     // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge 
1856     //    of the left leaf and where the user clicked in the leaf edge.
1857     //    Note that if this function was triggered by left() and not a
1858     //    mouse click, the width of leafEdgeTmp is very small (zero px).
1859     // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1860     //    leftLeaf to width=0.
1861     // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1862     //    (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1863     //    its new full width.
1864     // 4. After step 3 is finished, do the following:
1865     //      - remove leafEdgeTmp from the dom.
1866     //      - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1867     //          and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1868     //      - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1869     //          and width=newLeafEdgeWidthL.
1870     //      - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1871     //          and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1872     //      - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1873     //      - remove old left and right leafs from the dom [pruneUnusedImgs()].
1874     //      - prefetch new adjacent leafs.
1875     //      - set up click handlers for both new left and right leafs.
1876     //      - redraw the search highlight.
1877     //      - update the pagenum box and the url.
1878     
1879     
1880     var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1881
1882     this.leafEdgeTmp = document.createElement('div');
1883     $(this.leafEdgeTmp).css({
1884         borderStyle: 'solid none solid solid',
1885         borderColor: 'rgb(51, 51, 34)',
1886         borderWidth: '1px 0px 1px 1px',
1887         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1888         width: leafEdgeTmpW + 'px',
1889         height: this.twoPage.height-1 + 'px',
1890         left: leftEdgeTmpLeft + 'px',
1891         top: top+'px',    
1892         position: 'absolute',
1893         zIndex:1000
1894     }).appendTo('#BRtwopageview');
1895     
1896     //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1897     $(this.leafEdgeL).css({
1898         width: newLeafEdgeWidthL+'px', 
1899         left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1900     });   
1901
1902     // Left gets the offset of the current left leaf from the document
1903     var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1904     // $$$ This seems very similar to the gutter.  May be able to consolidate the logic.
1905     var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1906     
1907     // We change the left leaf to right positioning
1908     // $$$ This causes animation glitches during resize.  See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1909     $(this.prefetchedImgs[leftLeaf]).css({
1910         right: right,
1911         left: ''
1912     });
1913
1914     $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');    
1915     //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1916     
1917     var self = this;
1918
1919     this.removeSearchHilites();
1920
1921     //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1922     $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1923     
1924         //console.log('     and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1925         $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1926
1927         //console.log('  animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1928         $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1929             $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1930             
1931             $(self.leafEdgeR).css({
1932                 // Moves the right leaf edge
1933                 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1934                 left:  gutter+newWidthR+'px'
1935             });
1936
1937             $(self.leafEdgeL).css({
1938                 // Moves and resizes the left leaf edge
1939                 width: newLeafEdgeWidthL+'px',
1940                 left:  gutter-newWidthL-newLeafEdgeWidthL+'px'
1941             });
1942
1943             // Resizes the brown border div
1944             $(self.twoPage.coverDiv).css({
1945                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1946                 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1947             });
1948             
1949             $(self.leafEdgeTmp).remove();
1950             self.leafEdgeTmp = null;
1951
1952             // $$$ TODO refactor with opposite direction flip
1953             
1954             self.twoPage.currentIndexL = newIndexL;
1955             self.twoPage.currentIndexR = newIndexR;
1956             self.twoPage.scaledWL = newWidthL;
1957             self.twoPage.scaledWR = newWidthR;
1958             self.twoPage.gutter = gutter;
1959             
1960             self.firstIndex = self.twoPage.currentIndexL;
1961             self.displayedIndices = [newIndexL, newIndexR];
1962             self.pruneUnusedImgs();
1963             self.prefetch();            
1964             self.animating = false;
1965             
1966             self.updateSearchHilites2UP();
1967             self.updatePageNumBox2UP();
1968             
1969             // self.twoPagePlaceFlipAreas(); // No longer used
1970             self.setMouseHandlers2UP();
1971             self.twoPageSetCursor();
1972             
1973             if (self.animationFinishedCallback) {
1974                 self.animationFinishedCallback();
1975                 self.animationFinishedCallback = null;
1976             }
1977         });
1978     });        
1979     
1980 }
1981
1982 // flipFwdToIndex()
1983 //______________________________________________________________________________
1984 // Whether we flip left or right is dependent on the page progression
1985 // to flip forward one spread, pass index=null
1986 BookReader.prototype.flipFwdToIndex = function(index) {
1987
1988     if (this.animating) return;
1989
1990     if (null != this.leafEdgeTmp) {
1991         alert('error: leafEdgeTmp should be null!');
1992         return;
1993     }
1994
1995     if (null == index) {
1996         index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1997     }
1998     if (index > this.lastDisplayableIndex()) return;
1999
2000     this.animating = true;
2001     
2002     var nextIndices = this.getSpreadIndices(index);
2003     
2004     //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2005
2006     if ('rl' != this.pageProgression) {
2007         // We did not specify RTL
2008         var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2009         this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2010     } else {
2011         // RTL
2012         var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2013         this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2014     }
2015 }
2016
2017 // flipRightToLeft(nextL, nextR, gutter)
2018 // $$$ better not to have to pass gutter in
2019 //______________________________________________________________________________
2020 // Flip from left to right and show the nextL and nextR indices on those sides
2021 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2022     var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2023     var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2024     var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);  
2025     var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2026
2027     var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2028
2029     var top = this.twoPageTop();
2030     var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2031
2032     var middle = this.twoPage.middle;
2033     var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2034     
2035     this.leafEdgeTmp = document.createElement('div');
2036     $(this.leafEdgeTmp).css({
2037         borderStyle: 'solid none solid solid',
2038         borderColor: 'rgb(51, 51, 34)',
2039         borderWidth: '1px 0px 1px 1px',
2040         background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2041         width: leafEdgeTmpW + 'px',
2042         height: this.twoPage.height-1 + 'px',
2043         left: gutter+scaledW+'px',
2044         top: top+'px',    
2045         position: 'absolute',
2046         zIndex:1000
2047     }).appendTo('#BRtwopageview');
2048
2049     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2050     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2051     
2052     var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2053     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2054     var newWidthL = this.getPageWidth2UP(newIndexL);
2055     var newWidthR = this.getPageWidth2UP(newIndexR);
2056     
2057     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2058
2059     var self = this; // closure-tastic!
2060
2061     var speed = this.flipSpeed;
2062
2063     this.removeSearchHilites();
2064     
2065     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
2066     $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2067         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
2068         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2069             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2070             
2071             $(self.leafEdgeL).css({
2072                 width: newLeafEdgeWidthL+'px', 
2073                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2074             });
2075             
2076             // Resizes the book cover
2077             $(self.twoPage.coverDiv).css({
2078                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2079                 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2080             });
2081             
2082             $(self.leafEdgeTmp).remove();
2083             self.leafEdgeTmp = null;
2084             
2085             self.twoPage.currentIndexL = newIndexL;
2086             self.twoPage.currentIndexR = newIndexR;
2087             self.twoPage.scaledWL = newWidthL;
2088             self.twoPage.scaledWR = newWidthR;
2089             self.twoPage.gutter = gutter;
2090
2091             self.firstIndex = self.twoPage.currentIndexL;
2092             self.displayedIndices = [newIndexL, newIndexR];
2093             self.pruneUnusedImgs();
2094             self.prefetch();
2095             self.animating = false;
2096
2097
2098             self.updateSearchHilites2UP();
2099             self.updatePageNumBox2UP();
2100             
2101             // self.twoPagePlaceFlipAreas(); // No longer used
2102             self.setMouseHandlers2UP();     
2103             self.twoPageSetCursor();
2104             
2105             if (self.animationFinishedCallback) {
2106                 self.animationFinishedCallback();
2107                 self.animationFinishedCallback = null;
2108             }
2109         });
2110     });    
2111 }
2112
2113 // setMouseHandlers2UP
2114 //______________________________________________________________________________
2115 BookReader.prototype.setMouseHandlers2UP = function() {
2116     /*
2117     $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2118         //self.prevPage();
2119         self.autoStop();
2120         self.left();
2121     });
2122     $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2123         //self.nextPage();'
2124         self.autoStop();
2125         self.right();        
2126     });
2127     */
2128     
2129     this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2130     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2131         { self: this },
2132         function(e) {
2133             e.data.self.left();
2134         }
2135     );
2136         
2137     this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2138     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2139         { self: this },
2140         function(e) {
2141             e.data.self.right();
2142         }
2143     );
2144 }
2145
2146 // prefetchImg()
2147 //______________________________________________________________________________
2148 BookReader.prototype.prefetchImg = function(index) {
2149     var pageURI = this._getPageURI(index);
2150
2151     // Load image if not loaded or URI has changed (e.g. due to scaling)
2152     var loadImage = false;
2153     if (undefined == this.prefetchedImgs[index]) {
2154         //console.log('no image for ' + index);
2155         loadImage = true;
2156     } else if (pageURI != this.prefetchedImgs[index].uri) {
2157         //console.log('uri changed for ' + index);
2158         loadImage = true;
2159     }
2160     
2161     if (loadImage) {
2162         //console.log('prefetching ' + index);
2163         var img = document.createElement("img");
2164         img.src = pageURI;
2165         img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2166         this.prefetchedImgs[index] = img;
2167     }
2168 }
2169
2170
2171 // prepareFlipLeftToRight()
2172 //
2173 //______________________________________________________________________________
2174 //
2175 // Prepare to flip the left page towards the right.  This corresponds to moving
2176 // backward when the page progression is left to right.
2177 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2178
2179     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
2180
2181     this.prefetchImg(prevL);
2182     this.prefetchImg(prevR);
2183     
2184     var height  = this._getPageHeight(prevL); 
2185     var width   = this._getPageWidth(prevL);    
2186     var middle = this.twoPage.middle;
2187     var top  = this.twoPageTop();                
2188     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2189
2190     // The gutter is the dividing line between the left and right pages.
2191     // It is offset from the middle to create the illusion of thickness to the pages
2192     var gutter = middle + this.gutterOffsetForIndex(prevL);
2193     
2194     //console.log('    gutter for ' + prevL + ' is ' + gutter);
2195     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
2196     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2197     
2198     leftCSS = {
2199         position: 'absolute',
2200         left: gutter-scaledW+'px',
2201         right: '', // clear right property
2202         top:    top+'px',
2203         height: this.twoPage.height,
2204         width:  scaledW+'px',
2205         backgroundColor: this.getPageBackgroundColor(prevL),
2206         borderRight: '1px solid black',
2207         zIndex: 1
2208     }
2209     
2210     $(this.prefetchedImgs[prevL]).css(leftCSS);
2211
2212     $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2213
2214     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2215
2216     rightCSS = {
2217         position: 'absolute',
2218         left:   gutter+'px',
2219         right: '',
2220         top:    top+'px',
2221         height: this.twoPage.height,
2222         width:  '0px',
2223         backgroundColor: this.getPageBackgroundColor(prevR),
2224         borderLeft: '1px solid black',
2225         zIndex: 2
2226     }
2227     
2228     $(this.prefetchedImgs[prevR]).css(rightCSS);
2229
2230     $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2231             
2232 }
2233
2234 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2235 // prepareFlipRightToLeft()
2236 //______________________________________________________________________________
2237 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2238
2239     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
2240
2241     // Prefetch images
2242     this.prefetchImg(nextL);
2243     this.prefetchImg(nextR);
2244
2245     var height  = this._getPageHeight(nextR); 
2246     var width   = this._getPageWidth(nextR);    
2247     var middle = this.twoPage.middle;
2248     var top  = this.twoPageTop();               
2249     var scaledW = this.twoPage.height*width/height;
2250
2251     var gutter = middle + this.gutterOffsetForIndex(nextL);
2252         
2253     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2254     $(this.prefetchedImgs[nextR]).css({
2255         position: 'absolute',
2256         left:   gutter+'px',
2257         top:    top+'px',
2258         backgroundColor: this.getPageBackgroundColor(nextR),
2259         height: this.twoPage.height,
2260         width:  scaledW+'px',
2261         borderLeft: '1px solid black',
2262         zIndex: 1
2263     });
2264
2265     $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2266
2267     height  = this._getPageHeight(nextL); 
2268     width   = this._getPageWidth(nextL);      
2269     scaledW = this.twoPage.height*width/height;
2270
2271     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2272     $(this.prefetchedImgs[nextL]).css({
2273         position: 'absolute',
2274         right:   $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2275         top:    top+'px',
2276         backgroundColor: this.getPageBackgroundColor(nextL),
2277         height: this.twoPage.height,
2278         width:  0+'px', // Start at 0 width, then grow to the left
2279         borderRight: '1px solid black',
2280         zIndex: 2
2281     });
2282
2283     $('#BRtwopageview').append(this.prefetchedImgs[nextL]);    
2284             
2285 }
2286
2287 // getNextLeafs() -- NOT RTL AWARE
2288 //______________________________________________________________________________
2289 // BookReader.prototype.getNextLeafs = function(o) {
2290 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2291 //     //For now, assume that leafs are contiguous.
2292 //     
2293 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2294 //     o.L = this.twoPage.currentIndexL+2;
2295 //     o.R = this.twoPage.currentIndexL+3;
2296 // }
2297
2298 // getprevLeafs() -- NOT RTL AWARE
2299 //______________________________________________________________________________
2300 // BookReader.prototype.getPrevLeafs = function(o) {
2301 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2302 //     //For now, assume that leafs are contiguous.
2303 //     
2304 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2305 //     o.L = this.twoPage.currentIndexL-2;
2306 //     o.R = this.twoPage.currentIndexL-1;
2307 // }
2308
2309 // pruneUnusedImgs()
2310 //______________________________________________________________________________
2311 BookReader.prototype.pruneUnusedImgs = function() {
2312     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2313     for (var key in this.prefetchedImgs) {
2314         //console.log('key is ' + key);
2315         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2316             //console.log('removing key '+ key);
2317             $(this.prefetchedImgs[key]).remove();
2318         }
2319         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2320             //console.log('deleting key '+ key);
2321             delete this.prefetchedImgs[key];
2322         }
2323     }
2324 }
2325
2326 // prefetch()
2327 //______________________________________________________________________________
2328 BookReader.prototype.prefetch = function() {
2329
2330     // prefetch visible pages first
2331     this.prefetchImg(this.twoPage.currentIndexL);
2332     this.prefetchImg(this.twoPage.currentIndexR);
2333     
2334     var adjacentPagesToLoad = 3;
2335     
2336     var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2337     var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2338         
2339     var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2340     var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2341     
2342     // Load images spreading out from current
2343     for (var i = 1; i <= adjacentPagesToLoad; i++) {
2344         var goingDown = lowCurrent - i;
2345         if (goingDown >= start) {
2346             this.prefetchImg(goingDown);
2347         }
2348         var goingUp = highCurrent + i;
2349         if (goingUp <= end) {
2350             this.prefetchImg(goingUp);
2351         }
2352     }
2353
2354     /*
2355     var lim = this.twoPage.currentIndexL-4;
2356     var i;
2357     lim = Math.max(lim, 0);
2358     for (i = lim; i < this.twoPage.currentIndexL; i++) {
2359         this.prefetchImg(i);
2360     }
2361     
2362     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2363         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2364         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2365             this.prefetchImg(i);
2366         }
2367     }
2368     */
2369 }
2370
2371 // getPageWidth2UP()
2372 //______________________________________________________________________________
2373 BookReader.prototype.getPageWidth2UP = function(index) {
2374     // We return the width based on the dominant height
2375     var height  = this._getPageHeight(index); 
2376     var width   = this._getPageWidth(index);    
2377     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2378 }    
2379
2380 // search()
2381 //______________________________________________________________________________
2382 BookReader.prototype.search = function(term) {
2383     term = term.replace(/\//g, ' '); // strip slashes
2384     this.searchTerm = term;
2385     $('#BookReaderSearchScript').remove();
2386     var script  = document.createElement("script");
2387     script.setAttribute('id', 'BookReaderSearchScript');
2388     script.setAttribute("type", "text/javascript");
2389     script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2390     document.getElementsByTagName('head')[0].appendChild(script);
2391     $('#BookReaderSearchBox').val(term);
2392     $('#BookReaderSearchResults').html('Searching...');
2393 }
2394
2395 // BRSearchCallback()
2396 //______________________________________________________________________________
2397 BookReader.prototype.BRSearchCallback = function(txt) {
2398     //alert(txt);
2399     if (jQuery.browser.msie) {
2400         var dom=new ActiveXObject("Microsoft.XMLDOM");
2401         dom.async="false";
2402         dom.loadXML(txt);    
2403     } else {
2404         var parser = new DOMParser();
2405         var dom = parser.parseFromString(txt, "text/xml");    
2406     }
2407     
2408     $('#BookReaderSearchResults').empty();    
2409     $('#BookReaderSearchResults').append('<ul>');
2410     
2411     for (var key in this.searchResults) {
2412         if (null != this.searchResults[key].div) {
2413             $(this.searchResults[key].div).remove();
2414         }
2415         delete this.searchResults[key];
2416     }
2417     
2418     var pages = dom.getElementsByTagName('PAGE');
2419     
2420     if (0 == pages.length) {
2421         // $$$ it would be nice to echo the (sanitized) search result here
2422         $('#BookReaderSearchResults').append('<li>No search results found</li>');
2423     } else {    
2424         for (var i = 0; i < pages.length; i++){
2425             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2426     
2427             
2428             var re = new RegExp (/_(\d{4})/);
2429             var reMatch = re.exec(pages[i].getAttribute('file'));
2430             var index = parseInt(reMatch[1], 10);
2431             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2432             
2433             var children = pages[i].childNodes;
2434             var context = '';
2435             for (var j=0; j<children.length; j++) {
2436                 //console.log(j + ' - ' + children[j].nodeName);
2437                 //console.log(children[j].firstChild.nodeValue);
2438                 if ('CONTEXT' == children[j].nodeName) {
2439                     context += children[j].firstChild.nodeValue;
2440                 } else if ('WORD' == children[j].nodeName) {
2441                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2442                     
2443                     var index = this.leafNumToIndex(index);
2444                     if (null != index) {
2445                         //coordinates are [left, bottom, right, top, [baseline]]
2446                         //we'll skip baseline for now...
2447                         var coords = children[j].getAttribute('coords').split(',',4);
2448                         if (4 == coords.length) {
2449                             this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2450                         }
2451                     }
2452                 }
2453             }
2454             var pageName = this.getPageName(index);
2455             var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2456             var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2457             //TODO: remove hardcoded instance name
2458             $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2459         }
2460     }
2461     $('#BookReaderSearchResults').append('</ul>');
2462
2463     // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2464     $('#BookReaderSearchBox').val(this.searchTerm);
2465
2466     this.updateSearchHilites();
2467 }
2468
2469 // updateSearchHilites()
2470 //______________________________________________________________________________
2471 BookReader.prototype.updateSearchHilites = function() {
2472     if (2 == this.mode) {
2473         this.updateSearchHilites2UP();
2474     } else {
2475         this.updateSearchHilites1UP();
2476     }
2477 }
2478
2479 // showSearchHilites1UP()
2480 //______________________________________________________________________________
2481 BookReader.prototype.updateSearchHilites1UP = function() {
2482
2483     for (var key in this.searchResults) {
2484         
2485         if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2486             var result = this.searchResults[key];
2487             if(null == result.div) {
2488                 result.div = document.createElement('div');
2489                 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2490                 //console.log('appending ' + key);
2491             }    
2492             $(result.div).css({
2493                 width:  (result.r-result.l)/this.reduce + 'px',
2494                 height: (result.b-result.t)/this.reduce + 'px',
2495                 left:   (result.l)/this.reduce + 'px',
2496                 top:    (result.t)/this.reduce +'px'
2497             });
2498
2499         } else {
2500             //console.log(key + ' not displayed');
2501             this.searchResults[key].div=null;
2502         }
2503     }
2504 }
2505
2506 // twoPageGutter()
2507 //______________________________________________________________________________
2508 // Returns the position of the gutter (line between the page images)
2509 BookReader.prototype.twoPageGutter = function() {
2510     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2511 }
2512
2513 // twoPageTop()
2514 //______________________________________________________________________________
2515 // Returns the offset for the top of the page images
2516 BookReader.prototype.twoPageTop = function() {
2517     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2518 }
2519
2520 // twoPageCoverWidth()
2521 //______________________________________________________________________________
2522 // Returns the width of the cover div given the total page width
2523 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2524     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2525 }
2526
2527 // twoPageGetViewCenter()
2528 //______________________________________________________________________________
2529 // Returns the percentage offset into twopageview div at the center of container div
2530 // { percentageX: float, percentageY: float }
2531 BookReader.prototype.twoPageGetViewCenter = function() {
2532     var center = {};
2533
2534     var containerOffset = $('#BRcontainer').offset();
2535     var viewOffset = $('#BRtwopageview').offset();
2536     center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2537     center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2538     
2539     return center;
2540 }
2541
2542 // twoPageCenterView(percentageX, percentageY)
2543 //______________________________________________________________________________
2544 // Centers the point given by percentage from left,top of twopageview
2545 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2546     if ('undefined' == typeof(percentageX)) {
2547         percentageX = 0.5;
2548     }
2549     if ('undefined' == typeof(percentageY)) {
2550         percentageY = 0.5;
2551     }
2552
2553     var viewWidth = $('#BRtwopageview').width();
2554     var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2555     var intoViewX = percentageX * viewWidth;
2556     
2557     var viewHeight = $('#BRtwopageview').height();
2558     var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2559     var intoViewY = percentageY * viewHeight;
2560     
2561     if (viewWidth < containerClientWidth) {
2562         // Can fit width without scrollbars - center by adjusting offset
2563         $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2564     } else {
2565         // Need to scroll to center
2566         $('#BRtwopageview').css('left', 0);
2567         $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2568     }
2569     
2570     if (viewHeight < containerClientHeight) {
2571         // Fits with scrollbars - add offset
2572         $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2573     } else {
2574         $('#BRtwopageview').css('top', 0);
2575         $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2576     }
2577 }
2578
2579 // twoPageFlipAreaHeight
2580 //______________________________________________________________________________
2581 // Returns the integer height of the click-to-flip areas at the edges of the book
2582 BookReader.prototype.twoPageFlipAreaHeight = function() {
2583     return parseInt(this.twoPage.height);
2584 }
2585
2586 // twoPageFlipAreaWidth
2587 //______________________________________________________________________________
2588 // Returns the integer width of the flip areas 
2589 BookReader.prototype.twoPageFlipAreaWidth = function() {
2590     var max = 100; // $$$ TODO base on view width?
2591     var min = 10;
2592     
2593     var width = this.twoPage.width * 0.15;
2594     return parseInt(BookReader.util.clamp(width, min, max));
2595 }
2596
2597 // twoPageFlipAreaTop
2598 //______________________________________________________________________________
2599 // Returns integer top offset for flip areas
2600 BookReader.prototype.twoPageFlipAreaTop = function() {
2601     return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2602 }
2603
2604 // twoPageLeftFlipAreaLeft
2605 //______________________________________________________________________________
2606 // Left offset for left flip area
2607 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2608     return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2609 }
2610
2611 // twoPageRightFlipAreaLeft
2612 //______________________________________________________________________________
2613 // Left offset for right flip area
2614 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2615     return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2616 }
2617
2618 // twoPagePlaceFlipAreas
2619 //______________________________________________________________________________
2620 // Readjusts position of flip areas based on current layout
2621 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2622     // We don't set top since it shouldn't change relative to view
2623     $(this.twoPage.leftFlipArea).css({
2624         left: this.twoPageLeftFlipAreaLeft() + 'px',
2625         width: this.twoPageFlipAreaWidth() + 'px'
2626     });
2627     $(this.twoPage.rightFlipArea).css({
2628         left: this.twoPageRightFlipAreaLeft() + 'px',
2629         width: this.twoPageFlipAreaWidth() + 'px'
2630     });
2631 }
2632     
2633 // showSearchHilites2UP()
2634 //______________________________________________________________________________
2635 BookReader.prototype.updateSearchHilites2UP = function() {
2636
2637     for (var key in this.searchResults) {
2638         key = parseInt(key, 10);
2639         if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2640             var result = this.searchResults[key];
2641             if(null == result.div) {
2642                 result.div = document.createElement('div');
2643                 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2644                 //console.log('appending ' + key);
2645             }
2646
2647             // We calculate the reduction factor for the specific page because it can be different
2648             // for each page in the spread
2649             var height = this._getPageHeight(key);
2650             var width  = this._getPageWidth(key)
2651             var reduce = this.twoPage.height/height;
2652             var scaledW = parseInt(width*reduce);
2653             
2654             var gutter = this.twoPageGutter();
2655             var pageL;
2656             if ('L' == this.getPageSide(key)) {
2657                 pageL = gutter-scaledW;
2658             } else {
2659                 pageL = gutter;
2660             }
2661             var pageT  = this.twoPageTop();
2662             
2663             $(result.div).css({
2664                 width:  (result.r-result.l)*reduce + 'px',
2665                 height: (result.b-result.t)*reduce + 'px',
2666                 left:   pageL+(result.l)*reduce + 'px',
2667                 top:    pageT+(result.t)*reduce +'px'
2668             });
2669
2670         } else {
2671             //console.log(key + ' not displayed');
2672             if (null != this.searchResults[key].div) {
2673                 //console.log('removing ' + key);
2674                 $(this.searchResults[key].div).remove();
2675             }
2676             this.searchResults[key].div=null;
2677         }
2678     }
2679 }
2680
2681 // removeSearchHilites()
2682 //______________________________________________________________________________
2683 BookReader.prototype.removeSearchHilites = function() {
2684     for (var key in this.searchResults) {
2685         if (null != this.searchResults[key].div) {
2686             $(this.searchResults[key].div).remove();
2687             this.searchResults[key].div=null;
2688         }        
2689     }
2690 }
2691
2692 // printPage
2693 //______________________________________________________________________________
2694 BookReader.prototype.printPage = function() {
2695     window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2696
2697     /* iframe implementation
2698
2699     if (null != this.printPopup) { // check if already showing
2700         return;
2701     }
2702     this.printPopup = document.createElement("div");
2703     $(this.printPopup).css({
2704         position: 'absolute',
2705         top:      '20px',
2706         left:     ($('#BRcontainer').width()-400)/2 + 'px',
2707         width:    '400px',
2708         padding:  "20px",
2709         border:   "3px double #999999",
2710         zIndex:   3,
2711         backgroundColor: "#fff"
2712     }).appendTo('#BookReader');
2713
2714     var indexToPrint;
2715     if (this.constMode1up == this.mode) {
2716         indexToPrint = this.firstIndex;
2717     } else {
2718         indexToPrint = this.twoPage.currentIndexL;
2719     }
2720     
2721     this.indexToPrint = indexToPrint;
2722     
2723     var htmlStr = '<div style="text-align: center;">';
2724     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>';
2725     htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2726     htmlStr +=   '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2727     //htmlStr +=     '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2728     //htmlStr +=     '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2729     htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2730     htmlStr +=   '</p>';
2731     htmlStr += '</div>';
2732     htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2733     htmlStr += '</div>';
2734     
2735     this.printPopup.innerHTML = htmlStr;
2736     
2737     var iframe = document.createElement('iframe');
2738     iframe.id = 'printFrame';
2739     iframe.name = 'printFrame';
2740     iframe.width = '233px'; // 8.5 x 11 aspect
2741     iframe.height = '300px';
2742     
2743     var self = this; // closure
2744         
2745     $(iframe).load(function() {
2746         var doc = BookReader.util.getIFrameDocument(this);
2747         $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2748     });
2749     
2750     $('#printDiv').prepend(iframe);
2751     */
2752 }
2753
2754 // Get print URI from current indices and mode
2755 BookReader.prototype.getPrintURI = function() {
2756     var indexToPrint;
2757     if (this.constMode2up == this.mode) {
2758         indexToPrint = this.twoPage.currentIndexL;        
2759     } else {
2760         indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2761     }
2762     
2763     var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2764         + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2765         + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2766    
2767     if (this.constMode2up == this.mode) {
2768         options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2769         options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2770         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2771     } else {
2772         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2773     }
2774
2775     return '/bookreader/print.php?' + options;
2776 }
2777
2778 /* iframe implementation
2779 BookReader.prototype.getPrintFrameContent = function(index) {    
2780     // We fit the image based on an assumed A4 aspect ratio.  A4 is a bit taller aspect than
2781     // 8.5x11 so we should end up not overflowing on either paper size.
2782     var paperAspect = 8.5 / 11;
2783     var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2784     
2785     var rotate = 0;
2786     
2787     // Rotate if possible and appropriate, to get larger image size on printed page
2788     if (this.canRotatePage(index)) {
2789         if (imageAspect > 1 && imageAspect > paperAspect) {
2790             // more wide than square, and more wide than paper
2791             rotate = 90;
2792             imageAspect = 1/imageAspect;
2793         }
2794     }
2795     
2796     var fitAttrs;
2797     if (imageAspect > paperAspect) {
2798         // wider than paper, fit width
2799         fitAttrs = 'width="95%"';
2800     } else {
2801         // taller than paper, fit height
2802         fitAttrs = 'height="95%"';
2803     }
2804
2805     var imageURL = this._getPageURI(index, 1, rotate);
2806     var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2807     iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2808     iframeStr +=   '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2809     iframeStr += '</div>';
2810     iframeStr += '</body></html>';
2811     
2812     return iframeStr;
2813 }
2814
2815 BookReader.prototype.updatePrintFrame = function(delta) {
2816     var newIndex = this.indexToPrint + delta;
2817     newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2818     if (newIndex == this.indexToPrint) {
2819         return;
2820     }
2821     this.indexToPrint = newIndex;
2822     var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2823     $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2824 }
2825 */
2826
2827 // showEmbedCode()
2828 //______________________________________________________________________________
2829 BookReader.prototype.showEmbedCode = function() {
2830     if (null != this.embedPopup) { // check if already showing
2831         return;
2832     }
2833     this.autoStop();
2834     this.embedPopup = document.createElement("div");
2835     $(this.embedPopup).css({
2836         position: 'absolute',
2837         top:      '20px',
2838         left:     ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2839         width:    '400px',
2840         padding:  "20px",
2841         border:   "3px double #999999",
2842         zIndex:   3,
2843         backgroundColor: "#fff"
2844     }).appendTo('#BookReader');
2845
2846     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2847     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>';
2848     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2849     htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2850
2851     this.embedPopup.innerHTML = htmlStr;
2852     $(this.embedPopup).find('input').bind('click', function() {
2853         this.select();
2854     })
2855 }
2856
2857 // autoToggle()
2858 //______________________________________________________________________________
2859 BookReader.prototype.autoToggle = function() {
2860
2861     var bComingFrom1up = false;
2862     if (2 != this.mode) {
2863         bComingFrom1up = true;
2864         this.switchMode(2);
2865     }
2866     
2867     // Change to autofit if book is too large
2868     if (this.reduce < this.twoPageGetAutofitReduce()) {
2869         this.zoom2up(0);
2870     }
2871
2872     var self = this;
2873     if (null == this.autoTimer) {
2874         this.flipSpeed = 2000;
2875         
2876         // $$$ Draw events currently cause layout problems when they occur during animation.
2877         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2878         //     we workaround for now by not triggering immediate animation in that case.
2879         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2880         if (('rl' == this.pageProgression) && bComingFrom1up) {
2881             // don't flip immediately -- wait until timer fires
2882         } else {
2883             // flip immediately
2884             this.flipFwdToIndex();        
2885         }
2886
2887         $('#BRtoolbar .play').hide();
2888         $('#BRtoolbar .pause').show();
2889         this.autoTimer=setInterval(function(){
2890             if (self.animating) {return;}
2891             
2892             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2893                 self.flipBackToIndex(1); // $$$ really what we want?
2894             } else {            
2895                 self.flipFwdToIndex();
2896             }
2897         },5000);
2898     } else {
2899         this.autoStop();
2900     }
2901 }
2902
2903 // autoStop()
2904 //______________________________________________________________________________
2905 // Stop autoplay mode, allowing animations to finish
2906 BookReader.prototype.autoStop = function() {
2907     if (null != this.autoTimer) {
2908         clearInterval(this.autoTimer);
2909         this.flipSpeed = 'fast';
2910         $('#BRtoolbar .pause').hide();
2911         $('#BRtoolbar .play').show();
2912         this.autoTimer = null;
2913     }
2914 }
2915
2916 // stopFlipAnimations
2917 //______________________________________________________________________________
2918 // Immediately stop flip animations.  Callbacks are triggered.
2919 BookReader.prototype.stopFlipAnimations = function() {
2920
2921     this.autoStop(); // Clear timers
2922
2923     // Stop animation, clear queue, trigger callbacks
2924     if (this.leafEdgeTmp) {
2925         $(this.leafEdgeTmp).stop(false, true);
2926     }
2927     jQuery.each(this.prefetchedImgs, function() {
2928         $(this).stop(false, true);
2929         });
2930
2931     // And again since animations also queued in callbacks
2932     if (this.leafEdgeTmp) {
2933         $(this.leafEdgeTmp).stop(false, true);
2934     }
2935     jQuery.each(this.prefetchedImgs, function() {
2936         $(this).stop(false, true);
2937         });
2938    
2939 }
2940
2941 // keyboardNavigationIsDisabled(event)
2942 //   - returns true if keyboard navigation should be disabled for the event
2943 //______________________________________________________________________________
2944 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2945     if (event.target.tagName == "INPUT") {
2946         return true;
2947     }   
2948     return false;
2949 }
2950
2951 // gutterOffsetForIndex
2952 //______________________________________________________________________________
2953 //
2954 // Returns the gutter offset for the spread containing the given index.
2955 // This function supports RTL
2956 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2957
2958     // To find the offset of the gutter from the middle we calculate our percentage distance
2959     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2960     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2961     
2962     // But then again for RTL it's the opposite
2963     if ('rl' == this.pageProgression) {
2964         offset = -offset;
2965     }
2966     
2967     return offset;
2968 }
2969
2970 // leafEdgeWidth
2971 //______________________________________________________________________________
2972 // Returns the width of the leaf edge div for the page with index given
2973 BookReader.prototype.leafEdgeWidth = function(pindex) {
2974     // $$$ could there be single pixel rounding errors for L vs R?
2975     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2976         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2977     } else {
2978         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2979     }
2980 }
2981
2982 // jumpIndexForLeftEdgePageX
2983 //______________________________________________________________________________
2984 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2985 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2986     if ('rl' != this.pageProgression) {
2987         // LTR - flipping backward
2988         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2989
2990         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
2991         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2992         return jumpIndex;
2993
2994     } else {
2995         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2996         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2997         return jumpIndex;
2998     }
2999 }
3000
3001 // jumpIndexForRightEdgePageX
3002 //______________________________________________________________________________
3003 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3004 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3005     if ('rl' != this.pageProgression) {
3006         // LTR
3007         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3008         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3009         return jumpIndex;
3010     } else {
3011         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3012         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3013         return jumpIndex;
3014     }
3015 }
3016
3017 BookReader.prototype.initToolbar = function(mode, ui) {
3018
3019     $("#BookReader").append("<div id='BRtoolbar'>"
3020         + "<span id='BRtoolbarbuttons' style='float: right'>"
3021         +   "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3022         +   "<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>"
3023         +   "<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>"
3024         +   "<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>"
3025         +   "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3026         + "</span>"
3027         
3028         + "<span>"
3029         +   "<a class='BRicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
3030         +   " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>" 
3031         +   "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3032         +   " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3033         +   " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3034         +   " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3035         +   " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3036         + "</span>"
3037         
3038         + "<span id='#BRbooktitle'>"
3039         +   "&nbsp;&nbsp;<a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3040         + "</span>"
3041         + "</div>");
3042     
3043     this.updateToolbarZoom(this.reduce); // Pretty format
3044         
3045     if (ui == "embed") {
3046         $("#BookReader a.logo").attr("target","_blank");
3047     }
3048
3049     // $$$ turn this into a member variable
3050     var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3051     
3052     // We build in mode 2
3053     jToolbar.append();
3054
3055     this.bindToolbarNavHandlers(jToolbar);
3056     
3057     // Setup tooltips -- later we could load these from a file for i18n
3058     var titles = { '.logo': 'Go to Archive.org',
3059                    '.zoom_in': 'Zoom in',
3060                    '.zoom_out': 'Zoom out',
3061                    '.one_page_mode': 'One-page view',
3062                    '.two_page_mode': 'Two-page view',
3063                    '.thumbnail_mode': 'Thumbnail view',
3064                    '.print': 'Print this page',
3065                    '.embed': 'Embed bookreader',
3066                    '.book_left': 'Flip left',
3067                    '.book_right': 'Flip right',
3068                    '.book_up': 'Page up',
3069                    '.book_down': 'Page down',
3070                    '.play': 'Play',
3071                    '.pause': 'Pause',
3072                    '.book_top': 'First page',
3073                    '.book_bottom': 'Last page'
3074                   };
3075     if ('rl' == this.pageProgression) {
3076         titles['.book_leftmost'] = 'Last page';
3077         titles['.book_rightmost'] = 'First page';
3078     } else { // LTR
3079         titles['.book_leftmost'] = 'First page';
3080         titles['.book_rightmost'] = 'Last page';
3081     }
3082                   
3083     for (var icon in titles) {
3084         jToolbar.find(icon).attr('title', titles[icon]);
3085     }
3086     
3087     // Hide mode buttons and autoplay if 2up is not available
3088     // $$$ if we end up with more than two modes we should show the applicable buttons
3089     if ( !this.canSwitchToMode(this.constMode2up) ) {
3090         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3091     }
3092
3093     // Switch to requested mode -- binds other click handlers
3094     this.switchToolbarMode(mode);
3095     
3096 }
3097
3098
3099 // switchToolbarMode
3100 //______________________________________________________________________________
3101 // Update the toolbar for the given mode (changes navigation buttons)
3102 // $$$ we should soon split the toolbar out into its own module
3103 BookReader.prototype.switchToolbarMode = function(mode) { 
3104     if (1 == mode) {
3105         // 1-up
3106         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3107         $('#BRtoolbar .BRtoolbarmode2').hide();
3108         $('#BRtoolbar .BRtoolbarmode3').hide();
3109         $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3110     } else if (2 == mode) {
3111         // 2-up
3112         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3113         $('#BRtoolbar .BRtoolbarmode1').hide();
3114         $('#BRtoolbar .BRtoolbarmode3').hide();
3115         $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3116     } else {
3117         // 3-up    
3118         $('#BRtoolbar .BRtoolbarzoom').hide();
3119         $('#BRtoolbar .BRtoolbarmode2').hide();
3120         $('#BRtoolbar .BRtoolbarmode1').hide();
3121         $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3122     }
3123 }
3124
3125 // bindToolbarNavHandlers
3126 //______________________________________________________________________________
3127 // Binds the toolbar handlers
3128 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3129
3130     var self = this; // closure
3131
3132     jToolbar.find('.book_left').bind('click', function(e) {
3133         self.left();
3134         return false;
3135     });
3136          
3137     jToolbar.find('.book_right').bind('click', function(e) {
3138         self.right();
3139         return false;
3140     });
3141         
3142     jToolbar.find('.book_up').bind('click', function(e) {
3143         self.prev();
3144         return false;
3145     });        
3146         
3147     jToolbar.find('.book_down').bind('click', function(e) {
3148         self.next();
3149         return false;
3150     });
3151
3152     jToolbar.find('.print').bind('click', function(e) {
3153         self.printPage();
3154         return false;
3155     });
3156         
3157     jToolbar.find('.embed').bind('click', function(e) {
3158         self.showEmbedCode();
3159         return false;
3160     });
3161
3162     jToolbar.find('.play').bind('click', function(e) {
3163         self.autoToggle();
3164         return false;
3165     });
3166
3167     jToolbar.find('.pause').bind('click', function(e) {
3168         self.autoToggle();
3169         return false;
3170     });
3171     
3172     jToolbar.find('.book_top').bind('click', function(e) {
3173         self.first();
3174         return false;
3175     });
3176
3177     jToolbar.find('.book_bottom').bind('click', function(e) {
3178         self.last();
3179         return false;
3180     });
3181     
3182     jToolbar.find('.book_leftmost').bind('click', function(e) {
3183         self.leftmost();
3184         return false;
3185     });
3186   
3187     jToolbar.find('.book_rightmost').bind('click', function(e) {
3188         self.rightmost();
3189         return false;
3190     });
3191 }
3192
3193 // updateToolbarZoom(reduce)
3194 //______________________________________________________________________________
3195 // Update the displayed zoom factor based on reduction factor
3196 BookReader.prototype.updateToolbarZoom = function(reduce) {
3197     var value;
3198     if (this.constMode2up == this.mode && this.twoPage.autofit) {
3199         value = 'Auto';
3200     } else {
3201         value = (100 / reduce).toFixed(2);
3202         // Strip trailing zeroes and decimal if all zeroes
3203         value = value.replace(/0+$/,'');
3204         value = value.replace(/\.$/,'');
3205         value += '%';
3206     }
3207     $('#BRzoom').text(value);
3208 }
3209
3210 // firstDisplayableIndex
3211 //______________________________________________________________________________
3212 // Returns the index of the first visible page, dependent on the mode.
3213 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3214 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3215 BookReader.prototype.firstDisplayableIndex = function() {
3216     if (this.mode != this.constMode2up) {
3217         return 0;
3218     }
3219     
3220     if ('rl' != this.pageProgression) {
3221         // LTR
3222         if (this.getPageSide(0) == 'L') {
3223             return 0;
3224         } else {
3225             return -1;
3226         }
3227     } else {
3228         // RTL
3229         if (this.getPageSide(0) == 'R') {
3230             return 0;
3231         } else {
3232             return -1;
3233         }
3234     }
3235 }
3236
3237 // lastDisplayableIndex
3238 //______________________________________________________________________________
3239 // Returns the index of the last visible page, dependent on the mode.
3240 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3241 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
3242 BookReader.prototype.lastDisplayableIndex = function() {
3243
3244     var lastIndex = this.numLeafs - 1;
3245     
3246     if (this.mode != this.constMode2up) {
3247         return lastIndex;
3248     }
3249
3250     if ('rl' != this.pageProgression) {
3251         // LTR
3252         if (this.getPageSide(lastIndex) == 'R') {
3253             return lastIndex;
3254         } else {
3255             return lastIndex + 1;
3256         }
3257     } else {
3258         // RTL
3259         if (this.getPageSide(lastIndex) == 'L') {
3260             return lastIndex;
3261         } else {
3262             return lastIndex + 1;
3263         }
3264     }
3265 }
3266
3267 // shortTitle(maximumCharacters)
3268 //________
3269 // Returns a shortened version of the title with the maximum number of characters
3270 BookReader.prototype.shortTitle = function(maximumCharacters) {
3271     if (this.bookTitle.length < maximumCharacters) {
3272         return this.bookTitle;
3273     }
3274     
3275     var title = this.bookTitle.substr(0, maximumCharacters - 3);
3276     title += '...';
3277     return title;
3278 }
3279
3280 // Parameter related functions
3281
3282 // updateFromParams(params)
3283 //________
3284 // Update ourselves from the params object.
3285 //
3286 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3287 BookReader.prototype.updateFromParams = function(params) {
3288     if ('undefined' != typeof(params.mode)) {
3289         this.switchMode(params.mode);
3290     }
3291
3292     // process /search
3293     if ('undefined' != typeof(params.searchTerm)) {
3294         if (this.searchTerm != params.searchTerm) {
3295             this.search(params.searchTerm);
3296         }
3297     }
3298     
3299     // $$$ process /zoom
3300     
3301     // We only respect page if index is not set
3302     if ('undefined' != typeof(params.index)) {
3303         if (params.index != this.currentIndex()) {
3304             this.jumpToIndex(params.index);
3305         }
3306     } else if ('undefined' != typeof(params.page)) {
3307         // $$$ this assumes page numbers are unique
3308         if (params.page != this.getPageNum(this.currentIndex())) {
3309             this.jumpToPage(params.page);
3310         }
3311     }
3312     
3313     // $$$ process /region
3314     // $$$ process /highlight
3315 }
3316
3317 // paramsFromFragment(urlFragment)
3318 //________
3319 // Returns a object with configuration parametes from a URL fragment.
3320 //
3321 // E.g paramsFromFragment(window.location.hash)
3322 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3323     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3324
3325     var params = {};
3326     
3327     // For convenience we allow an initial # character (as from window.location.hash)
3328     // but don't require it
3329     if (urlFragment.substr(0,1) == '#') {
3330         urlFragment = urlFragment.substr(1);
3331     }
3332     
3333     // Simple #nn syntax
3334     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3335     if ( !isNaN(oldStyleLeafNum) ) {
3336         params.index = oldStyleLeafNum;
3337         
3338         // Done processing if using old-style syntax
3339         return params;
3340     }
3341     
3342     // Split into key-value pairs
3343     var urlArray = urlFragment.split('/');
3344     var urlHash = {};
3345     for (var i = 0; i < urlArray.length; i += 2) {
3346         urlHash[urlArray[i]] = urlArray[i+1];
3347     }
3348     
3349     // Mode
3350     if ('1up' == urlHash['mode']) {
3351         params.mode = this.constMode1up;
3352     } else if ('2up' == urlHash['mode']) {
3353         params.mode = this.constMode2up;
3354     } else if ('thumb' == urlHash['mode']) {
3355         params.mode = this.constModeThumb;
3356     }
3357     
3358     // Index and page
3359     if ('undefined' != typeof(urlHash['page'])) {
3360         // page was set -- may not be int
3361         params.page = urlHash['page'];
3362     }
3363     
3364     // $$$ process /region
3365     // $$$ process /search
3366     
3367     if (urlHash['search'] != undefined) {
3368         params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3369     }
3370     
3371     // $$$ process /highlight
3372         
3373     return params;
3374 }
3375
3376 // paramsFromCurrent()
3377 //________
3378 // Create a params object from the current parameters.
3379 BookReader.prototype.paramsFromCurrent = function() {
3380
3381     var params = {};
3382     
3383     var index = this.currentIndex();
3384     var pageNum = this.getPageNum(index);
3385     if ((pageNum === 0) || pageNum) {
3386         params.page = pageNum;
3387     }
3388     
3389     params.index = index;
3390     params.mode = this.mode;
3391     
3392     // $$$ highlight
3393     // $$$ region
3394
3395     // search    
3396     if (this.searchHighlightVisible()) {
3397         params.searchTerm = this.searchTerm;
3398     }
3399     
3400     return params;
3401 }
3402
3403 // fragmentFromParams(params)
3404 //________
3405 // Create a fragment string from the params object.
3406 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3407 BookReader.prototype.fragmentFromParams = function(params) {
3408     var separator = '/';
3409
3410     var fragments = [];
3411     
3412     if ('undefined' != typeof(params.page)) {
3413         fragments.push('page', params.page);
3414     } else {
3415         // Don't have page numbering -- use index instead
3416         fragments.push('page', 'n' + params.index);
3417     }
3418     
3419     // $$$ highlight
3420     // $$$ region
3421     
3422     // mode
3423     if ('undefined' != typeof(params.mode)) {    
3424         if (params.mode == this.constMode1up) {
3425             fragments.push('mode', '1up');
3426         } else if (params.mode == this.constMode2up) {
3427             fragments.push('mode', '2up');
3428         } else if (params.mode == this.constModeThumb) {
3429             fragments.push('mode', 'thumb');
3430         } else {
3431             throw 'fragmentFromParams called with unknown mode ' + params.mode;
3432         }
3433     }
3434     
3435     // search
3436     if (params.searchTerm) {
3437         fragments.push('search', params.searchTerm);
3438     }
3439     
3440     return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3441 }
3442
3443 // getPageIndex(pageNum)
3444 //________
3445 // Returns the *highest* index the given page number, or undefined
3446 BookReader.prototype.getPageIndex = function(pageNum) {
3447     var pageIndices = this.getPageIndices(pageNum);
3448     
3449     if (pageIndices.length > 0) {
3450         return pageIndices[pageIndices.length - 1];
3451     }
3452
3453     return undefined;
3454 }
3455
3456 // getPageIndices(pageNum)
3457 //________
3458 // Returns an array (possibly empty) of the indices with the given page number
3459 BookReader.prototype.getPageIndices = function(pageNum) {
3460     var indices = [];
3461
3462     // Check for special "nXX" page number
3463     if (pageNum.slice(0,1) == 'n') {
3464         try {
3465             var pageIntStr = pageNum.slice(1, pageNum.length);
3466             var pageIndex = parseInt(pageIntStr);
3467             indices.push(pageIndex);
3468             return indices;
3469         } catch(err) {
3470             // Do nothing... will run through page names and see if one matches
3471         }
3472     }
3473
3474     var i;
3475     for (i=0; i<this.numLeafs; i++) {
3476         if (this.getPageNum(i) == pageNum) {
3477             indices.push(i);
3478         }
3479     }
3480     
3481     return indices;
3482 }
3483
3484 // getPageName(index)
3485 //________
3486 // Returns the name of the page as it should be displayed in the user interface
3487 BookReader.prototype.getPageName = function(index) {
3488     return 'Page ' + this.getPageNum(index);
3489 }
3490
3491 // updateLocationHash
3492 //________
3493 // Update the location hash from the current parameters.  Call this instead of manually
3494 // using window.location.replace
3495 BookReader.prototype.updateLocationHash = function() {
3496     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3497     window.location.replace(newHash);
3498     
3499     // This is the variable checked in the timer.  Only user-generated changes
3500     // to the URL will trigger the event.
3501     this.oldLocationHash = newHash;
3502 }
3503
3504 // startLocationPolling
3505 //________
3506 // Starts polling of window.location to see hash fragment changes
3507 BookReader.prototype.startLocationPolling = function() {
3508     var self = this; // remember who I am
3509     self.oldLocationHash = window.location.hash;
3510     
3511     if (this.locationPollId) {
3512         clearInterval(this.locationPollID);
3513         this.locationPollId = null;
3514     }
3515     
3516     this.locationPollId = setInterval(function() {
3517         var newHash = window.location.hash;
3518         if (newHash != self.oldLocationHash) {
3519             if (newHash != self.oldUserHash) { // Only process new user hash once
3520                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3521                 
3522                 // Queue change if animating
3523                 if (self.animating) {
3524                     self.autoStop();
3525                     self.animationFinishedCallback = function() {
3526                         self.updateFromParams(self.paramsFromFragment(newHash));
3527                     }                        
3528                 } else { // update immediately
3529                     self.updateFromParams(self.paramsFromFragment(newHash));
3530                 }
3531                 self.oldUserHash = newHash;
3532             }
3533         }
3534     }, 500);
3535 }
3536
3537 // canSwitchToMode
3538 //________
3539 // Returns true if we can switch to the requested mode
3540 BookReader.prototype.canSwitchToMode = function(mode) {
3541     if (mode == this.constMode2up) {
3542         // check there are enough pages to display
3543         // $$$ this is a workaround for the mis-feature that we can't display
3544         //     short books in 2up mode
3545         if (this.numLeafs < 6) {
3546             return false;
3547         }
3548     }
3549     
3550     return true;
3551 }
3552
3553 // searchHighlightVisible
3554 //________
3555 // Returns true if a search highlight is currently being displayed
3556 BookReader.prototype.searchHighlightVisible = function() {
3557     if (this.constMode2up == this.mode) {
3558         if (this.searchResults[this.twoPage.currentIndexL]
3559                 || this.searchResults[this.twoPage.currentIndexR]) {
3560             return true;
3561         }
3562     } else { // 1up
3563         if (this.searchResults[this.currentIndex()]) {
3564             return true;
3565         }
3566     }
3567     return false;
3568 }
3569
3570 // getPageBackgroundColor
3571 //--------
3572 // Returns a CSS property string for the background color for the given page
3573 // $$$ turn into regular CSS?
3574 BookReader.prototype.getPageBackgroundColor = function(index) {
3575     if (index >= 0 && index < this.numLeafs) {
3576         // normal page
3577         return this.pageDefaultBackgroundColor;
3578     }
3579     
3580     return '';
3581 }
3582
3583 // _getPageWidth
3584 //--------
3585 // Returns the page width for the given index, or first or last page if out of range
3586 BookReader.prototype._getPageWidth = function(index) {
3587     // Synthesize a page width for pages not actually present in book.
3588     // May or may not be the best approach.
3589     // If index is out of range we return the width of first or last page
3590     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3591     return this.getPageWidth(index);
3592 }
3593
3594 // _getPageHeight
3595 //--------
3596 // Returns the page height for the given index, or first or last page if out of range
3597 BookReader.prototype._getPageHeight= function(index) {
3598     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3599     return this.getPageHeight(index);
3600 }
3601
3602 // _getPageURI
3603 //--------
3604 // Returns the page URI or transparent image if out of range
3605 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3606     if (index < 0 || index >= this.numLeafs) { // Synthesize page
3607         return this.imagesBaseURL + "/transparent.png";
3608     }
3609     
3610     if ('undefined' == typeof(reduce)) {
3611         // reduce not passed in
3612         // $$$ this probably won't work for thumbnail mode
3613         var ratio = this.getPageHeight(index) / this.twoPage.height;
3614         var scale;
3615         // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3616         if (ratio < 2) {
3617             scale = 1;
3618         } else if (ratio < 4) {
3619             scale = 2;
3620         } else if (ratio < 8) {
3621             scale = 4;
3622         } else if (ratio < 16) {
3623             scale = 8;
3624         } else  if (ratio < 32) {
3625             scale = 16;
3626         } else {
3627             scale = 32;
3628         }
3629         reduce = scale;
3630     }
3631     
3632     return this.getPageURI(index, reduce, rotate);
3633 }
3634
3635 // Library functions
3636 BookReader.util = {
3637     clamp: function(value, min, max) {
3638         return Math.min(Math.max(value, min), max);
3639     },
3640
3641     getIFrameDocument: function(iframe) {
3642         // Adapted from http://xkr.us/articles/dom/iframe-document/
3643         var outer = (iframe.contentWindow || iframe.contentDocument);
3644         return (outer.document || outer);
3645     },
3646     
3647     decodeURIComponentPlus: function(value) {
3648         // Decodes a URI component and converts '+' to ' '
3649         return decodeURIComponent(value).replace(/\+/g, ' ');
3650     },
3651     
3652     encodeURIComponentPlus: function(value) {
3653         // Encodes a URI component and converts ' ' to '+'
3654         return encodeURIComponent(value).replace(/%20/g, '+');
3655     }
3656     // The final property here must NOT have a comma after it - IE7
3657 }