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