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