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