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