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