More CSS cleanup
[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.className = 'BRleafEdgeTmp';
2094     $(this.leafEdgeTmp).css({
2095         width: leafEdgeTmpW + 'px',
2096         height: this.twoPage.height-1 + 'px',
2097         left: gutter+scaledW+'px',
2098         top: top+'px',    
2099         zIndex:1000
2100     }).appendTo('#BRtwopageview');
2101
2102     //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2103     //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2104     
2105     var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2106     var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2107     var newWidthL = this.getPageWidth2UP(newIndexL);
2108     var newWidthR = this.getPageWidth2UP(newIndexR);
2109     
2110     $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2111
2112     var self = this; // closure-tastic!
2113
2114     var speed = this.flipSpeed;
2115
2116     this.removeSearchHilites();
2117     
2118     $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');    
2119     $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2120         $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');    
2121         $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2122             $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2123             
2124             $(self.leafEdgeL).css({
2125                 width: newLeafEdgeWidthL+'px', 
2126                 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2127             });
2128             
2129             // Resizes the book cover
2130             $(self.twoPage.coverDiv).css({
2131                 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2132                 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2133             });
2134             
2135             $(self.leafEdgeTmp).remove();
2136             self.leafEdgeTmp = null;
2137             
2138             self.twoPage.currentIndexL = newIndexL;
2139             self.twoPage.currentIndexR = newIndexR;
2140             self.twoPage.scaledWL = newWidthL;
2141             self.twoPage.scaledWR = newWidthR;
2142             self.twoPage.gutter = gutter;
2143
2144             self.firstIndex = self.twoPage.currentIndexL;
2145             self.displayedIndices = [newIndexL, newIndexR];
2146             self.pruneUnusedImgs();
2147             self.prefetch();
2148             self.animating = false;
2149
2150
2151             self.updateSearchHilites2UP();
2152             self.updatePageNumBox2UP();
2153             
2154             // self.twoPagePlaceFlipAreas(); // No longer used
2155             self.setMouseHandlers2UP();     
2156             self.twoPageSetCursor();
2157             
2158             if (self.animationFinishedCallback) {
2159                 self.animationFinishedCallback();
2160                 self.animationFinishedCallback = null;
2161             }
2162         });
2163     });    
2164 }
2165
2166 // setMouseHandlers2UP
2167 //______________________________________________________________________________
2168 BookReader.prototype.setMouseHandlers2UP = function() {
2169     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2170         { self: this },
2171         function(e) {
2172             e.data.self.left();
2173             e.preventDefault();
2174         }
2175     );
2176         
2177     this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2178         { self: this },
2179         function(e) {
2180             e.data.self.right();
2181             e.preventDefault();
2182         }
2183     );
2184 }
2185
2186 // prefetchImg()
2187 //______________________________________________________________________________
2188 BookReader.prototype.prefetchImg = function(index) {
2189     var pageURI = this._getPageURI(index);
2190
2191     // Load image if not loaded or URI has changed (e.g. due to scaling)
2192     var loadImage = false;
2193     if (undefined == this.prefetchedImgs[index]) {
2194         //console.log('no image for ' + index);
2195         loadImage = true;
2196     } else if (pageURI != this.prefetchedImgs[index].uri) {
2197         //console.log('uri changed for ' + index);
2198         loadImage = true;
2199     }
2200     
2201     if (loadImage) {
2202         //console.log('prefetching ' + index);
2203         var img = document.createElement("img");
2204         img.src = pageURI;
2205         img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2206         this.prefetchedImgs[index] = img;
2207     }
2208 }
2209
2210
2211 // prepareFlipLeftToRight()
2212 //
2213 //______________________________________________________________________________
2214 //
2215 // Prepare to flip the left page towards the right.  This corresponds to moving
2216 // backward when the page progression is left to right.
2217 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2218
2219     //console.log('  preparing left->right for ' + prevL + ',' + prevR);
2220
2221     this.prefetchImg(prevL);
2222     this.prefetchImg(prevR);
2223     
2224     var height  = this._getPageHeight(prevL); 
2225     var width   = this._getPageWidth(prevL);    
2226     var middle = this.twoPage.middle;
2227     var top  = this.twoPageTop();                
2228     var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2229
2230     // The gutter is the dividing line between the left and right pages.
2231     // It is offset from the middle to create the illusion of thickness to the pages
2232     var gutter = middle + this.gutterOffsetForIndex(prevL);
2233     
2234     //console.log('    gutter for ' + prevL + ' is ' + gutter);
2235     //console.log('    prevL.left: ' + (gutter - scaledW) + 'px');
2236     //console.log('    changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2237     
2238     leftCSS = {
2239         position: 'absolute',
2240         left: gutter-scaledW+'px',
2241         right: '', // clear right property
2242         top:    top+'px',
2243         height: this.twoPage.height,
2244         width:  scaledW+'px',
2245         backgroundColor: this.getPageBackgroundColor(prevL),
2246         borderRight: '1px solid black',
2247         zIndex: 1
2248     }
2249     
2250     $(this.prefetchedImgs[prevL]).css(leftCSS);
2251
2252     $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2253
2254     //console.log('    changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2255
2256     rightCSS = {
2257         position: 'absolute',
2258         left:   gutter+'px',
2259         right: '',
2260         top:    top+'px',
2261         height: this.twoPage.height,
2262         width:  '0px',
2263         backgroundColor: this.getPageBackgroundColor(prevR),
2264         borderLeft: '1px solid black',
2265         zIndex: 2
2266     }
2267     
2268     $(this.prefetchedImgs[prevR]).css(rightCSS);
2269
2270     $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2271             
2272 }
2273
2274 // $$$ mang we're adding an extra pixel in the middle.  See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2275 // prepareFlipRightToLeft()
2276 //______________________________________________________________________________
2277 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2278
2279     //console.log('  preparing left<-right for ' + nextL + ',' + nextR);
2280
2281     // Prefetch images
2282     this.prefetchImg(nextL);
2283     this.prefetchImg(nextR);
2284
2285     var height  = this._getPageHeight(nextR); 
2286     var width   = this._getPageWidth(nextR);    
2287     var middle = this.twoPage.middle;
2288     var top  = this.twoPageTop();               
2289     var scaledW = this.twoPage.height*width/height;
2290
2291     var gutter = middle + this.gutterOffsetForIndex(nextL);
2292         
2293     //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2294     $(this.prefetchedImgs[nextR]).css({
2295         position: 'absolute',
2296         left:   gutter+'px',
2297         top:    top+'px',
2298         backgroundColor: this.getPageBackgroundColor(nextR),
2299         height: this.twoPage.height,
2300         width:  scaledW+'px',
2301         borderLeft: '1px solid black',
2302         zIndex: 1
2303     });
2304
2305     $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2306
2307     height  = this._getPageHeight(nextL); 
2308     width   = this._getPageWidth(nextL);      
2309     scaledW = this.twoPage.height*width/height;
2310
2311     //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2312     $(this.prefetchedImgs[nextL]).css({
2313         position: 'absolute',
2314         right:   $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2315         top:    top+'px',
2316         backgroundColor: this.getPageBackgroundColor(nextL),
2317         height: this.twoPage.height,
2318         width:  0+'px', // Start at 0 width, then grow to the left
2319         borderRight: '1px solid black',
2320         zIndex: 2
2321     });
2322
2323     $('#BRtwopageview').append(this.prefetchedImgs[nextL]);    
2324             
2325 }
2326
2327 // getNextLeafs() -- NOT RTL AWARE
2328 //______________________________________________________________________________
2329 // BookReader.prototype.getNextLeafs = function(o) {
2330 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2331 //     //For now, assume that leafs are contiguous.
2332 //     
2333 //     //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2334 //     o.L = this.twoPage.currentIndexL+2;
2335 //     o.R = this.twoPage.currentIndexL+3;
2336 // }
2337
2338 // getprevLeafs() -- NOT RTL AWARE
2339 //______________________________________________________________________________
2340 // BookReader.prototype.getPrevLeafs = function(o) {
2341 //     //TODO: we might have two left or two right leafs in a row (damaged book)
2342 //     //For now, assume that leafs are contiguous.
2343 //     
2344 //     //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2345 //     o.L = this.twoPage.currentIndexL-2;
2346 //     o.R = this.twoPage.currentIndexL-1;
2347 // }
2348
2349 // pruneUnusedImgs()
2350 //______________________________________________________________________________
2351 BookReader.prototype.pruneUnusedImgs = function() {
2352     //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2353     for (var key in this.prefetchedImgs) {
2354         //console.log('key is ' + key);
2355         if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2356             //console.log('removing key '+ key);
2357             $(this.prefetchedImgs[key]).remove();
2358         }
2359         if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2360             //console.log('deleting key '+ key);
2361             delete this.prefetchedImgs[key];
2362         }
2363     }
2364 }
2365
2366 // prefetch()
2367 //______________________________________________________________________________
2368 BookReader.prototype.prefetch = function() {
2369
2370     // $$$ We should check here if the current indices have finished
2371     //     loading (with some timeout) before loading more page images
2372     //     See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2373
2374     // prefetch visible pages first
2375     this.prefetchImg(this.twoPage.currentIndexL);
2376     this.prefetchImg(this.twoPage.currentIndexR);
2377         
2378     var adjacentPagesToLoad = 3;
2379     
2380     var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2381     var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2382         
2383     var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2384     var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2385     
2386     // Load images spreading out from current
2387     for (var i = 1; i <= adjacentPagesToLoad; i++) {
2388         var goingDown = lowCurrent - i;
2389         if (goingDown >= start) {
2390             this.prefetchImg(goingDown);
2391         }
2392         var goingUp = highCurrent + i;
2393         if (goingUp <= end) {
2394             this.prefetchImg(goingUp);
2395         }
2396     }
2397
2398     /*
2399     var lim = this.twoPage.currentIndexL-4;
2400     var i;
2401     lim = Math.max(lim, 0);
2402     for (i = lim; i < this.twoPage.currentIndexL; i++) {
2403         this.prefetchImg(i);
2404     }
2405     
2406     if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2407         lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2408         for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2409             this.prefetchImg(i);
2410         }
2411     }
2412     */
2413 }
2414
2415 // getPageWidth2UP()
2416 //______________________________________________________________________________
2417 BookReader.prototype.getPageWidth2UP = function(index) {
2418     // We return the width based on the dominant height
2419     var height  = this._getPageHeight(index); 
2420     var width   = this._getPageWidth(index);    
2421     return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2422 }    
2423
2424 // search()
2425 //______________________________________________________________________________
2426 BookReader.prototype.search = function(term) {
2427     term = term.replace(/\//g, ' '); // strip slashes
2428     this.searchTerm = term;
2429     $('#BookReaderSearchScript').remove();
2430     var script  = document.createElement("script");
2431     script.setAttribute('id', 'BookReaderSearchScript');
2432     script.setAttribute("type", "text/javascript");
2433     script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2434     document.getElementsByTagName('head')[0].appendChild(script);
2435     $('#BookReaderSearchBox').val(term);
2436     $('#BookReaderSearchResults').html('Searching...');
2437 }
2438
2439 // BRSearchCallback()
2440 //______________________________________________________________________________
2441 BookReader.prototype.BRSearchCallback = function(txt) {
2442     //alert(txt);
2443     if (jQuery.browser.msie) {
2444         var dom=new ActiveXObject("Microsoft.XMLDOM");
2445         dom.async="false";
2446         dom.loadXML(txt);    
2447     } else {
2448         var parser = new DOMParser();
2449         var dom = parser.parseFromString(txt, "text/xml");    
2450     }
2451     
2452     $('#BookReaderSearchResults').empty();    
2453     $('#BookReaderSearchResults').append('<ul>');
2454     
2455     for (var key in this.searchResults) {
2456         if (null != this.searchResults[key].div) {
2457             $(this.searchResults[key].div).remove();
2458         }
2459         delete this.searchResults[key];
2460     }
2461     
2462     var pages = dom.getElementsByTagName('PAGE');
2463     
2464     if (0 == pages.length) {
2465         // $$$ it would be nice to echo the (sanitized) search result here
2466         $('#BookReaderSearchResults').append('<li>No search results found</li>');
2467     } else {    
2468         for (var i = 0; i < pages.length; i++){
2469             //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2470     
2471             
2472             var re = new RegExp (/_(\d{4})\.djvu/);
2473             var reMatch = re.exec(pages[i].getAttribute('file'));
2474             var index = parseInt(reMatch[1], 10);
2475             //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2476             
2477             var children = pages[i].childNodes;
2478             var context = '';
2479             for (var j=0; j<children.length; j++) {
2480                 //console.log(j + ' - ' + children[j].nodeName);
2481                 //console.log(children[j].firstChild.nodeValue);
2482                 if ('CONTEXT' == children[j].nodeName) {
2483                     context += children[j].firstChild.nodeValue;
2484                 } else if ('WORD' == children[j].nodeName) {
2485                     context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2486                     
2487                     var index = this.leafNumToIndex(index);
2488                     if (null != index) {
2489                         //coordinates are [left, bottom, right, top, [baseline]]
2490                         //we'll skip baseline for now...
2491                         var coords = children[j].getAttribute('coords').split(',',4);
2492                         if (4 == coords.length) {
2493                             this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2494                         }
2495                     }
2496                 }
2497             }
2498             var pageName = this.getPageName(index);
2499             var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2500             var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2501             //TODO: remove hardcoded instance name
2502             $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2503         }
2504     }
2505     $('#BookReaderSearchResults').append('</ul>');
2506
2507     // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2508     $('#BookReaderSearchBox').val(this.searchTerm);
2509
2510     this.updateSearchHilites();
2511 }
2512
2513 // updateSearchHilites()
2514 //______________________________________________________________________________
2515 BookReader.prototype.updateSearchHilites = function() {
2516     if (2 == this.mode) {
2517         this.updateSearchHilites2UP();
2518     } else {
2519         this.updateSearchHilites1UP();
2520     }
2521 }
2522
2523 // showSearchHilites1UP()
2524 //______________________________________________________________________________
2525 BookReader.prototype.updateSearchHilites1UP = function() {
2526
2527     for (var key in this.searchResults) {
2528         
2529         if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2530             var result = this.searchResults[key];
2531             if (null == result.div) {
2532                 result.div = document.createElement('div');
2533                 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2534                 //console.log('appending ' + key);
2535             }    
2536             $(result.div).css({
2537                 width:  (result.r-result.l)/this.reduce + 'px',
2538                 height: (result.b-result.t)/this.reduce + 'px',
2539                 left:   (result.l)/this.reduce + 'px',
2540                 top:    (result.t)/this.reduce +'px'
2541             });
2542
2543         } else {
2544             //console.log(key + ' not displayed');
2545             this.searchResults[key].div=null;
2546         }
2547     }
2548 }
2549
2550 // twoPageGutter()
2551 //______________________________________________________________________________
2552 // Returns the position of the gutter (line between the page images)
2553 BookReader.prototype.twoPageGutter = function() {
2554     return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2555 }
2556
2557 // twoPageTop()
2558 //______________________________________________________________________________
2559 // Returns the offset for the top of the page images
2560 BookReader.prototype.twoPageTop = function() {
2561     return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2562 }
2563
2564 // twoPageCoverWidth()
2565 //______________________________________________________________________________
2566 // Returns the width of the cover div given the total page width
2567 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2568     return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2569 }
2570
2571 // twoPageGetViewCenter()
2572 //______________________________________________________________________________
2573 // Returns the percentage offset into twopageview div at the center of container div
2574 // { percentageX: float, percentageY: float }
2575 BookReader.prototype.twoPageGetViewCenter = function() {
2576     var center = {};
2577
2578     var containerOffset = $('#BRcontainer').offset();
2579     var viewOffset = $('#BRtwopageview').offset();
2580     center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2581     center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2582     
2583     return center;
2584 }
2585
2586 // twoPageCenterView(percentageX, percentageY)
2587 //______________________________________________________________________________
2588 // Centers the point given by percentage from left,top of twopageview
2589 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2590     if ('undefined' == typeof(percentageX)) {
2591         percentageX = 0.5;
2592     }
2593     if ('undefined' == typeof(percentageY)) {
2594         percentageY = 0.5;
2595     }
2596
2597     var viewWidth = $('#BRtwopageview').width();
2598     var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2599     var intoViewX = percentageX * viewWidth;
2600     
2601     var viewHeight = $('#BRtwopageview').height();
2602     var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2603     var intoViewY = percentageY * viewHeight;
2604     
2605     if (viewWidth < containerClientWidth) {
2606         // Can fit width without scrollbars - center by adjusting offset
2607         $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');    
2608     } else {
2609         // Need to scroll to center
2610         $('#BRtwopageview').css('left', 0);
2611         $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2612     }
2613     
2614     if (viewHeight < containerClientHeight) {
2615         // Fits with scrollbars - add offset
2616         $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2617     } else {
2618         $('#BRtwopageview').css('top', 0);
2619         $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2620     }
2621 }
2622
2623 // twoPageFlipAreaHeight
2624 //______________________________________________________________________________
2625 // Returns the integer height of the click-to-flip areas at the edges of the book
2626 BookReader.prototype.twoPageFlipAreaHeight = function() {
2627     return parseInt(this.twoPage.height);
2628 }
2629
2630 // twoPageFlipAreaWidth
2631 //______________________________________________________________________________
2632 // Returns the integer width of the flip areas 
2633 BookReader.prototype.twoPageFlipAreaWidth = function() {
2634     var max = 100; // $$$ TODO base on view width?
2635     var min = 10;
2636     
2637     var width = this.twoPage.width * 0.15;
2638     return parseInt(BookReader.util.clamp(width, min, max));
2639 }
2640
2641 // twoPageFlipAreaTop
2642 //______________________________________________________________________________
2643 // Returns integer top offset for flip areas
2644 BookReader.prototype.twoPageFlipAreaTop = function() {
2645     return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2646 }
2647
2648 // twoPageLeftFlipAreaLeft
2649 //______________________________________________________________________________
2650 // Left offset for left flip area
2651 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2652     return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2653 }
2654
2655 // twoPageRightFlipAreaLeft
2656 //______________________________________________________________________________
2657 // Left offset for right flip area
2658 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2659     return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2660 }
2661
2662 // twoPagePlaceFlipAreas
2663 //______________________________________________________________________________
2664 // Readjusts position of flip areas based on current layout
2665 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2666     // We don't set top since it shouldn't change relative to view
2667     $(this.twoPage.leftFlipArea).css({
2668         left: this.twoPageLeftFlipAreaLeft() + 'px',
2669         width: this.twoPageFlipAreaWidth() + 'px'
2670     });
2671     $(this.twoPage.rightFlipArea).css({
2672         left: this.twoPageRightFlipAreaLeft() + 'px',
2673         width: this.twoPageFlipAreaWidth() + 'px'
2674     });
2675 }
2676     
2677 // showSearchHilites2UP()
2678 //______________________________________________________________________________
2679 BookReader.prototype.updateSearchHilites2UP = function() {
2680
2681     for (var key in this.searchResults) {
2682         key = parseInt(key, 10);
2683         if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2684             var result = this.searchResults[key];
2685             if (null == result.div) {
2686                 result.div = document.createElement('div');
2687                 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2688                 //console.log('appending ' + key);
2689             }
2690
2691             // We calculate the reduction factor for the specific page because it can be different
2692             // for each page in the spread
2693             var height = this._getPageHeight(key);
2694             var width  = this._getPageWidth(key)
2695             var reduce = this.twoPage.height/height;
2696             var scaledW = parseInt(width*reduce);
2697             
2698             var gutter = this.twoPageGutter();
2699             var pageL;
2700             if ('L' == this.getPageSide(key)) {
2701                 pageL = gutter-scaledW;
2702             } else {
2703                 pageL = gutter;
2704             }
2705             var pageT  = this.twoPageTop();
2706             
2707             $(result.div).css({
2708                 width:  (result.r-result.l)*reduce + 'px',
2709                 height: (result.b-result.t)*reduce + 'px',
2710                 left:   pageL+(result.l)*reduce + 'px',
2711                 top:    pageT+(result.t)*reduce +'px'
2712             });
2713
2714         } else {
2715             //console.log(key + ' not displayed');
2716             if (null != this.searchResults[key].div) {
2717                 //console.log('removing ' + key);
2718                 $(this.searchResults[key].div).remove();
2719             }
2720             this.searchResults[key].div=null;
2721         }
2722     }
2723 }
2724
2725 // removeSearchHilites()
2726 //______________________________________________________________________________
2727 BookReader.prototype.removeSearchHilites = function() {
2728     for (var key in this.searchResults) {
2729         if (null != this.searchResults[key].div) {
2730             $(this.searchResults[key].div).remove();
2731             this.searchResults[key].div=null;
2732         }        
2733     }
2734 }
2735
2736 // printPage
2737 //______________________________________________________________________________
2738 BookReader.prototype.printPage = function() {
2739     window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2740
2741     /* iframe implementation
2742
2743     if (null != this.printPopup) { // check if already showing
2744         return;
2745     }
2746     this.printPopup = document.createElement("div");
2747     $(this.printPopup).css({
2748         position: 'absolute',
2749         top:      '20px',
2750         left:     ($('#BRcontainer').width()-400)/2 + 'px',
2751         width:    '400px',
2752         padding:  "20px",
2753         border:   "3px double #999999",
2754         zIndex:   3,
2755         backgroundColor: "#fff"
2756     }).appendTo('#BookReader');
2757
2758     var indexToPrint;
2759     if (this.constMode1up == this.mode) {
2760         indexToPrint = this.firstIndex;
2761     } else {
2762         indexToPrint = this.twoPage.currentIndexL;
2763     }
2764     
2765     this.indexToPrint = indexToPrint;
2766     
2767     var htmlStr = '<div style="text-align: center;">';
2768     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>';
2769     htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2770     htmlStr +=   '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2771     //htmlStr +=     '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2772     //htmlStr +=     '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2773     htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2774     htmlStr +=   '</p>';
2775     htmlStr += '</div>';
2776     htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2777     htmlStr += '</div>';
2778     
2779     this.printPopup.innerHTML = htmlStr;
2780     
2781     var iframe = document.createElement('iframe');
2782     iframe.id = 'printFrame';
2783     iframe.name = 'printFrame';
2784     iframe.width = '233px'; // 8.5 x 11 aspect
2785     iframe.height = '300px';
2786     
2787     var self = this; // closure
2788         
2789     $(iframe).load(function() {
2790         var doc = BookReader.util.getIFrameDocument(this);
2791         $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2792     });
2793     
2794     $('#printDiv').prepend(iframe);
2795     */
2796 }
2797
2798 // Get print URI from current indices and mode
2799 BookReader.prototype.getPrintURI = function() {
2800     var indexToPrint;
2801     if (this.constMode2up == this.mode) {
2802         indexToPrint = this.twoPage.currentIndexL;        
2803     } else {
2804         indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2805     }
2806     
2807     var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2808         + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2809         + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2810    
2811     if (this.constMode2up == this.mode) {
2812         options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2813         options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2814         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2815     } else {
2816         options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2817     }
2818
2819     return '/bookreader/print.php?' + options;
2820 }
2821
2822 /* iframe implementation
2823 BookReader.prototype.getPrintFrameContent = function(index) {    
2824     // We fit the image based on an assumed A4 aspect ratio.  A4 is a bit taller aspect than
2825     // 8.5x11 so we should end up not overflowing on either paper size.
2826     var paperAspect = 8.5 / 11;
2827     var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2828     
2829     var rotate = 0;
2830     
2831     // Rotate if possible and appropriate, to get larger image size on printed page
2832     if (this.canRotatePage(index)) {
2833         if (imageAspect > 1 && imageAspect > paperAspect) {
2834             // more wide than square, and more wide than paper
2835             rotate = 90;
2836             imageAspect = 1/imageAspect;
2837         }
2838     }
2839     
2840     var fitAttrs;
2841     if (imageAspect > paperAspect) {
2842         // wider than paper, fit width
2843         fitAttrs = 'width="95%"';
2844     } else {
2845         // taller than paper, fit height
2846         fitAttrs = 'height="95%"';
2847     }
2848
2849     var imageURL = this._getPageURI(index, 1, rotate);
2850     var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2851     iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2852     iframeStr +=   '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2853     iframeStr += '</div>';
2854     iframeStr += '</body></html>';
2855     
2856     return iframeStr;
2857 }
2858
2859 BookReader.prototype.updatePrintFrame = function(delta) {
2860     var newIndex = this.indexToPrint + delta;
2861     newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2862     if (newIndex == this.indexToPrint) {
2863         return;
2864     }
2865     this.indexToPrint = newIndex;
2866     var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2867     $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2868 }
2869 */
2870
2871 // showEmbedCode()
2872 //______________________________________________________________________________
2873 BookReader.prototype.showEmbedCode = function() {
2874     if (null != this.embedPopup) { // check if already showing
2875         return;
2876     }
2877     this.autoStop();
2878     this.embedPopup = document.createElement("div");
2879     $(this.embedPopup).css({
2880         position: 'absolute',
2881         top:      '20px',
2882         left:     ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2883         width:    '400px',
2884         padding:  "20px",
2885         border:   "3px double #999999",
2886         zIndex:   3,
2887         backgroundColor: "#fff"
2888     }).appendTo('#BookReader');
2889
2890     htmlStr =  '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2891     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>';
2892     htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2893     htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';    
2894
2895     this.embedPopup.innerHTML = htmlStr;
2896     $(this.embedPopup).find('input').bind('click', function() {
2897         this.select();
2898     })
2899 }
2900
2901 // autoToggle()
2902 //______________________________________________________________________________
2903 BookReader.prototype.autoToggle = function() {
2904
2905     var bComingFrom1up = false;
2906     if (2 != this.mode) {
2907         bComingFrom1up = true;
2908         this.switchMode(2);
2909     }
2910     
2911     // Change to autofit if book is too large
2912     if (this.reduce < this.twoPageGetAutofitReduce()) {
2913         this.zoom2up(0);
2914     }
2915
2916     var self = this;
2917     if (null == this.autoTimer) {
2918         this.flipSpeed = 2000;
2919         
2920         // $$$ Draw events currently cause layout problems when they occur during animation.
2921         //     There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2922         //     we workaround for now by not triggering immediate animation in that case.
2923         //     See https://bugs.launchpad.net/gnubook/+bug/328327
2924         if (('rl' == this.pageProgression) && bComingFrom1up) {
2925             // don't flip immediately -- wait until timer fires
2926         } else {
2927             // flip immediately
2928             this.flipFwdToIndex();        
2929         }
2930
2931         $('#BRtoolbar .play').hide();
2932         $('#BRtoolbar .pause').show();
2933         this.autoTimer=setInterval(function(){
2934             if (self.animating) {return;}
2935             
2936             if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2937                 self.flipBackToIndex(1); // $$$ really what we want?
2938             } else {            
2939                 self.flipFwdToIndex();
2940             }
2941         },5000);
2942     } else {
2943         this.autoStop();
2944     }
2945 }
2946
2947 // autoStop()
2948 //______________________________________________________________________________
2949 // Stop autoplay mode, allowing animations to finish
2950 BookReader.prototype.autoStop = function() {
2951     if (null != this.autoTimer) {
2952         clearInterval(this.autoTimer);
2953         this.flipSpeed = 'fast';
2954         $('#BRtoolbar .pause').hide();
2955         $('#BRtoolbar .play').show();
2956         this.autoTimer = null;
2957     }
2958 }
2959
2960 // stopFlipAnimations
2961 //______________________________________________________________________________
2962 // Immediately stop flip animations.  Callbacks are triggered.
2963 BookReader.prototype.stopFlipAnimations = function() {
2964
2965     this.autoStop(); // Clear timers
2966
2967     // Stop animation, clear queue, trigger callbacks
2968     if (this.leafEdgeTmp) {
2969         $(this.leafEdgeTmp).stop(false, true);
2970     }
2971     jQuery.each(this.prefetchedImgs, function() {
2972         $(this).stop(false, true);
2973         });
2974
2975     // And again since animations also queued in callbacks
2976     if (this.leafEdgeTmp) {
2977         $(this.leafEdgeTmp).stop(false, true);
2978     }
2979     jQuery.each(this.prefetchedImgs, function() {
2980         $(this).stop(false, true);
2981         });
2982    
2983 }
2984
2985 // keyboardNavigationIsDisabled(event)
2986 //   - returns true if keyboard navigation should be disabled for the event
2987 //______________________________________________________________________________
2988 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2989     if (event.target.tagName == "INPUT") {
2990         return true;
2991     }   
2992     return false;
2993 }
2994
2995 // gutterOffsetForIndex
2996 //______________________________________________________________________________
2997 //
2998 // Returns the gutter offset for the spread containing the given index.
2999 // This function supports RTL
3000 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3001
3002     // To find the offset of the gutter from the middle we calculate our percentage distance
3003     // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3004     var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3005     
3006     // But then again for RTL it's the opposite
3007     if ('rl' == this.pageProgression) {
3008         offset = -offset;
3009     }
3010     
3011     return offset;
3012 }
3013
3014 // leafEdgeWidth
3015 //______________________________________________________________________________
3016 // Returns the width of the leaf edge div for the page with index given
3017 BookReader.prototype.leafEdgeWidth = function(pindex) {
3018     // $$$ could there be single pixel rounding errors for L vs R?
3019     if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3020         return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3021     } else {
3022         return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3023     }
3024 }
3025
3026 // jumpIndexForLeftEdgePageX
3027 //______________________________________________________________________________
3028 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3029 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3030     if ('rl' != this.pageProgression) {
3031         // LTR - flipping backward
3032         var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3033
3034         // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570        
3035         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3036         return jumpIndex;
3037
3038     } else {
3039         var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3040         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3041         return jumpIndex;
3042     }
3043 }
3044
3045 // jumpIndexForRightEdgePageX
3046 //______________________________________________________________________________
3047 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3048 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3049     if ('rl' != this.pageProgression) {
3050         // LTR
3051         var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3052         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3053         return jumpIndex;
3054     } else {
3055         var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3056         jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3057         return jumpIndex;
3058     }
3059 }
3060
3061 BookReader.prototype.initToolbar = function(mode, ui) {
3062
3063     $("#BookReader").append("<div id='BRtoolbar'>"
3064         + "<span id='BRtoolbarbuttons' style='float: right'>"
3065         +   "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3066         +   "<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>"
3067         +   "<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>"
3068         +   "<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>"
3069         +   "<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>"
3070         +   "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3071         + "</span>"
3072         
3073         + "<span>"
3074         +   "<a class='BRicon logo rollover' href='" + this.logoURL + "'>&nbsp;</a>"
3075         +   " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>" 
3076         +   "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3077         +   " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3078         +   " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3079         +   " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3080         +   " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3081         + "</span>"
3082         
3083         + "<span id='#BRbooktitle'>"
3084         +   "&nbsp;&nbsp;<a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3085         + "</span>"
3086         + "</div>");
3087     
3088     this.updateToolbarZoom(this.reduce); // Pretty format
3089         
3090     if (ui == "embed" || ui == "touch") {
3091         $("#BookReader a.logo").attr("target","_blank");
3092     }
3093
3094     // $$$ turn this into a member variable
3095     var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3096     
3097     // We build in mode 2
3098     jToolbar.append();
3099
3100     this.bindToolbarNavHandlers(jToolbar);
3101     
3102     // Setup tooltips -- later we could load these from a file for i18n
3103     var titles = { '.logo': 'Go to Archive.org',
3104                    '.zoom_in': 'Zoom in',
3105                    '.zoom_out': 'Zoom out',
3106                    '.one_page_mode': 'One-page view',
3107                    '.two_page_mode': 'Two-page view',
3108                    '.thumbnail_mode': 'Thumbnail view',
3109                    '.print': 'Print this page',
3110                    '.embed': 'Embed bookreader',
3111                    '.book_left': 'Flip left',
3112                    '.book_right': 'Flip right',
3113                    '.book_up': 'Page up',
3114                    '.book_down': 'Page down',
3115                    '.play': 'Play',
3116                    '.pause': 'Pause',
3117                    '.book_top': 'First page',
3118                    '.book_bottom': 'Last page'
3119                   };
3120     if ('rl' == this.pageProgression) {
3121         titles['.book_leftmost'] = 'Last page';
3122         titles['.book_rightmost'] = 'First page';
3123     } else { // LTR
3124         titles['.book_leftmost'] = 'First page';
3125         titles['.book_rightmost'] = 'Last page';
3126     }
3127                   
3128     for (var icon in titles) {
3129         jToolbar.find(icon).attr('title', titles[icon]);
3130     }
3131     
3132     // Hide mode buttons and autoplay if 2up is not available
3133     // $$$ if we end up with more than two modes we should show the applicable buttons
3134     if ( !this.canSwitchToMode(this.constMode2up) ) {
3135         jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3136     }
3137
3138     // Switch to requested mode -- binds other click handlers
3139     this.switchToolbarMode(mode);
3140     
3141 }
3142
3143
3144 // switchToolbarMode
3145 //______________________________________________________________________________
3146 // Update the toolbar for the given mode (changes navigation buttons)
3147 // $$$ we should soon split the toolbar out into its own module
3148 BookReader.prototype.switchToolbarMode = function(mode) { 
3149     if (1 == mode) {
3150         // 1-up
3151         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3152         $('#BRtoolbar .BRtoolbarmode2').hide();
3153         $('#BRtoolbar .BRtoolbarmode3').hide();
3154         $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3155     } else if (2 == mode) {
3156         // 2-up
3157         $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3158         $('#BRtoolbar .BRtoolbarmode1').hide();
3159         $('#BRtoolbar .BRtoolbarmode3').hide();
3160         $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3161     } else {
3162         // 3-up    
3163         $('#BRtoolbar .BRtoolbarzoom').hide();
3164         $('#BRtoolbar .BRtoolbarmode2').hide();
3165         $('#BRtoolbar .BRtoolbarmode1').hide();
3166         $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3167     }
3168 }
3169
3170 // bindToolbarNavHandlers
3171 //______________________________________________________________________________
3172 // Binds the toolbar handlers
3173 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3174
3175     var self = this; // closure
3176
3177     jToolbar.find('.book_left').bind('click', function(e) {
3178         self.left();
3179         return false;
3180     });
3181          
3182     jToolbar.find('.book_right').bind('click', function(e) {
3183         self.right();
3184         return false;
3185     });
3186         
3187     jToolbar.find('.book_up').bind('click', function(e) {
3188         if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3189             self.scrollUp();
3190         } else {
3191             self.prev();
3192         }
3193         return false;
3194     });        
3195         
3196     jToolbar.find('.book_down').bind('click', function(e) {
3197         if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3198             self.scrollDown();
3199         } else {
3200             self.next();
3201         }
3202         return false;
3203     });
3204
3205     jToolbar.find('.print').bind('click', function(e) {
3206         self.printPage();
3207         return false;
3208     });
3209         
3210     jToolbar.find('.embed').bind('click', function(e) {
3211         self.showEmbedCode();
3212         return false;
3213     });
3214
3215     jToolbar.find('.play').bind('click', function(e) {
3216         self.autoToggle();
3217         return false;
3218     });
3219
3220     jToolbar.find('.pause').bind('click', function(e) {
3221         self.autoToggle();
3222         return false;
3223     });
3224     
3225     jToolbar.find('.book_top').bind('click', function(e) {
3226         self.first();
3227         return false;
3228     });
3229
3230     jToolbar.find('.book_bottom').bind('click', function(e) {
3231         self.last();
3232         return false;
3233     });
3234     
3235     jToolbar.find('.book_leftmost').bind('click', function(e) {
3236         self.leftmost();
3237         return false;
3238     });
3239   
3240     jToolbar.find('.book_rightmost').bind('click', function(e) {
3241         self.rightmost();
3242         return false;
3243     });
3244 }
3245
3246 // updateToolbarZoom(reduce)
3247 //______________________________________________________________________________
3248 // Update the displayed zoom factor based on reduction factor
3249 BookReader.prototype.updateToolbarZoom = function(reduce) {
3250     var value;
3251     if (this.constMode2up == this.mode && this.twoPage.autofit) {
3252         value = 'Auto';
3253     } else {
3254         value = (100 / reduce).toFixed(2);
3255         // Strip trailing zeroes and decimal if all zeroes
3256         value = value.replace(/0+$/,'');
3257         value = value.replace(/\.$/,'');
3258         value += '%';
3259     }
3260     $('#BRzoom').text(value);
3261 }
3262
3263 // firstDisplayableIndex
3264 //______________________________________________________________________________
3265 // Returns the index of the first visible page, dependent on the mode.
3266 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3267 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3268 BookReader.prototype.firstDisplayableIndex = function() {
3269     if (this.mode != this.constMode2up) {
3270         return 0;
3271     }
3272     
3273     if ('rl' != this.pageProgression) {
3274         // LTR
3275         if (this.getPageSide(0) == 'L') {
3276             return 0;
3277         } else {
3278             return -1;
3279         }
3280     } else {
3281         // RTL
3282         if (this.getPageSide(0) == 'R') {
3283             return 0;
3284         } else {
3285             return -1;
3286         }
3287     }
3288 }
3289
3290 // lastDisplayableIndex
3291 //______________________________________________________________________________
3292 // Returns the index of the last visible page, dependent on the mode.
3293 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3294 // this function when we can as pa  rt of https://bugs.launchpad.net/gnubook/+bug/296788
3295 BookReader.prototype.lastDisplayableIndex = function() {
3296
3297     var lastIndex = this.numLeafs - 1;
3298     
3299     if (this.mode != this.constMode2up) {
3300         return lastIndex;
3301     }
3302
3303     if ('rl' != this.pageProgression) {
3304         // LTR
3305         if (this.getPageSide(lastIndex) == 'R') {
3306             return lastIndex;
3307         } else {
3308             return lastIndex + 1;
3309         }
3310     } else {
3311         // RTL
3312         if (this.getPageSide(lastIndex) == 'L') {
3313             return lastIndex;
3314         } else {
3315             return lastIndex + 1;
3316         }
3317     }
3318 }
3319
3320 // shortTitle(maximumCharacters)
3321 //________
3322 // Returns a shortened version of the title with the maximum number of characters
3323 BookReader.prototype.shortTitle = function(maximumCharacters) {
3324     if (this.bookTitle.length < maximumCharacters) {
3325         return this.bookTitle;
3326     }
3327     
3328     var title = this.bookTitle.substr(0, maximumCharacters - 3);
3329     title += '...';
3330     return title;
3331 }
3332
3333 // Parameter related functions
3334
3335 // updateFromParams(params)
3336 //________
3337 // Update ourselves from the params object.
3338 //
3339 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3340 BookReader.prototype.updateFromParams = function(params) {
3341     if ('undefined' != typeof(params.mode)) {
3342         this.switchMode(params.mode);
3343     }
3344
3345     // process /search
3346     if ('undefined' != typeof(params.searchTerm)) {
3347         if (this.searchTerm != params.searchTerm) {
3348             this.search(params.searchTerm);
3349         }
3350     }
3351     
3352     // $$$ process /zoom
3353     
3354     // We only respect page if index is not set
3355     if ('undefined' != typeof(params.index)) {
3356         if (params.index != this.currentIndex()) {
3357             this.jumpToIndex(params.index);
3358         }
3359     } else if ('undefined' != typeof(params.page)) {
3360         // $$$ this assumes page numbers are unique
3361         if (params.page != this.getPageNum(this.currentIndex())) {
3362             this.jumpToPage(params.page);
3363         }
3364     }
3365     
3366     // $$$ process /region
3367     // $$$ process /highlight
3368 }
3369
3370 // paramsFromFragment(urlFragment)
3371 //________
3372 // Returns a object with configuration parametes from a URL fragment.
3373 //
3374 // E.g paramsFromFragment(window.location.hash)
3375 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3376     // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3377
3378     var params = {};
3379     
3380     // For convenience we allow an initial # character (as from window.location.hash)
3381     // but don't require it
3382     if (urlFragment.substr(0,1) == '#') {
3383         urlFragment = urlFragment.substr(1);
3384     }
3385     
3386     // Simple #nn syntax
3387     var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3388     if ( !isNaN(oldStyleLeafNum) ) {
3389         params.index = oldStyleLeafNum;
3390         
3391         // Done processing if using old-style syntax
3392         return params;
3393     }
3394     
3395     // Split into key-value pairs
3396     var urlArray = urlFragment.split('/');
3397     var urlHash = {};
3398     for (var i = 0; i < urlArray.length; i += 2) {
3399         urlHash[urlArray[i]] = urlArray[i+1];
3400     }
3401     
3402     // Mode
3403     if ('1up' == urlHash['mode']) {
3404         params.mode = this.constMode1up;
3405     } else if ('2up' == urlHash['mode']) {
3406         params.mode = this.constMode2up;
3407     } else if ('thumb' == urlHash['mode']) {
3408         params.mode = this.constModeThumb;
3409     }
3410     
3411     // Index and page
3412     if ('undefined' != typeof(urlHash['page'])) {
3413         // page was set -- may not be int
3414         params.page = urlHash['page'];
3415     }
3416     
3417     // $$$ process /region
3418     // $$$ process /search
3419     
3420     if (urlHash['search'] != undefined) {
3421         params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3422     }
3423     
3424     // $$$ process /highlight
3425         
3426     return params;
3427 }
3428
3429 // paramsFromCurrent()
3430 //________
3431 // Create a params object from the current parameters.
3432 BookReader.prototype.paramsFromCurrent = function() {
3433
3434     var params = {};
3435     
3436     var index = this.currentIndex();
3437     var pageNum = this.getPageNum(index);
3438     if ((pageNum === 0) || pageNum) {
3439         params.page = pageNum;
3440     }
3441     
3442     params.index = index;
3443     params.mode = this.mode;
3444     
3445     // $$$ highlight
3446     // $$$ region
3447
3448     // search    
3449     if (this.searchHighlightVisible()) {
3450         params.searchTerm = this.searchTerm;
3451     }
3452     
3453     return params;
3454 }
3455
3456 // fragmentFromParams(params)
3457 //________
3458 // Create a fragment string from the params object.
3459 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3460 BookReader.prototype.fragmentFromParams = function(params) {
3461     var separator = '/';
3462
3463     var fragments = [];
3464     
3465     if ('undefined' != typeof(params.page)) {
3466         fragments.push('page', params.page);
3467     } else {
3468         // Don't have page numbering -- use index instead
3469         fragments.push('page', 'n' + params.index);
3470     }
3471     
3472     // $$$ highlight
3473     // $$$ region
3474     
3475     // mode
3476     if ('undefined' != typeof(params.mode)) {    
3477         if (params.mode == this.constMode1up) {
3478             fragments.push('mode', '1up');
3479         } else if (params.mode == this.constMode2up) {
3480             fragments.push('mode', '2up');
3481         } else if (params.mode == this.constModeThumb) {
3482             fragments.push('mode', 'thumb');
3483         } else {
3484             throw 'fragmentFromParams called with unknown mode ' + params.mode;
3485         }
3486     }
3487     
3488     // search
3489     if (params.searchTerm) {
3490         fragments.push('search', params.searchTerm);
3491     }
3492     
3493     return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3494 }
3495
3496 // getPageIndex(pageNum)
3497 //________
3498 // Returns the *highest* index the given page number, or undefined
3499 BookReader.prototype.getPageIndex = function(pageNum) {
3500     var pageIndices = this.getPageIndices(pageNum);
3501     
3502     if (pageIndices.length > 0) {
3503         return pageIndices[pageIndices.length - 1];
3504     }
3505
3506     return undefined;
3507 }
3508
3509 // getPageIndices(pageNum)
3510 //________
3511 // Returns an array (possibly empty) of the indices with the given page number
3512 BookReader.prototype.getPageIndices = function(pageNum) {
3513     var indices = [];
3514
3515     // Check for special "nXX" page number
3516     if (pageNum.slice(0,1) == 'n') {
3517         try {
3518             var pageIntStr = pageNum.slice(1, pageNum.length);
3519             var pageIndex = parseInt(pageIntStr);
3520             indices.push(pageIndex);
3521             return indices;
3522         } catch(err) {
3523             // Do nothing... will run through page names and see if one matches
3524         }
3525     }
3526
3527     var i;
3528     for (i=0; i<this.numLeafs; i++) {
3529         if (this.getPageNum(i) == pageNum) {
3530             indices.push(i);
3531         }
3532     }
3533     
3534     return indices;
3535 }
3536
3537 // getPageName(index)
3538 //________
3539 // Returns the name of the page as it should be displayed in the user interface
3540 BookReader.prototype.getPageName = function(index) {
3541     return 'Page ' + this.getPageNum(index);
3542 }
3543
3544 // updateLocationHash
3545 //________
3546 // Update the location hash from the current parameters.  Call this instead of manually
3547 // using window.location.replace
3548 BookReader.prototype.updateLocationHash = function() {
3549     var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3550     window.location.replace(newHash);
3551     
3552     // This is the variable checked in the timer.  Only user-generated changes
3553     // to the URL will trigger the event.
3554     this.oldLocationHash = newHash;
3555 }
3556
3557 // startLocationPolling
3558 //________
3559 // Starts polling of window.location to see hash fragment changes
3560 BookReader.prototype.startLocationPolling = function() {
3561     var self = this; // remember who I am
3562     self.oldLocationHash = window.location.hash;
3563     
3564     if (this.locationPollId) {
3565         clearInterval(this.locationPollID);
3566         this.locationPollId = null;
3567     }
3568     
3569     this.locationPollId = setInterval(function() {
3570         var newHash = window.location.hash;
3571         if (newHash != self.oldLocationHash) {
3572             if (newHash != self.oldUserHash) { // Only process new user hash once
3573                 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3574                 
3575                 // Queue change if animating
3576                 if (self.animating) {
3577                     self.autoStop();
3578                     self.animationFinishedCallback = function() {
3579                         self.updateFromParams(self.paramsFromFragment(newHash));
3580                     }                        
3581                 } else { // update immediately
3582                     self.updateFromParams(self.paramsFromFragment(newHash));
3583                 }
3584                 self.oldUserHash = newHash;
3585             }
3586         }
3587     }, 500);
3588 }
3589
3590 // canSwitchToMode
3591 //________
3592 // Returns true if we can switch to the requested mode
3593 BookReader.prototype.canSwitchToMode = function(mode) {
3594     if (mode == this.constMode2up) {
3595         // check there are enough pages to display
3596         // $$$ this is a workaround for the mis-feature that we can't display
3597         //     short books in 2up mode
3598         if (this.numLeafs < 6) {
3599             return false;
3600         }
3601     }
3602     
3603     return true;
3604 }
3605
3606 // searchHighlightVisible
3607 //________
3608 // Returns true if a search highlight is currently being displayed
3609 BookReader.prototype.searchHighlightVisible = function() {
3610     if (this.constMode2up == this.mode) {
3611         if (this.searchResults[this.twoPage.currentIndexL]
3612                 || this.searchResults[this.twoPage.currentIndexR]) {
3613             return true;
3614         }
3615     } else { // 1up
3616         if (this.searchResults[this.currentIndex()]) {
3617             return true;
3618         }
3619     }
3620     return false;
3621 }
3622
3623 // getPageBackgroundColor
3624 //--------
3625 // Returns a CSS property string for the background color for the given page
3626 // $$$ turn into regular CSS?
3627 BookReader.prototype.getPageBackgroundColor = function(index) {
3628     if (index >= 0 && index < this.numLeafs) {
3629         // normal page
3630         return this.pageDefaultBackgroundColor;
3631     }
3632     
3633     return '';
3634 }
3635
3636 // _getPageWidth
3637 //--------
3638 // Returns the page width for the given index, or first or last page if out of range
3639 BookReader.prototype._getPageWidth = function(index) {
3640     // Synthesize a page width for pages not actually present in book.
3641     // May or may not be the best approach.
3642     // If index is out of range we return the width of first or last page
3643     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3644     return this.getPageWidth(index);
3645 }
3646
3647 // _getPageHeight
3648 //--------
3649 // Returns the page height for the given index, or first or last page if out of range
3650 BookReader.prototype._getPageHeight= function(index) {
3651     index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3652     return this.getPageHeight(index);
3653 }
3654
3655 // _getPageURI
3656 //--------
3657 // Returns the page URI or transparent image if out of range
3658 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3659     if (index < 0 || index >= this.numLeafs) { // Synthesize page
3660         return this.imagesBaseURL + "/transparent.png";
3661     }
3662     
3663     if ('undefined' == typeof(reduce)) {
3664         // reduce not passed in
3665         // $$$ this probably won't work for thumbnail mode
3666         var ratio = this.getPageHeight(index) / this.twoPage.height;
3667         var scale;
3668         // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3669         if (ratio < 2) {
3670             scale = 1;
3671         } else if (ratio < 4) {
3672             scale = 2;
3673         } else if (ratio < 8) {
3674             scale = 4;
3675         } else if (ratio < 16) {
3676             scale = 8;
3677         } else  if (ratio < 32) {
3678             scale = 16;
3679         } else {
3680             scale = 32;
3681         }
3682         reduce = scale;
3683     }
3684     
3685     return this.getPageURI(index, reduce, rotate);
3686 }
3687
3688 // Library functions
3689 BookReader.util = {
3690     disableSelect: function(jObject) {        
3691         // Bind mouse handlers
3692         // Disable mouse click to avoid selected/highlighted page images - bug 354239
3693         jObject.bind('mousedown', function(e) {
3694             // $$$ check here for right-click and don't disable.  Also use jQuery style
3695             //     for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3696             return false;
3697         });
3698         // Special hack for IE7
3699         jObject[0].onselectstart = function(e) { return false; };
3700     },
3701     
3702     clamp: function(value, min, max) {
3703         return Math.min(Math.max(value, min), max);
3704     },
3705     
3706     notInArray: function(value, array) {
3707         // inArray returns -1 or undefined if value not in array
3708         return ! (jQuery.inArray(value, array) >= 0);
3709     },
3710
3711     getIFrameDocument: function(iframe) {
3712         // Adapted from http://xkr.us/articles/dom/iframe-document/
3713         var outer = (iframe.contentWindow || iframe.contentDocument);
3714         return (outer.document || outer);
3715     },
3716     
3717     decodeURIComponentPlus: function(value) {
3718         // Decodes a URI component and converts '+' to ' '
3719         return decodeURIComponent(value).replace(/\+/g, ' ');
3720     },
3721     
3722     encodeURIComponentPlus: function(value) {
3723         // Encodes a URI component and converts ' ' to '+'
3724         return encodeURIComponent(value).replace(/%20/g, '+');
3725     }
3726     // The final property here must NOT have a comma after it - IE7
3727 }