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