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