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';
2312 if (index < 0 || index > (this.numLeafs - 1) ) {
2313 // Facing page at beginning or end, or beyond
2315 'background-color': 'transparent'
2319 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2320 this.prefetchedImgs[index] = img;
2325 // prepareFlipLeftToRight()
2327 //______________________________________________________________________________
2329 // Prepare to flip the left page towards the right. This corresponds to moving
2330 // backward when the page progression is left to right.
2331 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2333 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2335 this.prefetchImg(prevL);
2336 this.prefetchImg(prevR);
2338 var height = this._getPageHeight(prevL);
2339 var width = this._getPageWidth(prevL);
2340 var middle = this.twoPage.middle;
2341 var top = this.twoPageTop();
2342 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2344 // The gutter is the dividing line between the left and right pages.
2345 // It is offset from the middle to create the illusion of thickness to the pages
2346 var gutter = middle + this.gutterOffsetForIndex(prevL);
2348 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2349 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2350 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2353 position: 'absolute',
2354 left: gutter-scaledW+'px',
2355 right: '', // clear right property
2357 height: this.twoPage.height,
2358 width: scaledW+'px',
2359 borderRight: '1px solid black',
2363 $(this.prefetchedImgs[prevL]).css(leftCSS);
2365 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2367 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2370 position: 'absolute',
2374 height: this.twoPage.height,
2376 borderLeft: '1px solid black',
2380 $(this.prefetchedImgs[prevR]).css(rightCSS);
2382 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2386 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2387 // prepareFlipRightToLeft()
2388 //______________________________________________________________________________
2389 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2391 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2394 this.prefetchImg(nextL);
2395 this.prefetchImg(nextR);
2397 var height = this._getPageHeight(nextR);
2398 var width = this._getPageWidth(nextR);
2399 var middle = this.twoPage.middle;
2400 var top = this.twoPageTop();
2401 var scaledW = this.twoPage.height*width/height;
2403 var gutter = middle + this.gutterOffsetForIndex(nextL);
2405 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2406 $(this.prefetchedImgs[nextR]).css({
2407 position: 'absolute',
2410 height: this.twoPage.height,
2411 width: scaledW+'px',
2412 borderLeft: '1px solid black',
2416 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2418 height = this._getPageHeight(nextL);
2419 width = this._getPageWidth(nextL);
2420 scaledW = this.twoPage.height*width/height;
2422 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2423 $(this.prefetchedImgs[nextL]).css({
2424 position: 'absolute',
2425 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2427 height: this.twoPage.height,
2428 width: 0+'px', // Start at 0 width, then grow to the left
2429 borderRight: '1px solid black',
2433 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2437 // getNextLeafs() -- NOT RTL AWARE
2438 //______________________________________________________________________________
2439 // BookReader.prototype.getNextLeafs = function(o) {
2440 // //TODO: we might have two left or two right leafs in a row (damaged book)
2441 // //For now, assume that leafs are contiguous.
2443 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2444 // o.L = this.twoPage.currentIndexL+2;
2445 // o.R = this.twoPage.currentIndexL+3;
2448 // getprevLeafs() -- NOT RTL AWARE
2449 //______________________________________________________________________________
2450 // BookReader.prototype.getPrevLeafs = function(o) {
2451 // //TODO: we might have two left or two right leafs in a row (damaged book)
2452 // //For now, assume that leafs are contiguous.
2454 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2455 // o.L = this.twoPage.currentIndexL-2;
2456 // o.R = this.twoPage.currentIndexL-1;
2459 // pruneUnusedImgs()
2460 //______________________________________________________________________________
2461 BookReader.prototype.pruneUnusedImgs = function() {
2462 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2463 for (var key in this.prefetchedImgs) {
2464 //console.log('key is ' + key);
2465 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2466 //console.log('removing key '+ key);
2467 $(this.prefetchedImgs[key]).remove();
2469 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2470 //console.log('deleting key '+ key);
2471 delete this.prefetchedImgs[key];
2477 //______________________________________________________________________________
2478 BookReader.prototype.prefetch = function() {
2480 // $$$ We should check here if the current indices have finished
2481 // loading (with some timeout) before loading more page images
2482 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2484 // prefetch visible pages first
2485 this.prefetchImg(this.twoPage.currentIndexL);
2486 this.prefetchImg(this.twoPage.currentIndexR);
2488 var adjacentPagesToLoad = 3;
2490 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2491 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2493 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2494 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2496 // Load images spreading out from current
2497 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2498 var goingDown = lowCurrent - i;
2499 if (goingDown >= start) {
2500 this.prefetchImg(goingDown);
2502 var goingUp = highCurrent + i;
2503 if (goingUp <= end) {
2504 this.prefetchImg(goingUp);
2509 var lim = this.twoPage.currentIndexL-4;
2511 lim = Math.max(lim, 0);
2512 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2513 this.prefetchImg(i);
2516 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2517 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2518 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2519 this.prefetchImg(i);
2525 // getPageWidth2UP()
2526 //______________________________________________________________________________
2527 BookReader.prototype.getPageWidth2UP = function(index) {
2528 // We return the width based on the dominant height
2529 var height = this._getPageHeight(index);
2530 var width = this._getPageWidth(index);
2531 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2535 //______________________________________________________________________________
2536 BookReader.prototype.search = function(term) {
2537 term = term.replace(/\//g, ' '); // strip slashes
2538 this.searchTerm = term;
2539 $('#BookReaderSearchScript').remove();
2540 var script = document.createElement("script");
2541 script.setAttribute('id', 'BookReaderSearchScript');
2542 script.setAttribute("type", "text/javascript");
2543 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2544 document.getElementsByTagName('head')[0].appendChild(script);
2545 $('#BookReaderSearchBox').val(term);
2546 $('#BookReaderSearchResults').html('Searching...');
2549 // BRSearchCallback()
2550 //______________________________________________________________________________
2551 BookReader.prototype.BRSearchCallback = function(txt) {
2553 if (jQuery.browser.msie) {
2554 var dom=new ActiveXObject("Microsoft.XMLDOM");
2558 var parser = new DOMParser();
2559 var dom = parser.parseFromString(txt, "text/xml");
2562 $('#BookReaderSearchResults').empty();
2563 $('#BookReaderSearchResults').append('<ul>');
2565 for (var key in this.searchResults) {
2566 if (null != this.searchResults[key].div) {
2567 $(this.searchResults[key].div).remove();
2569 delete this.searchResults[key];
2572 var pages = dom.getElementsByTagName('PAGE');
2574 if (0 == pages.length) {
2575 // $$$ it would be nice to echo the (sanitized) search result here
2576 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2578 for (var i = 0; i < pages.length; i++){
2579 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2582 var re = new RegExp (/_(\d{4})\.djvu/);
2583 var reMatch = re.exec(pages[i].getAttribute('file'));
2584 var index = parseInt(reMatch[1], 10);
2585 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2587 var children = pages[i].childNodes;
2589 for (var j=0; j<children.length; j++) {
2590 //console.log(j + ' - ' + children[j].nodeName);
2591 //console.log(children[j].firstChild.nodeValue);
2592 if ('CONTEXT' == children[j].nodeName) {
2593 context += children[j].firstChild.nodeValue;
2594 } else if ('WORD' == children[j].nodeName) {
2595 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2597 var index = this.leafNumToIndex(index);
2598 if (null != index) {
2599 //coordinates are [left, bottom, right, top, [baseline]]
2600 //we'll skip baseline for now...
2601 var coords = children[j].getAttribute('coords').split(',',4);
2602 if (4 == coords.length) {
2603 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2608 var pageName = this.getPageName(index);
2609 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2610 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2611 //TODO: remove hardcoded instance name
2612 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2615 $('#BookReaderSearchResults').append('</ul>');
2617 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2618 $('#BookReaderSearchBox').val(this.searchTerm);
2620 this.updateSearchHilites();
2623 // updateSearchHilites()
2624 //______________________________________________________________________________
2625 BookReader.prototype.updateSearchHilites = function() {
2626 if (2 == this.mode) {
2627 this.updateSearchHilites2UP();
2629 this.updateSearchHilites1UP();
2633 // showSearchHilites1UP()
2634 //______________________________________________________________________________
2635 BookReader.prototype.updateSearchHilites1UP = function() {
2637 for (var key in this.searchResults) {
2639 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2640 var result = this.searchResults[key];
2641 if (null == result.div) {
2642 result.div = document.createElement('div');
2643 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2644 //console.log('appending ' + key);
2647 width: (result.r-result.l)/this.reduce + 'px',
2648 height: (result.b-result.t)/this.reduce + 'px',
2649 left: (result.l)/this.reduce + 'px',
2650 top: (result.t)/this.reduce +'px'
2654 //console.log(key + ' not displayed');
2655 this.searchResults[key].div=null;
2661 //______________________________________________________________________________
2662 // Returns the position of the gutter (line between the page images)
2663 BookReader.prototype.twoPageGutter = function() {
2664 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2668 //______________________________________________________________________________
2669 // Returns the offset for the top of the page images
2670 BookReader.prototype.twoPageTop = function() {
2671 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2674 // twoPageCoverWidth()
2675 //______________________________________________________________________________
2676 // Returns the width of the cover div given the total page width
2677 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2678 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2681 // twoPageGetViewCenter()
2682 //______________________________________________________________________________
2683 // Returns the percentage offset into twopageview div at the center of container div
2684 // { percentageX: float, percentageY: float }
2685 BookReader.prototype.twoPageGetViewCenter = function() {
2688 var containerOffset = $('#BRcontainer').offset();
2689 var viewOffset = $('#BRtwopageview').offset();
2690 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2691 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2696 // twoPageCenterView(percentageX, percentageY)
2697 //______________________________________________________________________________
2698 // Centers the point given by percentage from left,top of twopageview
2699 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2700 if ('undefined' == typeof(percentageX)) {
2703 if ('undefined' == typeof(percentageY)) {
2707 var viewWidth = $('#BRtwopageview').width();
2708 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2709 var intoViewX = percentageX * viewWidth;
2711 var viewHeight = $('#BRtwopageview').height();
2712 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2713 var intoViewY = percentageY * viewHeight;
2715 if (viewWidth < containerClientWidth) {
2716 // Can fit width without scrollbars - center by adjusting offset
2717 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2719 // Need to scroll to center
2720 $('#BRtwopageview').css('left', 0);
2721 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2724 if (viewHeight < containerClientHeight) {
2725 // Fits with scrollbars - add offset
2726 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2728 $('#BRtwopageview').css('top', 0);
2729 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2733 // twoPageFlipAreaHeight
2734 //______________________________________________________________________________
2735 // Returns the integer height of the click-to-flip areas at the edges of the book
2736 BookReader.prototype.twoPageFlipAreaHeight = function() {
2737 return parseInt(this.twoPage.height);
2740 // twoPageFlipAreaWidth
2741 //______________________________________________________________________________
2742 // Returns the integer width of the flip areas
2743 BookReader.prototype.twoPageFlipAreaWidth = function() {
2744 var max = 100; // $$$ TODO base on view width?
2747 var width = this.twoPage.width * 0.15;
2748 return parseInt(BookReader.util.clamp(width, min, max));
2751 // twoPageFlipAreaTop
2752 //______________________________________________________________________________
2753 // Returns integer top offset for flip areas
2754 BookReader.prototype.twoPageFlipAreaTop = function() {
2755 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2758 // twoPageLeftFlipAreaLeft
2759 //______________________________________________________________________________
2760 // Left offset for left flip area
2761 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2762 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2765 // twoPageRightFlipAreaLeft
2766 //______________________________________________________________________________
2767 // Left offset for right flip area
2768 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2769 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2772 // twoPagePlaceFlipAreas
2773 //______________________________________________________________________________
2774 // Readjusts position of flip areas based on current layout
2775 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2776 // We don't set top since it shouldn't change relative to view
2777 $(this.twoPage.leftFlipArea).css({
2778 left: this.twoPageLeftFlipAreaLeft() + 'px',
2779 width: this.twoPageFlipAreaWidth() + 'px'
2781 $(this.twoPage.rightFlipArea).css({
2782 left: this.twoPageRightFlipAreaLeft() + 'px',
2783 width: this.twoPageFlipAreaWidth() + 'px'
2787 // showSearchHilites2UP()
2788 //______________________________________________________________________________
2789 BookReader.prototype.updateSearchHilites2UP = function() {
2791 for (var key in this.searchResults) {
2792 key = parseInt(key, 10);
2793 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2794 var result = this.searchResults[key];
2795 if (null == result.div) {
2796 result.div = document.createElement('div');
2797 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2798 //console.log('appending ' + key);
2801 // We calculate the reduction factor for the specific page because it can be different
2802 // for each page in the spread
2803 var height = this._getPageHeight(key);
2804 var width = this._getPageWidth(key)
2805 var reduce = this.twoPage.height/height;
2806 var scaledW = parseInt(width*reduce);
2808 var gutter = this.twoPageGutter();
2810 if ('L' == this.getPageSide(key)) {
2811 pageL = gutter-scaledW;
2815 var pageT = this.twoPageTop();
2818 width: (result.r-result.l)*reduce + 'px',
2819 height: (result.b-result.t)*reduce + 'px',
2820 left: pageL+(result.l)*reduce + 'px',
2821 top: pageT+(result.t)*reduce +'px'
2825 //console.log(key + ' not displayed');
2826 if (null != this.searchResults[key].div) {
2827 //console.log('removing ' + key);
2828 $(this.searchResults[key].div).remove();
2830 this.searchResults[key].div=null;
2835 // removeSearchHilites()
2836 //______________________________________________________________________________
2837 BookReader.prototype.removeSearchHilites = function() {
2838 for (var key in this.searchResults) {
2839 if (null != this.searchResults[key].div) {
2840 $(this.searchResults[key].div).remove();
2841 this.searchResults[key].div=null;
2847 //______________________________________________________________________________
2848 BookReader.prototype.printPage = function() {
2849 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2852 // Get print URI from current indices and mode
2853 BookReader.prototype.getPrintURI = function() {
2855 if (this.constMode2up == this.mode) {
2856 indexToPrint = this.twoPage.currentIndexL;
2858 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2861 var options = 'id=' + this.subPrefix + '&server=' + this.server + '&zip=' + this.zip
2862 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2863 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2865 if (this.constMode2up == this.mode) {
2866 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2867 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2868 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2870 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2873 return '/bookreader/print.php?' + options;
2876 /* iframe implementation
2877 BookReader.prototype.getPrintFrameContent = function(index) {
2878 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2879 // 8.5x11 so we should end up not overflowing on either paper size.
2880 var paperAspect = 8.5 / 11;
2881 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2885 // Rotate if possible and appropriate, to get larger image size on printed page
2886 if (this.canRotatePage(index)) {
2887 if (imageAspect > 1 && imageAspect > paperAspect) {
2888 // more wide than square, and more wide than paper
2890 imageAspect = 1/imageAspect;
2895 if (imageAspect > paperAspect) {
2896 // wider than paper, fit width
2897 fitAttrs = 'width="95%"';
2899 // taller than paper, fit height
2900 fitAttrs = 'height="95%"';
2903 var imageURL = this._getPageURI(index, 1, rotate);
2904 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2905 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2906 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2907 iframeStr += '</div>';
2908 iframeStr += '</body></html>';
2913 BookReader.prototype.updatePrintFrame = function(delta) {
2914 var newIndex = this.indexToPrint + delta;
2915 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2916 if (newIndex == this.indexToPrint) {
2919 this.indexToPrint = newIndex;
2920 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2921 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2926 //______________________________________________________________________________
2927 BookReader.prototype.showEmbedCode = function() {
2928 if (null != this.embedPopup) { // check if already showing
2932 this.embedPopup = document.createElement("div");
2933 $(this.embedPopup).css({
2934 position: 'absolute',
2936 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2939 border: "3px double #999999",
2941 backgroundColor: "#fff"
2942 }).appendTo('#BookReader');
2944 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2945 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>';
2946 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2947 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2949 this.embedPopup.innerHTML = htmlStr;
2950 $(this.embedPopup).find('input').bind('click', function() {
2956 //______________________________________________________________________________
2957 BookReader.prototype.autoToggle = function() {
2959 var bComingFrom1up = false;
2960 if (2 != this.mode) {
2961 bComingFrom1up = true;
2965 // Change to autofit if book is too large
2966 if (this.reduce < this.twoPageGetAutofitReduce()) {
2967 this.zoom2up('auto');
2971 if (null == this.autoTimer) {
2972 this.flipSpeed = 2000;
2974 // $$$ Draw events currently cause layout problems when they occur during animation.
2975 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2976 // we workaround for now by not triggering immediate animation in that case.
2977 // See https://bugs.launchpad.net/gnubook/+bug/328327
2978 if (('rl' == this.pageProgression) && bComingFrom1up) {
2979 // don't flip immediately -- wait until timer fires
2982 this.flipFwdToIndex();
2985 $('#BRtoolbar .play').hide();
2986 $('#BRtoolbar .pause').show();
2987 this.autoTimer=setInterval(function(){
2988 if (self.animating) {return;}
2990 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2991 self.flipBackToIndex(1); // $$$ really what we want?
2993 self.flipFwdToIndex();
3002 //______________________________________________________________________________
3003 // Stop autoplay mode, allowing animations to finish
3004 BookReader.prototype.autoStop = function() {
3005 if (null != this.autoTimer) {
3006 clearInterval(this.autoTimer);
3007 this.flipSpeed = 'fast';
3008 $('#BRtoolbar .pause').hide();
3009 $('#BRtoolbar .play').show();
3010 this.autoTimer = null;
3014 // stopFlipAnimations
3015 //______________________________________________________________________________
3016 // Immediately stop flip animations. Callbacks are triggered.
3017 BookReader.prototype.stopFlipAnimations = function() {
3019 this.autoStop(); // Clear timers
3021 // Stop animation, clear queue, trigger callbacks
3022 if (this.leafEdgeTmp) {
3023 $(this.leafEdgeTmp).stop(false, true);
3025 jQuery.each(this.prefetchedImgs, function() {
3026 $(this).stop(false, true);
3029 // And again since animations also queued in callbacks
3030 if (this.leafEdgeTmp) {
3031 $(this.leafEdgeTmp).stop(false, true);
3033 jQuery.each(this.prefetchedImgs, function() {
3034 $(this).stop(false, true);
3039 // keyboardNavigationIsDisabled(event)
3040 // - returns true if keyboard navigation should be disabled for the event
3041 //______________________________________________________________________________
3042 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3043 if (event.target.tagName == "INPUT") {
3049 // gutterOffsetForIndex
3050 //______________________________________________________________________________
3052 // Returns the gutter offset for the spread containing the given index.
3053 // This function supports RTL
3054 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3056 // To find the offset of the gutter from the middle we calculate our percentage distance
3057 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3058 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3060 // But then again for RTL it's the opposite
3061 if ('rl' == this.pageProgression) {
3069 //______________________________________________________________________________
3070 // Returns the width of the leaf edge div for the page with index given
3071 BookReader.prototype.leafEdgeWidth = function(pindex) {
3072 // $$$ could there be single pixel rounding errors for L vs R?
3073 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3074 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3076 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3080 // jumpIndexForLeftEdgePageX
3081 //______________________________________________________________________________
3082 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3083 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3084 if ('rl' != this.pageProgression) {
3085 // LTR - flipping backward
3086 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3088 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3089 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3093 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3094 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3099 // jumpIndexForRightEdgePageX
3100 //______________________________________________________________________________
3101 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3102 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3103 if ('rl' != this.pageProgression) {
3105 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3106 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3109 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3110 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3115 BookReader.prototype.initToolbar = function(mode, ui) {
3117 $("#BookReader").append("<div id='BRtoolbar'>"
3118 + "<span id='BRtoolbarbuttons' style='float: right'>"
3119 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3120 + "<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>"
3121 + "<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>"
3122 + "<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>"
3123 + "<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>"
3124 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3128 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3129 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3130 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3131 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3132 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3133 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3134 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3137 + "<span id='#BRbooktitle'>"
3138 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3142 this.updateToolbarZoom(this.reduce); // Pretty format
3144 if (ui == "embed" || ui == "touch") {
3145 $("#BookReader a.logo").attr("target","_blank");
3148 // $$$ turn this into a member variable
3149 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3151 // We build in mode 2
3154 this.bindToolbarNavHandlers(jToolbar);
3156 // Setup tooltips -- later we could load these from a file for i18n
3157 var titles = { '.logo': 'Go to Archive.org',
3158 '.zoom_in': 'Zoom in',
3159 '.zoom_out': 'Zoom out',
3160 '.one_page_mode': 'One-page view',
3161 '.two_page_mode': 'Two-page view',
3162 '.thumbnail_mode': 'Thumbnail view',
3163 '.print': 'Print this page',
3164 '.embed': 'Embed bookreader',
3165 '.book_left': 'Flip left',
3166 '.book_right': 'Flip right',
3167 '.book_up': 'Page up',
3168 '.book_down': 'Page down',
3171 '.book_top': 'First page',
3172 '.book_bottom': 'Last page'
3174 if ('rl' == this.pageProgression) {
3175 titles['.book_leftmost'] = 'Last page';
3176 titles['.book_rightmost'] = 'First page';
3178 titles['.book_leftmost'] = 'First page';
3179 titles['.book_rightmost'] = 'Last page';
3182 for (var icon in titles) {
3183 jToolbar.find(icon).attr('title', titles[icon]);
3186 // Hide mode buttons and autoplay if 2up is not available
3187 // $$$ if we end up with more than two modes we should show the applicable buttons
3188 if ( !this.canSwitchToMode(this.constMode2up) ) {
3189 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3192 // Switch to requested mode -- binds other click handlers
3193 this.switchToolbarMode(mode);
3198 // switchToolbarMode
3199 //______________________________________________________________________________
3200 // Update the toolbar for the given mode (changes navigation buttons)
3201 // $$$ we should soon split the toolbar out into its own module
3202 BookReader.prototype.switchToolbarMode = function(mode) {
3205 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3206 $('#BRtoolbar .BRtoolbarmode2').hide();
3207 $('#BRtoolbar .BRtoolbarmode3').hide();
3208 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3209 } else if (2 == mode) {
3211 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3212 $('#BRtoolbar .BRtoolbarmode1').hide();
3213 $('#BRtoolbar .BRtoolbarmode3').hide();
3214 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3217 $('#BRtoolbar .BRtoolbarzoom').hide();
3218 $('#BRtoolbar .BRtoolbarmode2').hide();
3219 $('#BRtoolbar .BRtoolbarmode1').hide();
3220 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3224 // bindToolbarNavHandlers
3225 //______________________________________________________________________________
3226 // Binds the toolbar handlers
3227 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3229 var self = this; // closure
3231 jToolbar.find('.book_left').bind('click', function(e) {
3236 jToolbar.find('.book_right').bind('click', function(e) {
3241 jToolbar.find('.book_up').bind('click', function(e) {
3242 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3250 jToolbar.find('.book_down').bind('click', function(e) {
3251 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3259 jToolbar.find('.print').bind('click', function(e) {
3264 jToolbar.find('.embed').bind('click', function(e) {
3265 self.showEmbedCode();
3269 jToolbar.find('.play').bind('click', function(e) {
3274 jToolbar.find('.pause').bind('click', function(e) {
3279 jToolbar.find('.book_top').bind('click', function(e) {
3284 jToolbar.find('.book_bottom').bind('click', function(e) {
3289 jToolbar.find('.book_leftmost').bind('click', function(e) {
3294 jToolbar.find('.book_rightmost').bind('click', function(e) {
3300 // updateToolbarZoom(reduce)
3301 //______________________________________________________________________________
3302 // Update the displayed zoom factor based on reduction factor
3303 BookReader.prototype.updateToolbarZoom = function(reduce) {
3307 // $$$ TODO preserve zoom/fit for each mode
3308 if (this.mode == this.constMode2up) {
3309 autofit = this.twoPage.autofit;
3311 autofit = this.onePage.autofit;
3315 value = autofit.slice(0,1).toUpperCase() + autofit.slice(1);
3317 value = (100 / reduce).toFixed(2);
3318 // Strip trailing zeroes and decimal if all zeroes
3319 value = value.replace(/0+$/,'');
3320 value = value.replace(/\.$/,'');
3323 $('#BRzoom').text(value);
3326 // firstDisplayableIndex
3327 //______________________________________________________________________________
3328 // Returns the index of the first visible page, dependent on the mode.
3329 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3330 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3331 BookReader.prototype.firstDisplayableIndex = function() {
3332 if (this.mode != this.constMode2up) {
3336 if ('rl' != this.pageProgression) {
3338 if (this.getPageSide(0) == 'L') {
3345 if (this.getPageSide(0) == 'R') {
3353 // lastDisplayableIndex
3354 //______________________________________________________________________________
3355 // Returns the index of the last visible page, dependent on the mode.
3356 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3357 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3358 BookReader.prototype.lastDisplayableIndex = function() {
3360 var lastIndex = this.numLeafs - 1;
3362 if (this.mode != this.constMode2up) {
3366 if ('rl' != this.pageProgression) {
3368 if (this.getPageSide(lastIndex) == 'R') {
3371 return lastIndex + 1;
3375 if (this.getPageSide(lastIndex) == 'L') {
3378 return lastIndex + 1;
3383 // shortTitle(maximumCharacters)
3385 // Returns a shortened version of the title with the maximum number of characters
3386 BookReader.prototype.shortTitle = function(maximumCharacters) {
3387 if (this.bookTitle.length < maximumCharacters) {
3388 return this.bookTitle;
3391 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3396 // Parameter related functions
3398 // updateFromParams(params)
3400 // Update ourselves from the params object.
3402 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3403 BookReader.prototype.updateFromParams = function(params) {
3404 if ('undefined' != typeof(params.mode)) {
3405 this.switchMode(params.mode);
3409 if ('undefined' != typeof(params.searchTerm)) {
3410 if (this.searchTerm != params.searchTerm) {
3411 this.search(params.searchTerm);
3415 // $$$ process /zoom
3417 // We only respect page if index is not set
3418 if ('undefined' != typeof(params.index)) {
3419 if (params.index != this.currentIndex()) {
3420 this.jumpToIndex(params.index);
3422 } else if ('undefined' != typeof(params.page)) {
3423 // $$$ this assumes page numbers are unique
3424 if (params.page != this.getPageNum(this.currentIndex())) {
3425 this.jumpToPage(params.page);
3429 // $$$ process /region
3430 // $$$ process /highlight
3433 // paramsFromFragment(urlFragment)
3435 // Returns a object with configuration parametes from a URL fragment.
3437 // E.g paramsFromFragment(window.location.hash)
3438 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3439 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3443 // For convenience we allow an initial # character (as from window.location.hash)
3444 // but don't require it
3445 if (urlFragment.substr(0,1) == '#') {
3446 urlFragment = urlFragment.substr(1);
3449 // Simple #nn syntax
3450 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3451 if ( !isNaN(oldStyleLeafNum) ) {
3452 params.index = oldStyleLeafNum;
3454 // Done processing if using old-style syntax
3458 // Split into key-value pairs
3459 var urlArray = urlFragment.split('/');
3461 for (var i = 0; i < urlArray.length; i += 2) {
3462 urlHash[urlArray[i]] = urlArray[i+1];
3466 if ('1up' == urlHash['mode']) {
3467 params.mode = this.constMode1up;
3468 } else if ('2up' == urlHash['mode']) {
3469 params.mode = this.constMode2up;
3470 } else if ('thumb' == urlHash['mode']) {
3471 params.mode = this.constModeThumb;
3475 if ('undefined' != typeof(urlHash['page'])) {
3476 // page was set -- may not be int
3477 params.page = urlHash['page'];
3480 // $$$ process /region
3481 // $$$ process /search
3483 if (urlHash['search'] != undefined) {
3484 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3487 // $$$ process /highlight
3492 // paramsFromCurrent()
3494 // Create a params object from the current parameters.
3495 BookReader.prototype.paramsFromCurrent = function() {
3499 var index = this.currentIndex();
3500 var pageNum = this.getPageNum(index);
3501 if ((pageNum === 0) || pageNum) {
3502 params.page = pageNum;
3505 params.index = index;
3506 params.mode = this.mode;
3512 if (this.searchHighlightVisible()) {
3513 params.searchTerm = this.searchTerm;
3519 // fragmentFromParams(params)
3521 // Create a fragment string from the params object.
3522 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3523 BookReader.prototype.fragmentFromParams = function(params) {
3524 var separator = '/';
3528 if ('undefined' != typeof(params.page)) {
3529 fragments.push('page', params.page);
3531 // Don't have page numbering -- use index instead
3532 fragments.push('page', 'n' + params.index);
3539 if ('undefined' != typeof(params.mode)) {
3540 if (params.mode == this.constMode1up) {
3541 fragments.push('mode', '1up');
3542 } else if (params.mode == this.constMode2up) {
3543 fragments.push('mode', '2up');
3544 } else if (params.mode == this.constModeThumb) {
3545 fragments.push('mode', 'thumb');
3547 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3552 if (params.searchTerm) {
3553 fragments.push('search', params.searchTerm);
3556 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3559 // getPageIndex(pageNum)
3561 // Returns the *highest* index the given page number, or undefined
3562 BookReader.prototype.getPageIndex = function(pageNum) {
3563 var pageIndices = this.getPageIndices(pageNum);
3565 if (pageIndices.length > 0) {
3566 return pageIndices[pageIndices.length - 1];
3572 // getPageIndices(pageNum)
3574 // Returns an array (possibly empty) of the indices with the given page number
3575 BookReader.prototype.getPageIndices = function(pageNum) {
3578 // Check for special "nXX" page number
3579 if (pageNum.slice(0,1) == 'n') {
3581 var pageIntStr = pageNum.slice(1, pageNum.length);
3582 var pageIndex = parseInt(pageIntStr);
3583 indices.push(pageIndex);
3586 // Do nothing... will run through page names and see if one matches
3591 for (i=0; i<this.numLeafs; i++) {
3592 if (this.getPageNum(i) == pageNum) {
3600 // getPageName(index)
3602 // Returns the name of the page as it should be displayed in the user interface
3603 BookReader.prototype.getPageName = function(index) {
3604 return 'Page ' + this.getPageNum(index);
3607 // updateLocationHash
3609 // Update the location hash from the current parameters. Call this instead of manually
3610 // using window.location.replace
3611 BookReader.prototype.updateLocationHash = function() {
3612 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3613 window.location.replace(newHash);
3615 // This is the variable checked in the timer. Only user-generated changes
3616 // to the URL will trigger the event.
3617 this.oldLocationHash = newHash;
3620 // startLocationPolling
3622 // Starts polling of window.location to see hash fragment changes
3623 BookReader.prototype.startLocationPolling = function() {
3624 var self = this; // remember who I am
3625 self.oldLocationHash = window.location.hash;
3627 if (this.locationPollId) {
3628 clearInterval(this.locationPollID);
3629 this.locationPollId = null;
3632 this.locationPollId = setInterval(function() {
3633 var newHash = window.location.hash;
3634 if (newHash != self.oldLocationHash) {
3635 if (newHash != self.oldUserHash) { // Only process new user hash once
3636 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3638 // Queue change if animating
3639 if (self.animating) {
3641 self.animationFinishedCallback = function() {
3642 self.updateFromParams(self.paramsFromFragment(newHash));
3644 } else { // update immediately
3645 self.updateFromParams(self.paramsFromFragment(newHash));
3647 self.oldUserHash = newHash;
3655 // Returns true if we can switch to the requested mode
3656 BookReader.prototype.canSwitchToMode = function(mode) {
3657 if (mode == this.constMode2up) {
3658 // check there are enough pages to display
3659 // $$$ this is a workaround for the mis-feature that we can't display
3660 // short books in 2up mode
3661 if (this.numLeafs < 6) {
3669 // searchHighlightVisible
3671 // Returns true if a search highlight is currently being displayed
3672 BookReader.prototype.searchHighlightVisible = function() {
3673 if (this.constMode2up == this.mode) {
3674 if (this.searchResults[this.twoPage.currentIndexL]
3675 || this.searchResults[this.twoPage.currentIndexR]) {
3679 if (this.searchResults[this.currentIndex()]) {
3688 // Returns the page width for the given index, or first or last page if out of range
3689 BookReader.prototype._getPageWidth = function(index) {
3690 // Synthesize a page width for pages not actually present in book.
3691 // May or may not be the best approach.
3692 // If index is out of range we return the width of first or last page
3693 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3694 return this.getPageWidth(index);
3699 // Returns the page height for the given index, or first or last page if out of range
3700 BookReader.prototype._getPageHeight= function(index) {
3701 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3702 return this.getPageHeight(index);
3707 // Returns the page URI or transparent image if out of range
3708 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3709 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3710 return this.imagesBaseURL + "/transparent.png";
3713 if ('undefined' == typeof(reduce)) {
3714 // reduce not passed in
3715 // $$$ this probably won't work for thumbnail mode
3716 var ratio = this.getPageHeight(index) / this.twoPage.height;
3718 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3721 } else if (ratio < 4) {
3723 } else if (ratio < 8) {
3725 } else if (ratio < 16) {
3727 } else if (ratio < 32) {
3735 return this.getPageURI(index, reduce, rotate);
3738 // Library functions
3740 disableSelect: function(jObject) {
3741 // Bind mouse handlers
3742 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3743 jObject.bind('mousedown', function(e) {
3744 // $$$ check here for right-click and don't disable. Also use jQuery style
3745 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3748 // Special hack for IE7
3749 jObject[0].onselectstart = function(e) { return false; };
3752 clamp: function(value, min, max) {
3753 return Math.min(Math.max(value, min), max);
3756 notInArray: function(value, array) {
3757 // inArray returns -1 or undefined if value not in array
3758 return ! (jQuery.inArray(value, array) >= 0);
3761 getIFrameDocument: function(iframe) {
3762 // Adapted from http://xkr.us/articles/dom/iframe-document/
3763 var outer = (iframe.contentWindow || iframe.contentDocument);
3764 return (outer.document || outer);
3767 decodeURIComponentPlus: function(value) {
3768 // Decodes a URI component and converts '+' to ' '
3769 return decodeURIComponent(value).replace(/\+/g, ' ');
3772 encodeURIComponentPlus: function(value) {
3773 // Encodes a URI component and converts ' ' to '+'
3774 return encodeURIComponent(value).replace(/%20/g, '+');
3776 // The final property here must NOT have a comma after it - IE7