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