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