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