2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
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.
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.
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/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
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.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI 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=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 // $$$ provide finer grained zooming
87 this.reductionFactors = [ {reduce: 0.5, autofit: null},
88 {reduce: 1, autofit: null},
89 {reduce: 2, autofit: null},
90 {reduce: 4, autofit: null},
91 {reduce: 8, autofit: null},
92 {reduce: 16, autofit: null} ];
94 // Object to hold parameters related to 1up mode
96 autofit: 'height' // valid values are height, width, none
99 // Object to hold parameters related to 2up mode
101 coverInternalPadding: 10, // Width of cover
102 coverExternalPadding: 10, // Padding outside of cover
103 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
111 //______________________________________________________________________________
112 BookReader.prototype.init = function() {
114 var startIndex = undefined;
115 this.pageScale = this.reduce; // preserve current reduce
117 // Find start index and mode if set in location hash
118 var params = this.paramsFromFragment(window.location.hash);
120 if ('undefined' != typeof(params.index)) {
121 startIndex = params.index;
122 } else if ('undefined' != typeof(params.page)) {
123 startIndex = this.getPageIndex(params.page);
126 if ('undefined' == typeof(startIndex)) {
127 if ('undefined' != typeof(this.titleLeaf)) {
128 startIndex = this.leafNumToIndex(this.titleLeaf);
132 if ('undefined' == typeof(startIndex)) {
136 if ('undefined' != typeof(params.mode)) {
137 this.mode = params.mode;
140 // Set document title -- may have already been set in enclosing html for
141 // search engine visibility
142 document.title = this.shortTitle(50);
144 // Sanitize parameters
145 if ( !this.canSwitchToMode( this.mode ) ) {
146 this.mode = this.constMode1up;
149 $("#BookReader").empty();
151 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
152 $("#BookReader").append("<div id='BRcontainer'></div>");
153 $("#BRcontainer").append("<div id='BRpageview'></div>");
155 $("#BRcontainer").bind('scroll', this, function(e) {
159 this.setupKeyListeners();
160 this.startLocationPolling();
162 $(window).bind('resize', this, function(e) {
163 //console.log('resize!');
164 if (1 == e.data.mode) {
165 //console.log('centering 1page view');
166 if (e.data.autofit) {
167 e.data.resizePageView();
169 e.data.centerPageView();
170 $('#BRpageview').empty()
171 e.data.displayedIndices = [];
172 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
174 } else if (3 == e.data.mode){
175 e.data.prepareThumbnailView();
177 //console.log('drawing 2 page view');
179 // We only need to prepare again in autofit (size of spread changes)
180 if (e.data.twoPage.autofit) {
181 e.data.prepareTwoPageView();
183 // Re-center if the scrollbars have disappeared
184 var center = e.data.twoPageGetViewCenter();
185 var doRecenter = false;
186 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
187 center.percentageX = 0.5;
190 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
191 center.percentageY = 0.5;
195 e.data.twoPageCenterView(center.percentageX, center.percentageY);
201 $('.BRpagediv1up').bind('mousedown', this, function(e) {
202 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
203 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
207 // $$$ refactor this so it's enough to set the first index and call preparePageView
208 // (get rid of mode-specific logic at this point)
209 if (1 == this.mode) {
210 this.firstIndex = startIndex;
211 this.prepareOnePageView();
212 this.jumpToIndex(startIndex);
213 } else if (3 == this.mode) {
214 this.firstIndex = startIndex;
215 this.prepareThumbnailView();
216 this.jumpToIndex(startIndex);
218 //this.resizePageView();
220 this.displayedIndices=[0];
221 this.firstIndex = startIndex;
222 this.displayedIndices = [this.firstIndex];
223 //console.log('titleLeaf: %d', this.titleLeaf);
224 //console.log('displayedIndices: %s', this.displayedIndices);
225 this.prepareTwoPageView();
228 // Enact other parts of initial params
229 this.updateFromParams(params);
232 BookReader.prototype.setupKeyListeners = function() {
245 // We use document here instead of window to avoid a bug in jQuery on IE7
246 $(document).keydown(function(e) {
248 // Keyboard navigation
249 if (!self.keyboardNavigationIsDisabled(e)) {
253 // In 1up mode page scrolling is handled by browser
254 if (2 == self.mode) {
261 if (2 == self.mode) {
275 if (2 == self.mode) {
281 if (2 == self.mode) {
292 //______________________________________________________________________________
293 BookReader.prototype.drawLeafs = function() {
294 if (1 == this.mode) {
295 this.drawLeafsOnePage();
296 } else if (3 == this.mode) {
297 this.drawLeafsThumbnail();
299 this.drawLeafsTwoPage();
304 // bindGestures(jElement)
305 //______________________________________________________________________________
306 BookReader.prototype.bindGestures = function(jElement) {
308 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
310 if (e.originalEvent.scale > 1.5) {
312 } else if (e.originalEvent.scale < 0.6) {
319 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
320 //console.log('setting handler');
321 //console.log(element.tagName);
323 $(element).unbind('tap').bind('tap', data, function(e) {
328 // drawLeafsOnePage()
329 //______________________________________________________________________________
330 BookReader.prototype.drawLeafsOnePage = function() {
331 //alert('drawing leafs!');
335 var scrollTop = $('#BRcontainer').attr('scrollTop');
336 var scrollBottom = scrollTop + $('#BRcontainer').height();
337 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
339 var indicesToDisplay = [];
344 for (i=0; i<this.numLeafs; i++) {
345 var height = parseInt(this._getPageHeight(i)/this.reduce);
347 leafBottom += height;
348 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
349 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
350 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
351 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
352 if (topInView | bottomInView | middleInView) {
353 //console.log('displayed: ' + this.displayedIndices);
354 //console.log('to display: ' + i);
355 indicesToDisplay.push(i);
357 leafTop += height +10;
361 var firstIndexToDraw = indicesToDisplay[0];
362 this.firstIndex = firstIndexToDraw;
364 // Update hash, but only if we're currently displaying a leaf
365 // Hack that fixes #365790
366 if (this.displayedIndices.length > 0) {
367 this.updateLocationHash();
370 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
372 indicesToDisplay.unshift(firstIndexToDraw);
375 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
376 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
377 indicesToDisplay.push(lastIndexToDraw+1);
382 for (i=0; i<firstIndexToDraw; i++) {
383 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
386 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
387 var viewWidth = $('#BRcontainer').attr('scrollWidth');
390 for (i=0; i<indicesToDisplay.length; i++) {
391 var index = indicesToDisplay[i];
392 var height = parseInt(this._getPageHeight(index)/this.reduce);
394 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
395 var width = parseInt(this._getPageWidth(index)/this.reduce);
396 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
397 var div = document.createElement("div");
398 div.className = 'BRpagediv1up';
399 div.id = 'pagediv'+index;
400 div.style.position = "absolute";
401 $(div).css('top', leafTop + 'px');
402 var left = (viewWidth-width)>>1;
403 if (left<0) left = 0;
404 $(div).css('left', left+'px');
405 $(div).css('width', width+'px');
406 $(div).css('height', height+'px');
407 //$(div).text('loading...');
409 $('#BRpageview').append(div);
411 var img = document.createElement("img");
412 img.src = this._getPageURI(index, this.reduce, 0);
413 $(img).css('width', width+'px');
414 $(img).css('height', height+'px');
418 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
421 leafTop += height +10;
425 for (i=0; i<this.displayedIndices.length; i++) {
426 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
427 var index = this.displayedIndices[i];
428 //console.log('Removing leaf ' + index);
429 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
430 $('#pagediv'+index).remove();
432 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
436 this.displayedIndices = indicesToDisplay.slice();
437 this.updateSearchHilites();
439 if (null != this.getPageNum(firstIndexToDraw)) {
440 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
442 $("#BRpagenum").val('');
445 this.updateToolbarZoom(this.reduce);
449 // drawLeafsThumbnail()
450 //______________________________________________________________________________
451 // If seekIndex is defined, the view will be drawn with that page visible (without any
452 // animated scrolling)
453 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
454 //alert('drawing leafs!');
457 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
459 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
473 // Will be set to top of requested seek index, if set
476 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
477 for (i=0; i<this.numLeafs; i++) {
478 leafWidth = this.thumbWidth;
479 if (rightPos + (leafWidth + this.padding) > viewWidth){
485 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
486 if (leafMap[currentRow].leafs===undefined) {
487 leafMap[currentRow].leafs = [];
488 leafMap[currentRow].height = 0;
489 leafMap[currentRow].top = 0;
491 leafMap[currentRow].leafs[leafIndex] = {};
492 leafMap[currentRow].leafs[leafIndex].num = i;
493 leafMap[currentRow].leafs[leafIndex].left = rightPos;
495 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
496 if (leafHeight > leafMap[currentRow].height) {
497 leafMap[currentRow].height = leafHeight;
499 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
500 rightPos += leafWidth + this.padding;
501 if (rightPos > maxRight) { maxRight = rightPos; }
504 if (i == seekIndex) {
505 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
509 // reset the bottom position based on thumbnails
510 $('#BRpageview').height(bottomPos);
512 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
514 // If seekTop is defined, seeking was requested and target found
515 if (typeof(seekTop) != 'undefined') {
516 $('#BRcontainer').scrollTop( seekTop );
519 var scrollTop = $('#BRcontainer').attr('scrollTop');
520 var scrollBottom = scrollTop + $('#BRcontainer').height();
524 var rowsToDisplay = [];
526 // Visible leafs with least/greatest index
527 var leastVisible = this.numLeafs - 1;
530 // Determine the thumbnails in view
531 for (i=0; i<leafMap.length; i++) {
532 leafBottom += this.padding + leafMap[i].height;
533 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
534 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
535 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
536 if (topInView | bottomInView | middleInView) {
537 //console.log('row to display: ' + j);
538 rowsToDisplay.push(i);
539 if (leafMap[i].leafs[0].num < leastVisible) {
540 leastVisible = leafMap[i].leafs[0].num;
542 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
543 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
546 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
547 leafTop = leafBottom;
550 // create a buffer of preloaded rows before and after the visible rows
551 var firstRow = rowsToDisplay[0];
552 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
553 for (i=1; i<this.thumbRowBuffer+1; i++) {
554 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
556 for (i=1; i<this.thumbRowBuffer+1; i++) {
557 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
560 // Create the thumbnail divs and images (lazy loaded)
569 for (i=0; i<rowsToDisplay.length; i++) {
570 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
571 row = rowsToDisplay[i];
573 for (j=0; j<leafMap[row].leafs.length; j++) {
575 leaf = leafMap[row].leafs[j].num;
577 leafWidth = this.thumbWidth;
578 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
579 leafTop = leafMap[row].top;
580 left = leafMap[row].leafs[index].left + pageViewBuffer;
581 if ('rl' == this.pageProgression){
582 left = viewWidth - leafWidth - left;
585 div = document.createElement("div");
586 div.id = 'pagediv'+leaf;
587 div.style.position = "absolute";
588 div.className = "BRpagedivthumb";
590 left += this.padding;
591 $(div).css('top', leafTop + 'px');
592 $(div).css('left', left+'px');
593 $(div).css('width', leafWidth+'px');
594 $(div).css('height', leafHeight+'px');
595 //$(div).text('loading...');
597 // link to page in single page mode
598 link = document.createElement("a");
599 $(link).data('leaf', leaf);
600 $(link).bind('tap', function(event) {
601 self.firstIndex = $(this).data('leaf');
602 self.switchMode(self.constMode1up);
603 event.preventDefault();
606 // $$$ we don't actually go to this URL (click is handled in handler above)
607 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
610 $('#BRpageview').append(div);
612 img = document.createElement("img");
613 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
615 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
616 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
617 .addClass('BRlazyload')
618 // Store the URL of the image that will replace this one
619 .data('srcURL', this._getPageURI(leaf, thumbReduce));
621 //console.log('displaying thumbnail: ' + leaf);
626 // Remove thumbnails that are not to be displayed
628 for (i=0; i<this.displayedRows.length; i++) {
629 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
630 row = this.displayedRows[i];
632 // $$$ Safari doesn't like the comprehension
633 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
634 //console.log('Removing row ' + row + ' ' + rowLeafs);
636 for (k=0; k<leafMap[row].leafs.length; k++) {
637 index = leafMap[row].leafs[k].num;
638 //console.log('Removing leaf ' + index);
639 $('#pagediv'+index).remove();
643 var mRow = this.displayedRows[i];
644 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
645 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
650 // Update which page is considered current to make sure a visible page is the current one
651 var currentIndex = this.currentIndex();
652 // console.log('current ' + currentIndex);
653 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
654 if (currentIndex < leastVisible) {
655 this.setCurrentIndex(leastVisible);
656 } else if (currentIndex > mostVisible) {
657 this.setCurrentIndex(mostVisible);
660 this.displayedRows = rowsToDisplay.slice();
662 // Update hash, but only if we're currently displaying a leaf
663 // Hack that fixes #365790
664 if (this.displayedRows.length > 0) {
665 this.updateLocationHash();
668 // remove previous highlights
669 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
671 // highlight current page
672 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
674 this.lazyLoadThumbnails();
676 // Update page number box. $$$ refactor to function
677 if (null !== this.getPageNum(this.currentIndex())) {
678 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
680 $("#BRpagenum").val('');
683 this.updateToolbarZoom(this.reduce);
686 BookReader.prototype.lazyLoadThumbnails = function() {
688 // console.log('lazy load');
690 // We check the complete property since load may not be fired if loading from the cache
691 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
693 var loading = $('.BRlazyloading').length;
694 var toLoad = this.thumbMaxLoading - loading;
696 // console.log(' ' + loading + ' thumbnails loading');
697 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
702 // $$$ TODO load those near top (but not beyond) page view first
703 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
704 self.lazyLoadImage(this);
709 BookReader.prototype.lazyLoadImage = function (dummyImage) {
710 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
712 var img = new Image();
716 .addClass('BRlazyloading')
717 .one('load', function() {
718 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
720 $(this).removeClass('BRlazyloading');
722 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
723 // we call the function after a slight delay. Also the img.complete property
724 // is not yet set in IE8 inside this onload handler
725 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
727 .one('error', function() {
728 // Remove class so we no longer count as loading
729 $(this).removeClass('BRlazyloading');
731 .attr( { width: $(dummyImage).width(),
732 height: $(dummyImage).height(),
733 src: $(dummyImage).data('srcURL')
736 // replace with the new img
737 $(dummyImage).before(img).remove();
739 img = null; // tidy up closure
743 // drawLeafsTwoPage()
744 //______________________________________________________________________________
745 BookReader.prototype.drawLeafsTwoPage = function() {
746 var scrollTop = $('#BRtwopageview').attr('scrollTop');
747 var scrollBottom = scrollTop + $('#BRtwopageview').height();
749 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
751 var indexL = this.twoPage.currentIndexL;
753 var heightL = this._getPageHeight(indexL);
754 var widthL = this._getPageWidth(indexL);
756 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
757 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
758 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
759 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
760 //console.log(leafEdgeWidthL);
762 var middle = this.twoPage.middle; // $$$ getter instead?
763 var top = this.twoPageTop();
764 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
766 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
767 this.twoPage.gutter = this.twoPageGutter();
769 this.prefetchImg(indexL);
770 $(this.prefetchedImgs[indexL]).css({
771 position: 'absolute',
772 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
775 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
776 width: this.twoPage.scaledWL + 'px',
777 borderRight: '1px solid black',
779 }).appendTo('#BRtwopageview');
781 var indexR = this.twoPage.currentIndexR;
782 var heightR = this._getPageHeight(indexR);
783 var widthR = this._getPageWidth(indexR);
785 // $$$ should use getwidth2up?
786 //var scaledWR = this.twoPage.height*widthR/heightR;
787 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
788 this.prefetchImg(indexR);
789 $(this.prefetchedImgs[indexR]).css({
790 position: 'absolute',
791 left: this.twoPage.gutter+'px',
794 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
795 width: this.twoPage.scaledWR + 'px',
796 borderLeft: '1px solid black',
798 }).appendTo('#BRtwopageview');
801 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
802 this.setMouseHandlers2UP();
803 this.twoPageSetCursor();
805 this.updatePageNumBox2UP();
806 this.updateToolbarZoom(this.reduce);
808 // this.twoPagePlaceFlipAreas(); // No longer used
812 // updatePageNumBox2UP
813 //______________________________________________________________________________
814 BookReader.prototype.updatePageNumBox2UP = function() {
815 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
816 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
818 $("#BRpagenum").val('');
820 this.updateLocationHash();
824 //______________________________________________________________________________
825 BookReader.prototype.loadLeafs = function() {
829 if (null == this.timer) {
830 this.timer=setTimeout(function(){self.drawLeafs()},250);
832 clearTimeout(this.timer);
833 this.timer=setTimeout(function(){self.drawLeafs()},250);
839 // Pass 1 to zoom in, anything else to zoom out
840 //______________________________________________________________________________
841 BookReader.prototype.zoom = function(direction) {
843 case this.constMode1up:
844 if (direction == 1) {
846 return this.zoom1up('in');
848 return this.zoom1up('out');
851 case this.constMode2up:
852 if (direction == 1) {
854 return this.zoom2up('in');
856 return this.zoom2up('out');
859 case this.constModeThumb:
860 // XXX update zoomThumb for named directions
861 return this.zoomThumb(direction);
867 //______________________________________________________________________________
868 BookReader.prototype.zoom1up = function(direction) {
870 if (2 == this.mode) { //can only zoom in 1-page mode
875 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
877 if (this.reduce == reduceFactor.reduce) {
878 // Already at this level
882 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
883 this.onePage.autofit = reduceFactor.autofit;
885 this.pageScale = this.reduce; // preserve current reduce
886 this.resizePageView();
888 $('#BRpageview').empty()
889 this.displayedIndices = [];
892 this.updateToolbarZoom(this.reduce);
894 // Recalculate search hilites
895 this.removeSearchHilites();
896 this.updateSearchHilites();
901 //______________________________________________________________________________
902 BookReader.prototype.resizePageView = function() {
904 // $$$ This code assumes 1up mode
905 // e.g. does not preserve position in thumbnail mode
906 // See http://bugs.launchpad.net/bookreader/+bug/552972
909 case this.constMode1up:
910 case this.constMode2up:
911 this.resizePageView1up();
913 case this.constModeThumb:
914 this.prepareThumbnailView( this.currentIndex() );
917 alert('Resize not implemented for this mode');
921 BookReader.prototype.resizePageView1up = function() {
924 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
925 var viewWidth = $('#BRcontainer').attr('clientWidth');
927 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
928 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
929 var oldPageViewHeight = $('#BRpageview').height();
930 var oldPageViewWidth = $('#BRpageview').width();
932 var oldCenterY = this.centerY1up();
933 var oldCenterX = this.centerX1up();
935 if (0 != oldPageViewHeight) {
936 var scrollRatio = oldCenterY / oldPageViewHeight;
941 // Recalculate 1up reduction factors
942 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
943 $('#BRcontainer').attr('clientHeight') );
944 // Update current reduce (if in autofit)
945 if (this.onePage.autofit) {
946 var reductionFactor = this.nextReduce(this.reduce, this.onePage.autofit, this.onePage.reductionFactors);
947 this.reduce = reductionFactor.reduce;
950 for (i=0; i<this.numLeafs; i++) {
951 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
952 var width = parseInt(this._getPageWidth(i)/this.reduce);
953 if (width>viewWidth) viewWidth=width;
955 $('#BRpageview').height(viewHeight);
956 $('#BRpageview').width(viewWidth);
958 var newCenterY = scrollRatio*viewHeight;
959 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
960 $('#BRcontainer').attr('scrollTop', newTop);
962 // We use clientWidth here to avoid miscalculating due to scroll bar
963 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
964 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
965 newLeft = Math.max(newLeft, 0);
966 $('#BRcontainer').attr('scrollLeft', newLeft);
967 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
969 //this.centerPageView();
972 this.removeSearchHilites();
973 this.updateSearchHilites();
978 //______________________________________________________________________________
979 // Returns the current offset of the viewport center in scaled document coordinates.
980 BookReader.prototype.centerX1up = function() {
982 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
983 centerX = $('#BRpageview').width();
985 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
987 centerX = Math.floor(centerX);
992 //______________________________________________________________________________
993 // Returns the current offset of the viewport center in scaled document coordinates.
994 BookReader.prototype.centerY1up = function() {
995 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
996 return Math.floor(centerY);
1000 //______________________________________________________________________________
1001 BookReader.prototype.centerPageView = function() {
1003 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1004 var clientWidth = $('#BRcontainer').attr('clientWidth');
1005 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1006 if (scrollWidth > clientWidth) {
1007 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1012 // zoom2up(direction)
1013 //______________________________________________________________________________
1014 BookReader.prototype.zoom2up = function(direction) {
1016 // Hard stop autoplay
1017 this.stopFlipAnimations();
1019 // Recalculate autofit factors
1020 this.twoPageCalculateReductionFactors();
1022 // Get new zoom state
1023 var reductionFactor = this.nextReduce(this.reduce, direction, this.twoPage.reductionFactors);
1024 if ((this.reduce == reductionFactor.reduce) && (this.twoPage.autofit == reductionFactor.autofit)) {
1028 this.twoPage.autofit = reductionFactor.autofit;
1029 this.reduce = reductionFactor.reduce;
1030 this.pageScale = this.reduce; // preserve current reduce
1032 // Preserve view center position
1033 var oldCenter = this.twoPageGetViewCenter();
1035 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1036 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1037 if (1 == direction) {
1038 for (var img in this.prefetchedImgs) {
1039 delete this.prefetchedImgs[img];
1043 // Prepare view with new center to minimize visual glitches
1044 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1047 BookReader.prototype.zoomThumb = function(direction) {
1048 var oldColumns = this.thumbColumns;
1049 switch (direction) {
1051 this.thumbColumns += 1;
1054 this.thumbColumns -= 1;
1059 if (this.thumbColumns < 2) {
1060 this.thumbColumns = 2;
1061 } else if (this.thumbColumns > 8) {
1062 this.thumbColumns = 8;
1065 if (this.thumbColumns != oldColumns) {
1066 this.prepareThumbnailView();
1070 // Returns the width per thumbnail to display the requested number of columns
1071 // Note: #BRpageview must already exist since its width is used to calculate the
1073 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1074 var padding = (thumbnailColumns + 1) * this.padding;
1075 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1076 return parseInt(width);
1079 // quantizeReduce(reduce)
1080 //______________________________________________________________________________
1081 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1082 BookReader.prototype.quantizeReduce = function(reduce, reductionFactors) {
1083 var quantized = reductionFactors[0].reduce;
1084 var distance = Math.abs(reduce - quantized);
1085 for (var i = 1; i < reductionFactors.length; i++) {
1086 newDistance = Math.abs(reduce - reductionFactors[i].reduce);
1087 if (newDistance < distance) {
1088 distance = newDistance;
1089 quantized = reductionFactors[i].reduce;
1096 // reductionFactors should be array of sorted reduction factors
1097 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1098 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1100 // XXX add 'closest', to replace quantize function
1102 if (direction == 'in') {
1103 var newReduceIndex = 0;
1105 for (var i = 1; i < reductionFactors.length; i++) {
1106 if (reductionFactors[i].reduce < currentReduce) {
1110 return reductionFactors[newReduceIndex];
1112 } else if (direction == 'out') { // zoom out
1113 var lastIndex = reductionFactors.length - 1;
1114 var newReduceIndex = lastIndex;
1116 for (var i = lastIndex; i >= 0; i--) {
1117 if (reductionFactors[i].reduce > currentReduce) {
1121 return reductionFactors[newReduceIndex];
1124 // Asked for specific autofit mode
1125 for (var i = 0; i < reductionFactors.length; i++) {
1126 if (reductionFactors[i].autofit == direction) {
1127 return reductionFactors[i];
1131 alert('Could not find reduction factor for direction ' + direction);
1132 return reductionFactors[0];
1136 BookReader.prototype._reduceSort = function(a, b) {
1137 return a.reduce - b.reduce;
1141 //______________________________________________________________________________
1142 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1143 BookReader.prototype.jumpToPage = function(pageNum) {
1145 var pageIndex = this.getPageIndex(pageNum);
1147 if ('undefined' != typeof(pageIndex)) {
1150 this.jumpToIndex(pageIndex);
1151 $('#BRcontainer').attr('scrollTop', leafTop);
1160 //______________________________________________________________________________
1161 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1163 if (this.constMode2up == this.mode) {
1166 // By checking against min/max we do nothing if requested index
1168 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1169 this.flipBackToIndex(index);
1170 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1171 this.flipFwdToIndex(index);
1174 } else if (this.constModeThumb == this.mode) {
1175 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1185 for (i=0; i<(index+1); i++) {
1186 leafWidth = this.thumbWidth;
1187 if (rightPos + (leafWidth + this.padding) > viewWidth){
1193 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1194 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1195 if (leafIndex==0) { leafTop = bottomPos; }
1196 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1197 rightPos += leafWidth + this.padding;
1200 this.firstIndex=index;
1201 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1204 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1212 for (i=0; i<index; i++) {
1213 h = parseInt(this._getPageHeight(i)/this.reduce);
1214 leafTop += h + this.padding;
1218 //console.log('pageY ' + pageY);
1219 var offset = parseInt( (pageY) / this.reduce);
1220 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1221 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1224 // Show page just a little below the top
1225 leafTop -= this.padding / 2;
1229 var offset = parseInt( (pageX) / this.reduce);
1230 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1233 // Preserve left position
1234 leafLeft = $('#BRcontainer').scrollLeft();
1237 //$('#BRcontainer').attr('scrollTop', leafTop);
1238 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1244 //______________________________________________________________________________
1245 BookReader.prototype.switchMode = function(mode) {
1247 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1249 if (mode == this.mode) {
1253 if (!this.canSwitchToMode(mode)) {
1258 this.removeSearchHilites();
1261 this.switchToolbarMode(mode);
1263 // reinstate scale if moving from thumbnail view
1264 if (this.pageScale != this.reduce) {
1265 this.reduce = this.pageScale;
1268 // $$$ TODO preserve center of view when switching between mode
1269 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1271 // XXX maybe better to preserve zoom in each mode
1273 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'), $('#BRcontainer').attr('clientHeight'));
1274 this.reduce = this.quantizeReduce(this.reduce, this.onePage.reductionFactors);
1275 this.prepareOnePageView();
1276 } else if (3 == mode) {
1277 this.reduce = this.quantizeReduce(this.reduce, this.reductionFactors);
1278 this.prepareThumbnailView();
1280 // $$$ why don't we save autofit?
1281 this.twoPage.autofit = null; // Take zoom level from other mode
1282 this.twoPageCalculateReductionFactors();
1283 this.reduce = this.quantizeReduce(this.reduce, this.twoPage.reductionFactors);
1284 this.prepareTwoPageView();
1285 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1290 //prepareOnePageView()
1291 //______________________________________________________________________________
1292 BookReader.prototype.prepareOnePageView = function() {
1294 // var startLeaf = this.displayedIndices[0];
1295 var startLeaf = this.currentIndex();
1297 $('#BRcontainer').empty();
1298 $('#BRcontainer').css({
1299 overflowY: 'scroll',
1303 $("#BRcontainer").append("<div id='BRpageview'></div>");
1305 // Attaches to first child - child must be present
1306 $('#BRcontainer').dragscrollable();
1307 this.bindGestures($('#BRcontainer'));
1309 // $$$ keep select enabled for now since disabling it breaks keyboard
1310 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1311 // BookReader.util.disableSelect($('#BRpageview'));
1313 this.resizePageView();
1315 this.jumpToIndex(startLeaf);
1316 this.displayedIndices = [];
1318 this.drawLeafsOnePage();
1321 //prepareThumbnailView()
1322 //______________________________________________________________________________
1323 BookReader.prototype.prepareThumbnailView = function() {
1325 $('#BRcontainer').empty();
1326 $('#BRcontainer').css({
1327 overflowY: 'scroll',
1331 $("#BRcontainer").append("<div id='BRpageview'></div>");
1333 $('#BRcontainer').dragscrollable();
1334 this.bindGestures($('#BRcontainer'));
1336 // $$$ keep select enabled for now since disabling it breaks keyboard
1337 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1338 // BookReader.util.disableSelect($('#BRpageview'));
1340 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1341 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1343 this.displayedRows = [];
1345 // Draw leafs with current index directly in view (no animating to the index)
1346 this.drawLeafsThumbnail( this.currentIndex() );
1350 // prepareTwoPageView()
1351 //______________________________________________________________________________
1352 // Some decisions about two page view:
1354 // Both pages will be displayed at the same height, even if they were different physical/scanned
1355 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1356 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1357 // aspect ratio to determine the height.
1359 // The two page view div is resized to keep the middle of the book in the middle of the div
1360 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1361 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1362 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1363 $('#BRcontainer').empty();
1364 $('#BRcontainer').css('overflow', 'auto');
1366 // We want to display two facing pages. We may be missing
1367 // one side of the spread because it is the first/last leaf,
1368 // foldouts, missing pages, etc
1370 //var targetLeaf = this.displayedIndices[0];
1371 var targetLeaf = this.firstIndex;
1373 if (targetLeaf < this.firstDisplayableIndex()) {
1374 targetLeaf = this.firstDisplayableIndex();
1377 if (targetLeaf > this.lastDisplayableIndex()) {
1378 targetLeaf = this.lastDisplayableIndex();
1381 //this.twoPage.currentIndexL = null;
1382 //this.twoPage.currentIndexR = null;
1383 //this.pruneUnusedImgs();
1385 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1386 this.twoPage.currentIndexL = currentSpreadIndices[0];
1387 this.twoPage.currentIndexR = currentSpreadIndices[1];
1388 this.firstIndex = this.twoPage.currentIndexL;
1390 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1392 this.pruneUnusedImgs();
1393 this.prefetch(); // Preload images or reload if scaling has changed
1395 //console.dir(this.twoPage);
1397 // Add the two page view
1398 // $$$ Can we get everything set up and then append?
1399 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1401 // Attaches to first child, so must come after we add the page view
1402 $('#BRcontainer').dragscrollable();
1403 this.bindGestures($('#BRcontainer'));
1405 // $$$ calculate first then set
1406 $('#BRtwopageview').css( {
1407 height: this.twoPage.totalHeight + 'px',
1408 width: this.twoPage.totalWidth + 'px',
1409 position: 'absolute'
1412 // If there will not be scrollbars (e.g. when zooming out) we center the book
1413 // since otherwise the book will be stuck off-center
1414 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1415 centerPercentageX = 0.5;
1417 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1418 centerPercentageY = 0.5;
1421 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1423 this.twoPage.coverDiv = document.createElement('div');
1424 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1425 width: this.twoPage.bookCoverDivWidth + 'px',
1426 height: this.twoPage.bookCoverDivHeight+'px',
1427 visibility: 'visible',
1428 position: 'absolute',
1429 left: this.twoPage.bookCoverDivLeft + 'px',
1430 top: this.twoPage.bookCoverDivTop+'px',
1431 }).appendTo('#BRtwopageview');
1433 this.leafEdgeR = document.createElement('div');
1434 this.leafEdgeR.className = 'BRleafEdgeR';
1435 $(this.leafEdgeR).css({
1436 width: this.twoPage.leafEdgeWidthR + 'px',
1437 height: this.twoPage.height-1 + 'px',
1438 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1439 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1440 }).appendTo('#BRtwopageview');
1442 this.leafEdgeL = document.createElement('div');
1443 this.leafEdgeL.className = 'BRleafEdgeL';
1444 $(this.leafEdgeL).css({
1445 width: this.twoPage.leafEdgeWidthL + 'px',
1446 height: this.twoPage.height-1 + 'px',
1447 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1448 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1449 }).appendTo('#BRtwopageview');
1451 div = document.createElement('div');
1452 $(div).attr('id', 'BRbookspine').css({
1453 width: this.twoPage.bookSpineDivWidth+'px',
1454 height: this.twoPage.bookSpineDivHeight+'px',
1455 left: this.twoPage.bookSpineDivLeft+'px',
1456 top: this.twoPage.bookSpineDivTop+'px'
1457 }).appendTo('#BRtwopageview');
1459 var self = this; // for closure
1461 /* Flip areas no longer used
1462 this.twoPage.leftFlipArea = document.createElement('div');
1463 this.twoPage.leftFlipArea.className = 'BRfliparea';
1464 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1466 width: this.twoPageFlipAreaWidth() + 'px',
1467 height: this.twoPageFlipAreaHeight() + 'px',
1468 position: 'absolute',
1469 left: this.twoPageLeftFlipAreaLeft() + 'px',
1470 top: this.twoPageFlipAreaTop() + 'px',
1473 }).bind('click', function(e) {
1475 }).bind('mousedown', function(e) {
1477 }).appendTo('#BRtwopageview');
1479 this.twoPage.rightFlipArea = document.createElement('div');
1480 this.twoPage.rightFlipArea.className = 'BRfliparea';
1481 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1483 width: this.twoPageFlipAreaWidth() + 'px',
1484 height: this.twoPageFlipAreaHeight() + 'px',
1485 position: 'absolute',
1486 left: this.twoPageRightFlipAreaLeft() + 'px',
1487 top: this.twoPageFlipAreaTop() + 'px',
1490 }).bind('click', function(e) {
1492 }).bind('mousedown', function(e) {
1494 }).appendTo('#BRtwopageview');
1497 this.prepareTwoPagePopUp();
1499 this.displayedIndices = [];
1501 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1502 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1504 this.drawLeafsTwoPage();
1505 this.updateToolbarZoom(this.reduce);
1509 this.removeSearchHilites();
1510 this.updateSearchHilites();
1514 // prepareTwoPagePopUp()
1516 // This function prepares the "View Page n" popup that shows while the mouse is
1517 // over the left/right "stack of sheets" edges. It also binds the mouse
1518 // events for these divs.
1519 //______________________________________________________________________________
1520 BookReader.prototype.prepareTwoPagePopUp = function() {
1522 this.twoPagePopUp = document.createElement('div');
1523 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1524 $(this.twoPagePopUp).css({
1526 }).appendTo('#BRcontainer');
1527 $(this.twoPagePopUp).hide();
1529 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1530 $(e.data.twoPagePopUp).show();
1533 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1534 $(e.data.twoPagePopUp).hide();
1537 $(this.leafEdgeL).bind('click', this, function(e) {
1539 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1540 e.data.jumpToIndex(jumpIndex);
1543 $(this.leafEdgeR).bind('click', this, function(e) {
1545 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1546 e.data.jumpToIndex(jumpIndex);
1549 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1551 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1552 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1554 // $$$ TODO: Make sure popup is positioned so that it is in view
1555 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1556 $(e.data.twoPagePopUp).css({
1557 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1558 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1562 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1564 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1565 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1567 // $$$ TODO: Make sure popup is positioned so that it is in view
1568 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1569 $(e.data.twoPagePopUp).css({
1570 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1571 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1576 // calculateSpreadSize()
1577 //______________________________________________________________________________
1578 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1579 // this.twoPage.currentIndexR
1580 // This function sets this.twoPage.height, twoPage.width
1582 BookReader.prototype.calculateSpreadSize = function() {
1584 var firstIndex = this.twoPage.currentIndexL;
1585 var secondIndex = this.twoPage.currentIndexR;
1586 //console.log('first page is ' + firstIndex);
1588 // Calculate page sizes and total leaf width
1590 if ( this.twoPage.autofit) {
1591 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1593 // set based on reduction factor
1594 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1597 // Both pages together
1598 this.twoPage.height = spreadSize.height;
1599 this.twoPage.width = spreadSize.width;
1602 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1603 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1606 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1607 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1608 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1612 // The width of the book cover div. The combined width of both pages, twice the width
1613 // of the book cover internal padding (2*10) and the page edges
1614 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1615 // The height of the book cover div
1616 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1619 // We calculate the total width and height for the div so that we can make the book
1621 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1622 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1623 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1624 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1625 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1626 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1628 // We want to minimize the unused space in two-up mode (maximize the amount of page
1629 // shown). We give width to the leaf edges and these widths change (though the sum
1630 // of the two remains constant) as we flip through the book. With the book
1631 // cover centered and fixed in the BRcontainer div the page images will meet
1632 // at the "gutter" which is generally offset from the center.
1633 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1634 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1636 // The left edge of the book cover moves depending on the width of the pages
1637 // $$$ change to getter
1638 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1639 // The top edge of the book cover stays a fixed distance from the top
1640 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1643 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1644 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1645 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1648 this.reduce = spreadSize.reduce; // $$$ really set this here?
1651 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1654 // We check which page is closest to a "normal" page and use that to set the height
1655 // for both pages. This means that foldouts and other odd size pages will be displayed
1656 // smaller than the nominal zoom amount.
1657 var canon5Dratio = 1.5;
1660 height: this._getPageHeight(firstIndex),
1661 width: this._getPageWidth(firstIndex)
1665 height: this._getPageHeight(secondIndex),
1666 width: this._getPageWidth(secondIndex)
1669 var firstIndexRatio = first.height / first.width;
1670 var secondIndexRatio = second.height / second.width;
1671 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1674 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1675 ratio = firstIndexRatio;
1676 //console.log('using firstIndexRatio ' + ratio);
1678 ratio = secondIndexRatio;
1679 //console.log('using secondIndexRatio ' + ratio);
1682 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1683 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1684 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1686 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1687 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1689 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1690 ideal.width -= 10; // $$$ fudge factor
1691 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1692 ideal.height -= 20; // fudge factor
1693 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1695 if (ideal.height/ratio <= ideal.width) {
1697 ideal.width = parseInt(ideal.height/ratio);
1700 ideal.height = parseInt(ideal.width*ratio);
1703 // $$$ check this logic with large spreads
1704 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1709 // getSpreadSizeFromReduce()
1710 //______________________________________________________________________________
1711 // Returns the spread size calculated from the reduction factor for the given pages
1712 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1713 var spreadSize = {};
1714 // $$$ Scale this based on reduce?
1715 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1716 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1717 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1719 // $$$ Possibly incorrect -- we should make height "dominant"
1720 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1721 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1722 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1723 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1724 spreadSize.reduce = reduce;
1729 // twoPageGetAutofitReduce()
1730 //______________________________________________________________________________
1731 // Returns the current ideal reduction factor
1732 BookReader.prototype.twoPageGetAutofitReduce = function() {
1733 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1734 return spreadSize.reduce;
1737 BookReader.prototype.onePageGetAutofitWidth = function() {
1738 var widthPadding = 20;
1739 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1742 BookReader.prototype.onePageGetAutofitHeight = function() {
1743 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - this.padding * 2); // make sure a little of adjacent pages show
1746 BookReader.prototype.getMedianPageSize = function() {
1747 if (this._medianPageSize) {
1748 return this._medianPageSize;
1751 // A little expensive but we just do it once
1754 for (var i = 0; i < this.numLeafs; i++) {
1755 widths.push(this.getPageWidth(i));
1756 heights.push(this.getPageHeight(i));
1762 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1763 return this._medianPageSize;
1766 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1767 // the autofit reduction factors.
1768 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1769 this.onePage.reductionFactors = this.reductionFactors.concat(
1771 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1772 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1774 this.onePage.reductionFactors.sort(this._reduceSort);
1777 BookReader.prototype.twoPageCalculateReductionFactors = function() {
1778 this.twoPage.reductionFactors = this.reductionFactors.concat(
1780 { reduce: this.getIdealSpreadSize( this.twoPage.currentIndexL, this.twoPage.currentIndexR ).reduce,
1783 this.twoPage.reductionFactors.sort(this._reduceSort);
1786 // twoPageSetCursor()
1787 //______________________________________________________________________________
1788 // Set the cursor for two page view
1789 BookReader.prototype.twoPageSetCursor = function() {
1790 // console.log('setting cursor');
1791 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1792 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1793 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1794 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1796 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1797 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1802 //______________________________________________________________________________
1803 // Returns the currently active index.
1804 BookReader.prototype.currentIndex = function() {
1805 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1806 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1807 return this.firstIndex; // $$$ TODO page in center of view would be better
1808 } else if (this.mode == this.constMode2up) {
1809 // Only allow indices that are actually present in book
1810 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1812 throw 'currentIndex called for unimplemented mode ' + this.mode;
1816 // setCurrentIndex(index)
1817 //______________________________________________________________________________
1818 // Sets the idea of current index without triggering other actions such as animation.
1819 // Compare to jumpToIndex which animates to that index
1820 BookReader.prototype.setCurrentIndex = function(index) {
1821 this.firstIndex = index;
1826 //______________________________________________________________________________
1827 // Flip the right page over onto the left
1828 BookReader.prototype.right = function() {
1829 if ('rl' != this.pageProgression) {
1839 //______________________________________________________________________________
1840 // Flip to the rightmost page
1841 BookReader.prototype.rightmost = function() {
1842 if ('rl' != this.pageProgression) {
1850 //______________________________________________________________________________
1851 // Flip the left page over onto the right.
1852 BookReader.prototype.left = function() {
1853 if ('rl' != this.pageProgression) {
1863 //______________________________________________________________________________
1864 // Flip to the leftmost page
1865 BookReader.prototype.leftmost = function() {
1866 if ('rl' != this.pageProgression) {
1874 //______________________________________________________________________________
1875 BookReader.prototype.next = function() {
1876 if (2 == this.mode) {
1878 this.flipFwdToIndex(null);
1880 if (this.firstIndex < this.lastDisplayableIndex()) {
1881 this.jumpToIndex(this.firstIndex+1);
1887 //______________________________________________________________________________
1888 BookReader.prototype.prev = function() {
1889 if (2 == this.mode) {
1891 this.flipBackToIndex(null);
1893 if (this.firstIndex >= 1) {
1894 this.jumpToIndex(this.firstIndex-1);
1899 BookReader.prototype.first = function() {
1900 this.jumpToIndex(this.firstDisplayableIndex());
1903 BookReader.prototype.last = function() {
1904 this.jumpToIndex(this.lastDisplayableIndex());
1908 //______________________________________________________________________________
1909 // Scrolls down one screen view
1910 BookReader.prototype.scrollDown = function() {
1911 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1912 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1913 // Whole pages are visible, scroll whole page only
1917 $('#BRcontainer').animate(
1918 { scrollTop: '+=' + this._scrollAmount() + 'px'},
1919 400, 'easeInOutExpo'
1928 //______________________________________________________________________________
1929 // Scrolls up one screen view
1930 BookReader.prototype.scrollUp = function() {
1931 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1932 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1933 // Whole pages are visible, scroll whole page only
1937 $('#BRcontainer').animate(
1938 { scrollTop: '-=' + this._scrollAmount() + 'px'},
1939 400, 'easeInOutExpo'
1948 //______________________________________________________________________________
1949 // The amount to scroll vertically in integer pixels
1950 BookReader.prototype._scrollAmount = function() {
1951 if (this.constMode1up == this.mode) {
1952 // Overlap by % of page size
1953 return parseInt($('#BRcontainer').attr('clientHeight') - this.getPageHeight(this.currentIndex()) / this.reduce * 0.03);
1956 return parseInt(0.9 * $('#BRcontainer').attr('clientHeight'));
1960 // flipBackToIndex()
1961 //______________________________________________________________________________
1962 // to flip back one spread, pass index=null
1963 BookReader.prototype.flipBackToIndex = function(index) {
1965 if (1 == this.mode) return;
1967 var leftIndex = this.twoPage.currentIndexL;
1969 if (this.animating) return;
1971 if (null != this.leafEdgeTmp) {
1972 alert('error: leafEdgeTmp should be null!');
1976 if (null == index) {
1977 index = leftIndex-2;
1979 //if (index<0) return;
1981 var previousIndices = this.getSpreadIndices(index);
1983 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1987 this.animating = true;
1989 if ('rl' != this.pageProgression) {
1990 // Assume LTR and we are going backward
1991 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1992 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1994 // RTL and going backward
1995 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1996 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2000 // flipLeftToRight()
2001 //______________________________________________________________________________
2002 // Flips the page on the left towards the page on the right
2003 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2005 var leftLeaf = this.twoPage.currentIndexL;
2007 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2008 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2009 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2011 var currWidthL = this.getPageWidth2UP(leftLeaf);
2012 var newWidthL = this.getPageWidth2UP(newIndexL);
2013 var newWidthR = this.getPageWidth2UP(newIndexR);
2015 var top = this.twoPageTop();
2016 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2018 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2019 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2021 //animation strategy:
2022 // 0. remove search highlight, if any.
2023 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2024 // of the left leaf and where the user clicked in the leaf edge.
2025 // Note that if this function was triggered by left() and not a
2026 // mouse click, the width of leafEdgeTmp is very small (zero px).
2027 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2028 // leftLeaf to width=0.
2029 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2030 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2031 // its new full width.
2032 // 4. After step 3 is finished, do the following:
2033 // - remove leafEdgeTmp from the dom.
2034 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2035 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2036 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2037 // and width=newLeafEdgeWidthL.
2038 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2039 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2040 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2041 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2042 // - prefetch new adjacent leafs.
2043 // - set up click handlers for both new left and right leafs.
2044 // - redraw the search highlight.
2045 // - update the pagenum box and the url.
2048 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2050 this.leafEdgeTmp = document.createElement('div');
2051 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2052 $(this.leafEdgeTmp).css({
2053 width: leafEdgeTmpW + 'px',
2054 height: this.twoPage.height-1 + 'px',
2055 left: leftEdgeTmpLeft + 'px',
2058 }).appendTo('#BRtwopageview');
2060 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2061 $(this.leafEdgeL).css({
2062 width: newLeafEdgeWidthL+'px',
2063 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2066 // Left gets the offset of the current left leaf from the document
2067 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2068 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2069 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2071 // We change the left leaf to right positioning
2072 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2073 $(this.prefetchedImgs[leftLeaf]).css({
2078 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2079 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2083 this.removeSearchHilites();
2085 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2086 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2088 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2089 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2091 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2092 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2093 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2095 $(self.leafEdgeR).css({
2096 // Moves the right leaf edge
2097 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2098 left: gutter+newWidthR+'px'
2101 $(self.leafEdgeL).css({
2102 // Moves and resizes the left leaf edge
2103 width: newLeafEdgeWidthL+'px',
2104 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2107 // Resizes the brown border div
2108 $(self.twoPage.coverDiv).css({
2109 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2110 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2113 $(self.leafEdgeTmp).remove();
2114 self.leafEdgeTmp = null;
2116 // $$$ TODO refactor with opposite direction flip
2118 self.twoPage.currentIndexL = newIndexL;
2119 self.twoPage.currentIndexR = newIndexR;
2120 self.twoPage.scaledWL = newWidthL;
2121 self.twoPage.scaledWR = newWidthR;
2122 self.twoPage.gutter = gutter;
2124 self.firstIndex = self.twoPage.currentIndexL;
2125 self.displayedIndices = [newIndexL, newIndexR];
2126 self.pruneUnusedImgs();
2128 self.animating = false;
2130 self.updateSearchHilites2UP();
2131 self.updatePageNumBox2UP();
2133 // self.twoPagePlaceFlipAreas(); // No longer used
2134 self.setMouseHandlers2UP();
2135 self.twoPageSetCursor();
2137 if (self.animationFinishedCallback) {
2138 self.animationFinishedCallback();
2139 self.animationFinishedCallback = null;
2147 //______________________________________________________________________________
2148 // Whether we flip left or right is dependent on the page progression
2149 // to flip forward one spread, pass index=null
2150 BookReader.prototype.flipFwdToIndex = function(index) {
2152 if (this.animating) return;
2154 if (null != this.leafEdgeTmp) {
2155 alert('error: leafEdgeTmp should be null!');
2159 if (null == index) {
2160 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2162 if (index > this.lastDisplayableIndex()) return;
2164 this.animating = true;
2166 var nextIndices = this.getSpreadIndices(index);
2168 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2170 if ('rl' != this.pageProgression) {
2171 // We did not specify RTL
2172 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2173 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2176 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2177 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2181 // flipRightToLeft(nextL, nextR, gutter)
2182 // $$$ better not to have to pass gutter in
2183 //______________________________________________________________________________
2184 // Flip from left to right and show the nextL and nextR indices on those sides
2185 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2186 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2187 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2188 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2189 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2191 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2193 var top = this.twoPageTop();
2194 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2196 var middle = this.twoPage.middle;
2197 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2199 this.leafEdgeTmp = document.createElement('div');
2200 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2201 $(this.leafEdgeTmp).css({
2202 width: leafEdgeTmpW + 'px',
2203 height: this.twoPage.height-1 + 'px',
2204 left: gutter+scaledW+'px',
2207 }).appendTo('#BRtwopageview');
2209 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2210 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2212 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2213 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2214 var newWidthL = this.getPageWidth2UP(newIndexL);
2215 var newWidthR = this.getPageWidth2UP(newIndexR);
2217 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2219 var self = this; // closure-tastic!
2221 var speed = this.flipSpeed;
2223 this.removeSearchHilites();
2225 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2226 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2227 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2228 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2229 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2231 $(self.leafEdgeL).css({
2232 width: newLeafEdgeWidthL+'px',
2233 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2236 // Resizes the book cover
2237 $(self.twoPage.coverDiv).css({
2238 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2239 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2242 $(self.leafEdgeTmp).remove();
2243 self.leafEdgeTmp = null;
2245 self.twoPage.currentIndexL = newIndexL;
2246 self.twoPage.currentIndexR = newIndexR;
2247 self.twoPage.scaledWL = newWidthL;
2248 self.twoPage.scaledWR = newWidthR;
2249 self.twoPage.gutter = gutter;
2251 self.firstIndex = self.twoPage.currentIndexL;
2252 self.displayedIndices = [newIndexL, newIndexR];
2253 self.pruneUnusedImgs();
2255 self.animating = false;
2258 self.updateSearchHilites2UP();
2259 self.updatePageNumBox2UP();
2261 // self.twoPagePlaceFlipAreas(); // No longer used
2262 self.setMouseHandlers2UP();
2263 self.twoPageSetCursor();
2265 if (self.animationFinishedCallback) {
2266 self.animationFinishedCallback();
2267 self.animationFinishedCallback = null;
2273 // setMouseHandlers2UP
2274 //______________________________________________________________________________
2275 BookReader.prototype.setMouseHandlers2UP = function() {
2276 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2284 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2287 e.data.self.right();
2294 //______________________________________________________________________________
2295 BookReader.prototype.prefetchImg = function(index) {
2296 var pageURI = this._getPageURI(index);
2298 // Load image if not loaded or URI has changed (e.g. due to scaling)
2299 var loadImage = false;
2300 if (undefined == this.prefetchedImgs[index]) {
2301 //console.log('no image for ' + index);
2303 } else if (pageURI != this.prefetchedImgs[index].uri) {
2304 //console.log('uri changed for ' + index);
2309 //console.log('prefetching ' + index);
2310 var img = document.createElement("img");
2311 img.className = 'BRpageimage';
2313 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2314 this.prefetchedImgs[index] = img;
2319 // prepareFlipLeftToRight()
2321 //______________________________________________________________________________
2323 // Prepare to flip the left page towards the right. This corresponds to moving
2324 // backward when the page progression is left to right.
2325 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2327 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2329 this.prefetchImg(prevL);
2330 this.prefetchImg(prevR);
2332 var height = this._getPageHeight(prevL);
2333 var width = this._getPageWidth(prevL);
2334 var middle = this.twoPage.middle;
2335 var top = this.twoPageTop();
2336 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2338 // The gutter is the dividing line between the left and right pages.
2339 // It is offset from the middle to create the illusion of thickness to the pages
2340 var gutter = middle + this.gutterOffsetForIndex(prevL);
2342 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2343 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2344 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2347 position: 'absolute',
2348 left: gutter-scaledW+'px',
2349 right: '', // clear right property
2351 height: this.twoPage.height,
2352 width: scaledW+'px',
2353 borderRight: '1px solid black',
2357 $(this.prefetchedImgs[prevL]).css(leftCSS);
2359 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2361 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2364 position: 'absolute',
2368 height: this.twoPage.height,
2370 borderLeft: '1px solid black',
2374 $(this.prefetchedImgs[prevR]).css(rightCSS);
2376 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2380 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2381 // prepareFlipRightToLeft()
2382 //______________________________________________________________________________
2383 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2385 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2388 this.prefetchImg(nextL);
2389 this.prefetchImg(nextR);
2391 var height = this._getPageHeight(nextR);
2392 var width = this._getPageWidth(nextR);
2393 var middle = this.twoPage.middle;
2394 var top = this.twoPageTop();
2395 var scaledW = this.twoPage.height*width/height;
2397 var gutter = middle + this.gutterOffsetForIndex(nextL);
2399 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2400 $(this.prefetchedImgs[nextR]).css({
2401 position: 'absolute',
2404 height: this.twoPage.height,
2405 width: scaledW+'px',
2406 borderLeft: '1px solid black',
2410 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2412 height = this._getPageHeight(nextL);
2413 width = this._getPageWidth(nextL);
2414 scaledW = this.twoPage.height*width/height;
2416 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2417 $(this.prefetchedImgs[nextL]).css({
2418 position: 'absolute',
2419 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2421 height: this.twoPage.height,
2422 width: 0+'px', // Start at 0 width, then grow to the left
2423 borderRight: '1px solid black',
2427 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2431 // getNextLeafs() -- NOT RTL AWARE
2432 //______________________________________________________________________________
2433 // BookReader.prototype.getNextLeafs = function(o) {
2434 // //TODO: we might have two left or two right leafs in a row (damaged book)
2435 // //For now, assume that leafs are contiguous.
2437 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2438 // o.L = this.twoPage.currentIndexL+2;
2439 // o.R = this.twoPage.currentIndexL+3;
2442 // getprevLeafs() -- NOT RTL AWARE
2443 //______________________________________________________________________________
2444 // BookReader.prototype.getPrevLeafs = function(o) {
2445 // //TODO: we might have two left or two right leafs in a row (damaged book)
2446 // //For now, assume that leafs are contiguous.
2448 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2449 // o.L = this.twoPage.currentIndexL-2;
2450 // o.R = this.twoPage.currentIndexL-1;
2453 // pruneUnusedImgs()
2454 //______________________________________________________________________________
2455 BookReader.prototype.pruneUnusedImgs = function() {
2456 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2457 for (var key in this.prefetchedImgs) {
2458 //console.log('key is ' + key);
2459 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2460 //console.log('removing key '+ key);
2461 $(this.prefetchedImgs[key]).remove();
2463 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2464 //console.log('deleting key '+ key);
2465 delete this.prefetchedImgs[key];
2471 //______________________________________________________________________________
2472 BookReader.prototype.prefetch = function() {
2474 // $$$ We should check here if the current indices have finished
2475 // loading (with some timeout) before loading more page images
2476 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2478 // prefetch visible pages first
2479 this.prefetchImg(this.twoPage.currentIndexL);
2480 this.prefetchImg(this.twoPage.currentIndexR);
2482 var adjacentPagesToLoad = 3;
2484 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2485 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2487 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2488 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2490 // Load images spreading out from current
2491 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2492 var goingDown = lowCurrent - i;
2493 if (goingDown >= start) {
2494 this.prefetchImg(goingDown);
2496 var goingUp = highCurrent + i;
2497 if (goingUp <= end) {
2498 this.prefetchImg(goingUp);
2503 var lim = this.twoPage.currentIndexL-4;
2505 lim = Math.max(lim, 0);
2506 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2507 this.prefetchImg(i);
2510 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2511 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2512 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2513 this.prefetchImg(i);
2519 // getPageWidth2UP()
2520 //______________________________________________________________________________
2521 BookReader.prototype.getPageWidth2UP = function(index) {
2522 // We return the width based on the dominant height
2523 var height = this._getPageHeight(index);
2524 var width = this._getPageWidth(index);
2525 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2529 //______________________________________________________________________________
2530 BookReader.prototype.search = function(term) {
2531 term = term.replace(/\//g, ' '); // strip slashes
2532 this.searchTerm = term;
2533 $('#BookReaderSearchScript').remove();
2534 var script = document.createElement("script");
2535 script.setAttribute('id', 'BookReaderSearchScript');
2536 script.setAttribute("type", "text/javascript");
2537 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2538 document.getElementsByTagName('head')[0].appendChild(script);
2539 $('#BookReaderSearchBox').val(term);
2540 $('#BookReaderSearchResults').html('Searching...');
2543 // BRSearchCallback()
2544 //______________________________________________________________________________
2545 BookReader.prototype.BRSearchCallback = function(txt) {
2547 if (jQuery.browser.msie) {
2548 var dom=new ActiveXObject("Microsoft.XMLDOM");
2552 var parser = new DOMParser();
2553 var dom = parser.parseFromString(txt, "text/xml");
2556 $('#BookReaderSearchResults').empty();
2557 $('#BookReaderSearchResults').append('<ul>');
2559 for (var key in this.searchResults) {
2560 if (null != this.searchResults[key].div) {
2561 $(this.searchResults[key].div).remove();
2563 delete this.searchResults[key];
2566 var pages = dom.getElementsByTagName('PAGE');
2568 if (0 == pages.length) {
2569 // $$$ it would be nice to echo the (sanitized) search result here
2570 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2572 for (var i = 0; i < pages.length; i++){
2573 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2576 var re = new RegExp (/_(\d{4})\.djvu/);
2577 var reMatch = re.exec(pages[i].getAttribute('file'));
2578 var index = parseInt(reMatch[1], 10);
2579 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2581 var children = pages[i].childNodes;
2583 for (var j=0; j<children.length; j++) {
2584 //console.log(j + ' - ' + children[j].nodeName);
2585 //console.log(children[j].firstChild.nodeValue);
2586 if ('CONTEXT' == children[j].nodeName) {
2587 context += children[j].firstChild.nodeValue;
2588 } else if ('WORD' == children[j].nodeName) {
2589 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2591 var index = this.leafNumToIndex(index);
2592 if (null != index) {
2593 //coordinates are [left, bottom, right, top, [baseline]]
2594 //we'll skip baseline for now...
2595 var coords = children[j].getAttribute('coords').split(',',4);
2596 if (4 == coords.length) {
2597 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2602 var pageName = this.getPageName(index);
2603 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2604 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2605 //TODO: remove hardcoded instance name
2606 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2609 $('#BookReaderSearchResults').append('</ul>');
2611 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2612 $('#BookReaderSearchBox').val(this.searchTerm);
2614 this.updateSearchHilites();
2617 // updateSearchHilites()
2618 //______________________________________________________________________________
2619 BookReader.prototype.updateSearchHilites = function() {
2620 if (2 == this.mode) {
2621 this.updateSearchHilites2UP();
2623 this.updateSearchHilites1UP();
2627 // showSearchHilites1UP()
2628 //______________________________________________________________________________
2629 BookReader.prototype.updateSearchHilites1UP = function() {
2631 for (var key in this.searchResults) {
2633 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2634 var result = this.searchResults[key];
2635 if (null == result.div) {
2636 result.div = document.createElement('div');
2637 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2638 //console.log('appending ' + key);
2641 width: (result.r-result.l)/this.reduce + 'px',
2642 height: (result.b-result.t)/this.reduce + 'px',
2643 left: (result.l)/this.reduce + 'px',
2644 top: (result.t)/this.reduce +'px'
2648 //console.log(key + ' not displayed');
2649 this.searchResults[key].div=null;
2655 //______________________________________________________________________________
2656 // Returns the position of the gutter (line between the page images)
2657 BookReader.prototype.twoPageGutter = function() {
2658 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2662 //______________________________________________________________________________
2663 // Returns the offset for the top of the page images
2664 BookReader.prototype.twoPageTop = function() {
2665 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2668 // twoPageCoverWidth()
2669 //______________________________________________________________________________
2670 // Returns the width of the cover div given the total page width
2671 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2672 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2675 // twoPageGetViewCenter()
2676 //______________________________________________________________________________
2677 // Returns the percentage offset into twopageview div at the center of container div
2678 // { percentageX: float, percentageY: float }
2679 BookReader.prototype.twoPageGetViewCenter = function() {
2682 var containerOffset = $('#BRcontainer').offset();
2683 var viewOffset = $('#BRtwopageview').offset();
2684 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2685 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2690 // twoPageCenterView(percentageX, percentageY)
2691 //______________________________________________________________________________
2692 // Centers the point given by percentage from left,top of twopageview
2693 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2694 if ('undefined' == typeof(percentageX)) {
2697 if ('undefined' == typeof(percentageY)) {
2701 var viewWidth = $('#BRtwopageview').width();
2702 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2703 var intoViewX = percentageX * viewWidth;
2705 var viewHeight = $('#BRtwopageview').height();
2706 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2707 var intoViewY = percentageY * viewHeight;
2709 if (viewWidth < containerClientWidth) {
2710 // Can fit width without scrollbars - center by adjusting offset
2711 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2713 // Need to scroll to center
2714 $('#BRtwopageview').css('left', 0);
2715 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2718 if (viewHeight < containerClientHeight) {
2719 // Fits with scrollbars - add offset
2720 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2722 $('#BRtwopageview').css('top', 0);
2723 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2727 // twoPageFlipAreaHeight
2728 //______________________________________________________________________________
2729 // Returns the integer height of the click-to-flip areas at the edges of the book
2730 BookReader.prototype.twoPageFlipAreaHeight = function() {
2731 return parseInt(this.twoPage.height);
2734 // twoPageFlipAreaWidth
2735 //______________________________________________________________________________
2736 // Returns the integer width of the flip areas
2737 BookReader.prototype.twoPageFlipAreaWidth = function() {
2738 var max = 100; // $$$ TODO base on view width?
2741 var width = this.twoPage.width * 0.15;
2742 return parseInt(BookReader.util.clamp(width, min, max));
2745 // twoPageFlipAreaTop
2746 //______________________________________________________________________________
2747 // Returns integer top offset for flip areas
2748 BookReader.prototype.twoPageFlipAreaTop = function() {
2749 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2752 // twoPageLeftFlipAreaLeft
2753 //______________________________________________________________________________
2754 // Left offset for left flip area
2755 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2756 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2759 // twoPageRightFlipAreaLeft
2760 //______________________________________________________________________________
2761 // Left offset for right flip area
2762 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2763 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2766 // twoPagePlaceFlipAreas
2767 //______________________________________________________________________________
2768 // Readjusts position of flip areas based on current layout
2769 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2770 // We don't set top since it shouldn't change relative to view
2771 $(this.twoPage.leftFlipArea).css({
2772 left: this.twoPageLeftFlipAreaLeft() + 'px',
2773 width: this.twoPageFlipAreaWidth() + 'px'
2775 $(this.twoPage.rightFlipArea).css({
2776 left: this.twoPageRightFlipAreaLeft() + 'px',
2777 width: this.twoPageFlipAreaWidth() + 'px'
2781 // showSearchHilites2UP()
2782 //______________________________________________________________________________
2783 BookReader.prototype.updateSearchHilites2UP = function() {
2785 for (var key in this.searchResults) {
2786 key = parseInt(key, 10);
2787 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2788 var result = this.searchResults[key];
2789 if (null == result.div) {
2790 result.div = document.createElement('div');
2791 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2792 //console.log('appending ' + key);
2795 // We calculate the reduction factor for the specific page because it can be different
2796 // for each page in the spread
2797 var height = this._getPageHeight(key);
2798 var width = this._getPageWidth(key)
2799 var reduce = this.twoPage.height/height;
2800 var scaledW = parseInt(width*reduce);
2802 var gutter = this.twoPageGutter();
2804 if ('L' == this.getPageSide(key)) {
2805 pageL = gutter-scaledW;
2809 var pageT = this.twoPageTop();
2812 width: (result.r-result.l)*reduce + 'px',
2813 height: (result.b-result.t)*reduce + 'px',
2814 left: pageL+(result.l)*reduce + 'px',
2815 top: pageT+(result.t)*reduce +'px'
2819 //console.log(key + ' not displayed');
2820 if (null != this.searchResults[key].div) {
2821 //console.log('removing ' + key);
2822 $(this.searchResults[key].div).remove();
2824 this.searchResults[key].div=null;
2829 // removeSearchHilites()
2830 //______________________________________________________________________________
2831 BookReader.prototype.removeSearchHilites = function() {
2832 for (var key in this.searchResults) {
2833 if (null != this.searchResults[key].div) {
2834 $(this.searchResults[key].div).remove();
2835 this.searchResults[key].div=null;
2841 //______________________________________________________________________________
2842 BookReader.prototype.printPage = function() {
2843 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2846 // Get print URI from current indices and mode
2847 BookReader.prototype.getPrintURI = function() {
2849 if (this.constMode2up == this.mode) {
2850 indexToPrint = this.twoPage.currentIndexL;
2852 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2855 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2856 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2857 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2859 if (this.constMode2up == this.mode) {
2860 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2861 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2862 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2864 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2867 return '/bookreader/print.php?' + options;
2870 /* iframe implementation
2871 BookReader.prototype.getPrintFrameContent = function(index) {
2872 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2873 // 8.5x11 so we should end up not overflowing on either paper size.
2874 var paperAspect = 8.5 / 11;
2875 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2879 // Rotate if possible and appropriate, to get larger image size on printed page
2880 if (this.canRotatePage(index)) {
2881 if (imageAspect > 1 && imageAspect > paperAspect) {
2882 // more wide than square, and more wide than paper
2884 imageAspect = 1/imageAspect;
2889 if (imageAspect > paperAspect) {
2890 // wider than paper, fit width
2891 fitAttrs = 'width="95%"';
2893 // taller than paper, fit height
2894 fitAttrs = 'height="95%"';
2897 var imageURL = this._getPageURI(index, 1, rotate);
2898 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2899 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2900 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2901 iframeStr += '</div>';
2902 iframeStr += '</body></html>';
2907 BookReader.prototype.updatePrintFrame = function(delta) {
2908 var newIndex = this.indexToPrint + delta;
2909 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2910 if (newIndex == this.indexToPrint) {
2913 this.indexToPrint = newIndex;
2914 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2915 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2920 //______________________________________________________________________________
2921 BookReader.prototype.showEmbedCode = function() {
2922 if (null != this.embedPopup) { // check if already showing
2926 this.embedPopup = document.createElement("div");
2927 $(this.embedPopup).css({
2928 position: 'absolute',
2930 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2933 border: "3px double #999999",
2935 backgroundColor: "#fff"
2936 }).appendTo('#BookReader');
2938 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2939 htmlStr += '<p>The bookreader uses iframes for embedding. It will not work on web hosts that block iframes. The embed feature has been tested on blogspot.com blogs as well as self-hosted Wordpress blogs. This feature will NOT work on wordpress.com blogs.</p>';
2940 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2941 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2943 this.embedPopup.innerHTML = htmlStr;
2944 $(this.embedPopup).find('input').bind('click', function() {
2950 //______________________________________________________________________________
2951 BookReader.prototype.autoToggle = function() {
2953 var bComingFrom1up = false;
2954 if (2 != this.mode) {
2955 bComingFrom1up = true;
2959 // Change to autofit if book is too large
2960 if (this.reduce < this.twoPageGetAutofitReduce()) {
2961 this.zoom2up('auto');
2965 if (null == this.autoTimer) {
2966 this.flipSpeed = 2000;
2968 // $$$ Draw events currently cause layout problems when they occur during animation.
2969 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2970 // we workaround for now by not triggering immediate animation in that case.
2971 // See https://bugs.launchpad.net/gnubook/+bug/328327
2972 if (('rl' == this.pageProgression) && bComingFrom1up) {
2973 // don't flip immediately -- wait until timer fires
2976 this.flipFwdToIndex();
2979 $('#BRtoolbar .play').hide();
2980 $('#BRtoolbar .pause').show();
2981 this.autoTimer=setInterval(function(){
2982 if (self.animating) {return;}
2984 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2985 self.flipBackToIndex(1); // $$$ really what we want?
2987 self.flipFwdToIndex();
2996 //______________________________________________________________________________
2997 // Stop autoplay mode, allowing animations to finish
2998 BookReader.prototype.autoStop = function() {
2999 if (null != this.autoTimer) {
3000 clearInterval(this.autoTimer);
3001 this.flipSpeed = 'fast';
3002 $('#BRtoolbar .pause').hide();
3003 $('#BRtoolbar .play').show();
3004 this.autoTimer = null;
3008 // stopFlipAnimations
3009 //______________________________________________________________________________
3010 // Immediately stop flip animations. Callbacks are triggered.
3011 BookReader.prototype.stopFlipAnimations = function() {
3013 this.autoStop(); // Clear timers
3015 // Stop animation, clear queue, trigger callbacks
3016 if (this.leafEdgeTmp) {
3017 $(this.leafEdgeTmp).stop(false, true);
3019 jQuery.each(this.prefetchedImgs, function() {
3020 $(this).stop(false, true);
3023 // And again since animations also queued in callbacks
3024 if (this.leafEdgeTmp) {
3025 $(this.leafEdgeTmp).stop(false, true);
3027 jQuery.each(this.prefetchedImgs, function() {
3028 $(this).stop(false, true);
3033 // keyboardNavigationIsDisabled(event)
3034 // - returns true if keyboard navigation should be disabled for the event
3035 //______________________________________________________________________________
3036 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3037 if (event.target.tagName == "INPUT") {
3043 // gutterOffsetForIndex
3044 //______________________________________________________________________________
3046 // Returns the gutter offset for the spread containing the given index.
3047 // This function supports RTL
3048 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3050 // To find the offset of the gutter from the middle we calculate our percentage distance
3051 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3052 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3054 // But then again for RTL it's the opposite
3055 if ('rl' == this.pageProgression) {
3063 //______________________________________________________________________________
3064 // Returns the width of the leaf edge div for the page with index given
3065 BookReader.prototype.leafEdgeWidth = function(pindex) {
3066 // $$$ could there be single pixel rounding errors for L vs R?
3067 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3068 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3070 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3074 // jumpIndexForLeftEdgePageX
3075 //______________________________________________________________________________
3076 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3077 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3078 if ('rl' != this.pageProgression) {
3079 // LTR - flipping backward
3080 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3082 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3083 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3087 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3088 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3093 // jumpIndexForRightEdgePageX
3094 //______________________________________________________________________________
3095 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3096 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3097 if ('rl' != this.pageProgression) {
3099 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3100 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3103 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3104 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3109 BookReader.prototype.initToolbar = function(mode, ui) {
3111 $("#BookReader").append("<div id='BRtoolbar'>"
3112 + "<span id='BRtoolbarbuttons' style='float: right'>"
3113 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3114 + "<form class='BRpageform' action='javascript:' onsubmit='br.jumpToPage(this.elements[0].value)'> <span class='label'>Page:<input id='BRpagenum' type='text' size='3' onfocus='br.autoStop();'></input></span></form>"
3115 + "<div class='BRtoolbarmode2' style='display: none'><button class='BRicon rollover book_leftmost' /><button class='BRicon rollover book_left' /><button class='BRicon rollover book_right' /><button class='BRicon rollover book_rightmost' /></div>"
3116 + "<div class='BRtoolbarmode1' style='display: none'><button class='BRicon rollover book_top' /><button class='BRicon rollover book_up' /> <button class='BRicon rollover book_down' /><button class='BRicon rollover book_bottom' /></div>"
3117 + "<div class='BRtoolbarmode3' style='display: none'><button class='BRicon rollover book_top' /><button class='BRicon rollover book_up' /> <button class='BRicon rollover book_down' /><button class='BRicon rollover book_bottom' /></div>"
3118 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3122 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3123 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3124 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3125 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3126 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3127 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3128 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3131 + "<span id='#BRbooktitle'>"
3132 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3136 this.updateToolbarZoom(this.reduce); // Pretty format
3138 if (ui == "embed" || ui == "touch") {
3139 $("#BookReader a.logo").attr("target","_blank");
3142 // $$$ turn this into a member variable
3143 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3145 // We build in mode 2
3148 this.bindToolbarNavHandlers(jToolbar);
3150 // Setup tooltips -- later we could load these from a file for i18n
3151 var titles = { '.logo': 'Go to Archive.org',
3152 '.zoom_in': 'Zoom in',
3153 '.zoom_out': 'Zoom out',
3154 '.one_page_mode': 'One-page view',
3155 '.two_page_mode': 'Two-page view',
3156 '.thumbnail_mode': 'Thumbnail view',
3157 '.print': 'Print this page',
3158 '.embed': 'Embed bookreader',
3159 '.book_left': 'Flip left',
3160 '.book_right': 'Flip right',
3161 '.book_up': 'Page up',
3162 '.book_down': 'Page down',
3165 '.book_top': 'First page',
3166 '.book_bottom': 'Last page'
3168 if ('rl' == this.pageProgression) {
3169 titles['.book_leftmost'] = 'Last page';
3170 titles['.book_rightmost'] = 'First page';
3172 titles['.book_leftmost'] = 'First page';
3173 titles['.book_rightmost'] = 'Last page';
3176 for (var icon in titles) {
3177 jToolbar.find(icon).attr('title', titles[icon]);
3180 // Hide mode buttons and autoplay if 2up is not available
3181 // $$$ if we end up with more than two modes we should show the applicable buttons
3182 if ( !this.canSwitchToMode(this.constMode2up) ) {
3183 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3186 // Switch to requested mode -- binds other click handlers
3187 this.switchToolbarMode(mode);
3192 // switchToolbarMode
3193 //______________________________________________________________________________
3194 // Update the toolbar for the given mode (changes navigation buttons)
3195 // $$$ we should soon split the toolbar out into its own module
3196 BookReader.prototype.switchToolbarMode = function(mode) {
3199 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3200 $('#BRtoolbar .BRtoolbarmode2').hide();
3201 $('#BRtoolbar .BRtoolbarmode3').hide();
3202 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3203 } else if (2 == mode) {
3205 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3206 $('#BRtoolbar .BRtoolbarmode1').hide();
3207 $('#BRtoolbar .BRtoolbarmode3').hide();
3208 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3211 $('#BRtoolbar .BRtoolbarzoom').hide();
3212 $('#BRtoolbar .BRtoolbarmode2').hide();
3213 $('#BRtoolbar .BRtoolbarmode1').hide();
3214 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3218 // bindToolbarNavHandlers
3219 //______________________________________________________________________________
3220 // Binds the toolbar handlers
3221 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3223 var self = this; // closure
3225 jToolbar.find('.book_left').bind('click', function(e) {
3230 jToolbar.find('.book_right').bind('click', function(e) {
3235 jToolbar.find('.book_up').bind('click', function(e) {
3236 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3244 jToolbar.find('.book_down').bind('click', function(e) {
3245 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3253 jToolbar.find('.print').bind('click', function(e) {
3258 jToolbar.find('.embed').bind('click', function(e) {
3259 self.showEmbedCode();
3263 jToolbar.find('.play').bind('click', function(e) {
3268 jToolbar.find('.pause').bind('click', function(e) {
3273 jToolbar.find('.book_top').bind('click', function(e) {
3278 jToolbar.find('.book_bottom').bind('click', function(e) {
3283 jToolbar.find('.book_leftmost').bind('click', function(e) {
3288 jToolbar.find('.book_rightmost').bind('click', function(e) {
3294 // updateToolbarZoom(reduce)
3295 //______________________________________________________________________________
3296 // Update the displayed zoom factor based on reduction factor
3297 BookReader.prototype.updateToolbarZoom = function(reduce) {
3301 // $$$ TODO preserve zoom/fit for each mode
3302 if (this.mode == this.constMode2up) {
3303 autofit = this.twoPage.autofit;
3305 autofit = this.onePage.autofit;
3309 value = autofit[0].toUpperCase() + autofit.slice(1);
3311 value = (100 / reduce).toFixed(2);
3312 // Strip trailing zeroes and decimal if all zeroes
3313 value = value.replace(/0+$/,'');
3314 value = value.replace(/\.$/,'');
3317 $('#BRzoom').text(value);
3320 // firstDisplayableIndex
3321 //______________________________________________________________________________
3322 // Returns the index of the first visible page, dependent on the mode.
3323 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3324 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3325 BookReader.prototype.firstDisplayableIndex = function() {
3326 if (this.mode != this.constMode2up) {
3330 if ('rl' != this.pageProgression) {
3332 if (this.getPageSide(0) == 'L') {
3339 if (this.getPageSide(0) == 'R') {
3347 // lastDisplayableIndex
3348 //______________________________________________________________________________
3349 // Returns the index of the last visible page, dependent on the mode.
3350 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3351 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3352 BookReader.prototype.lastDisplayableIndex = function() {
3354 var lastIndex = this.numLeafs - 1;
3356 if (this.mode != this.constMode2up) {
3360 if ('rl' != this.pageProgression) {
3362 if (this.getPageSide(lastIndex) == 'R') {
3365 return lastIndex + 1;
3369 if (this.getPageSide(lastIndex) == 'L') {
3372 return lastIndex + 1;
3377 // shortTitle(maximumCharacters)
3379 // Returns a shortened version of the title with the maximum number of characters
3380 BookReader.prototype.shortTitle = function(maximumCharacters) {
3381 if (this.bookTitle.length < maximumCharacters) {
3382 return this.bookTitle;
3385 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3390 // Parameter related functions
3392 // updateFromParams(params)
3394 // Update ourselves from the params object.
3396 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3397 BookReader.prototype.updateFromParams = function(params) {
3398 if ('undefined' != typeof(params.mode)) {
3399 this.switchMode(params.mode);
3403 if ('undefined' != typeof(params.searchTerm)) {
3404 if (this.searchTerm != params.searchTerm) {
3405 this.search(params.searchTerm);
3409 // $$$ process /zoom
3411 // We only respect page if index is not set
3412 if ('undefined' != typeof(params.index)) {
3413 if (params.index != this.currentIndex()) {
3414 this.jumpToIndex(params.index);
3416 } else if ('undefined' != typeof(params.page)) {
3417 // $$$ this assumes page numbers are unique
3418 if (params.page != this.getPageNum(this.currentIndex())) {
3419 this.jumpToPage(params.page);
3423 // $$$ process /region
3424 // $$$ process /highlight
3427 // paramsFromFragment(urlFragment)
3429 // Returns a object with configuration parametes from a URL fragment.
3431 // E.g paramsFromFragment(window.location.hash)
3432 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3433 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3437 // For convenience we allow an initial # character (as from window.location.hash)
3438 // but don't require it
3439 if (urlFragment.substr(0,1) == '#') {
3440 urlFragment = urlFragment.substr(1);
3443 // Simple #nn syntax
3444 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3445 if ( !isNaN(oldStyleLeafNum) ) {
3446 params.index = oldStyleLeafNum;
3448 // Done processing if using old-style syntax
3452 // Split into key-value pairs
3453 var urlArray = urlFragment.split('/');
3455 for (var i = 0; i < urlArray.length; i += 2) {
3456 urlHash[urlArray[i]] = urlArray[i+1];
3460 if ('1up' == urlHash['mode']) {
3461 params.mode = this.constMode1up;
3462 } else if ('2up' == urlHash['mode']) {
3463 params.mode = this.constMode2up;
3464 } else if ('thumb' == urlHash['mode']) {
3465 params.mode = this.constModeThumb;
3469 if ('undefined' != typeof(urlHash['page'])) {
3470 // page was set -- may not be int
3471 params.page = urlHash['page'];
3474 // $$$ process /region
3475 // $$$ process /search
3477 if (urlHash['search'] != undefined) {
3478 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3481 // $$$ process /highlight
3486 // paramsFromCurrent()
3488 // Create a params object from the current parameters.
3489 BookReader.prototype.paramsFromCurrent = function() {
3493 var index = this.currentIndex();
3494 var pageNum = this.getPageNum(index);
3495 if ((pageNum === 0) || pageNum) {
3496 params.page = pageNum;
3499 params.index = index;
3500 params.mode = this.mode;
3506 if (this.searchHighlightVisible()) {
3507 params.searchTerm = this.searchTerm;
3513 // fragmentFromParams(params)
3515 // Create a fragment string from the params object.
3516 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3517 BookReader.prototype.fragmentFromParams = function(params) {
3518 var separator = '/';
3522 if ('undefined' != typeof(params.page)) {
3523 fragments.push('page', params.page);
3525 // Don't have page numbering -- use index instead
3526 fragments.push('page', 'n' + params.index);
3533 if ('undefined' != typeof(params.mode)) {
3534 if (params.mode == this.constMode1up) {
3535 fragments.push('mode', '1up');
3536 } else if (params.mode == this.constMode2up) {
3537 fragments.push('mode', '2up');
3538 } else if (params.mode == this.constModeThumb) {
3539 fragments.push('mode', 'thumb');
3541 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3546 if (params.searchTerm) {
3547 fragments.push('search', params.searchTerm);
3550 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3553 // getPageIndex(pageNum)
3555 // Returns the *highest* index the given page number, or undefined
3556 BookReader.prototype.getPageIndex = function(pageNum) {
3557 var pageIndices = this.getPageIndices(pageNum);
3559 if (pageIndices.length > 0) {
3560 return pageIndices[pageIndices.length - 1];
3566 // getPageIndices(pageNum)
3568 // Returns an array (possibly empty) of the indices with the given page number
3569 BookReader.prototype.getPageIndices = function(pageNum) {
3572 // Check for special "nXX" page number
3573 if (pageNum.slice(0,1) == 'n') {
3575 var pageIntStr = pageNum.slice(1, pageNum.length);
3576 var pageIndex = parseInt(pageIntStr);
3577 indices.push(pageIndex);
3580 // Do nothing... will run through page names and see if one matches
3585 for (i=0; i<this.numLeafs; i++) {
3586 if (this.getPageNum(i) == pageNum) {
3594 // getPageName(index)
3596 // Returns the name of the page as it should be displayed in the user interface
3597 BookReader.prototype.getPageName = function(index) {
3598 return 'Page ' + this.getPageNum(index);
3601 // updateLocationHash
3603 // Update the location hash from the current parameters. Call this instead of manually
3604 // using window.location.replace
3605 BookReader.prototype.updateLocationHash = function() {
3606 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3607 window.location.replace(newHash);
3609 // This is the variable checked in the timer. Only user-generated changes
3610 // to the URL will trigger the event.
3611 this.oldLocationHash = newHash;
3614 // startLocationPolling
3616 // Starts polling of window.location to see hash fragment changes
3617 BookReader.prototype.startLocationPolling = function() {
3618 var self = this; // remember who I am
3619 self.oldLocationHash = window.location.hash;
3621 if (this.locationPollId) {
3622 clearInterval(this.locationPollID);
3623 this.locationPollId = null;
3626 this.locationPollId = setInterval(function() {
3627 var newHash = window.location.hash;
3628 if (newHash != self.oldLocationHash) {
3629 if (newHash != self.oldUserHash) { // Only process new user hash once
3630 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3632 // Queue change if animating
3633 if (self.animating) {
3635 self.animationFinishedCallback = function() {
3636 self.updateFromParams(self.paramsFromFragment(newHash));
3638 } else { // update immediately
3639 self.updateFromParams(self.paramsFromFragment(newHash));
3641 self.oldUserHash = newHash;
3649 // Returns true if we can switch to the requested mode
3650 BookReader.prototype.canSwitchToMode = function(mode) {
3651 if (mode == this.constMode2up) {
3652 // check there are enough pages to display
3653 // $$$ this is a workaround for the mis-feature that we can't display
3654 // short books in 2up mode
3655 if (this.numLeafs < 6) {
3663 // searchHighlightVisible
3665 // Returns true if a search highlight is currently being displayed
3666 BookReader.prototype.searchHighlightVisible = function() {
3667 if (this.constMode2up == this.mode) {
3668 if (this.searchResults[this.twoPage.currentIndexL]
3669 || this.searchResults[this.twoPage.currentIndexR]) {
3673 if (this.searchResults[this.currentIndex()]) {
3682 // Returns the page width for the given index, or first or last page if out of range
3683 BookReader.prototype._getPageWidth = function(index) {
3684 // Synthesize a page width for pages not actually present in book.
3685 // May or may not be the best approach.
3686 // If index is out of range we return the width of first or last page
3687 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3688 return this.getPageWidth(index);
3693 // Returns the page height for the given index, or first or last page if out of range
3694 BookReader.prototype._getPageHeight= function(index) {
3695 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3696 return this.getPageHeight(index);
3701 // Returns the page URI or transparent image if out of range
3702 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3703 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3704 return this.imagesBaseURL + "/transparent.png";
3707 if ('undefined' == typeof(reduce)) {
3708 // reduce not passed in
3709 // $$$ this probably won't work for thumbnail mode
3710 var ratio = this.getPageHeight(index) / this.twoPage.height;
3712 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3715 } else if (ratio < 4) {
3717 } else if (ratio < 8) {
3719 } else if (ratio < 16) {
3721 } else if (ratio < 32) {
3729 return this.getPageURI(index, reduce, rotate);
3732 // Library functions
3734 disableSelect: function(jObject) {
3735 // Bind mouse handlers
3736 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3737 jObject.bind('mousedown', function(e) {
3738 // $$$ check here for right-click and don't disable. Also use jQuery style
3739 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3742 // Special hack for IE7
3743 jObject[0].onselectstart = function(e) { return false; };
3746 clamp: function(value, min, max) {
3747 return Math.min(Math.max(value, min), max);
3750 notInArray: function(value, array) {
3751 // inArray returns -1 or undefined if value not in array
3752 return ! (jQuery.inArray(value, array) >= 0);
3755 getIFrameDocument: function(iframe) {
3756 // Adapted from http://xkr.us/articles/dom/iframe-document/
3757 var outer = (iframe.contentWindow || iframe.contentDocument);
3758 return (outer.document || outer);
3761 decodeURIComponentPlus: function(value) {
3762 // Decodes a URI component and converts '+' to ' '
3763 return decodeURIComponent(value).replace(/\+/g, ' ');
3766 encodeURIComponentPlus: function(value) {
3767 // Encodes a URI component and converts ' ' to '+'
3768 return encodeURIComponent(value).replace(/%20/g, '+');
3770 // The final property here must NOT have a comma after it - IE7