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