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