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
107 // Background color for pages (e.g. when loading page image)
108 // $$$ TODO dynamically calculate based on page images
109 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
115 //______________________________________________________________________________
116 BookReader.prototype.init = function() {
118 var startIndex = undefined;
119 this.pageScale = this.reduce; // preserve current reduce
121 // Find start index and mode if set in location hash
122 var params = this.paramsFromFragment(window.location.hash);
124 if ('undefined' != typeof(params.index)) {
125 startIndex = params.index;
126 } else if ('undefined' != typeof(params.page)) {
127 startIndex = this.getPageIndex(params.page);
130 if ('undefined' == typeof(startIndex)) {
131 if ('undefined' != typeof(this.titleLeaf)) {
132 startIndex = this.leafNumToIndex(this.titleLeaf);
136 if ('undefined' == typeof(startIndex)) {
140 if ('undefined' != typeof(params.mode)) {
141 this.mode = params.mode;
144 // Set document title -- may have already been set in enclosing html for
145 // search engine visibility
146 document.title = this.shortTitle(50);
148 // Sanitize parameters
149 if ( !this.canSwitchToMode( this.mode ) ) {
150 this.mode = this.constMode1up;
153 $("#BookReader").empty();
155 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
156 $("#BookReader").append("<div id='BRcontainer'></div>");
157 $("#BRcontainer").append("<div id='BRpageview'></div>");
159 $("#BRcontainer").bind('scroll', this, function(e) {
163 this.setupKeyListeners();
164 this.startLocationPolling();
166 $(window).bind('resize', this, function(e) {
167 //console.log('resize!');
168 if (1 == e.data.mode) {
169 //console.log('centering 1page view');
170 e.data.centerPageView();
171 $('#BRpageview').empty()
172 e.data.displayedIndices = [];
173 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
175 } else if (3 == e.data.mode){
176 e.data.prepareThumbnailView();
178 //console.log('drawing 2 page view');
180 // We only need to prepare again in autofit (size of spread changes)
181 if (e.data.twoPage.autofit) {
182 e.data.prepareTwoPageView();
184 // Re-center if the scrollbars have disappeared
185 var center = e.data.twoPageGetViewCenter();
186 var doRecenter = false;
187 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
188 center.percentageX = 0.5;
191 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
192 center.percentageY = 0.5;
196 e.data.twoPageCenterView(center.percentageX, center.percentageY);
202 $('.BRpagediv1up').bind('mousedown', this, function(e) {
203 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
204 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
208 // $$$ refactor this so it's enough to set the first index and call preparePageView
209 // (get rid of mode-specific logic at this point)
210 if (1 == this.mode) {
211 this.firstIndex = startIndex;
212 this.prepareOnePageView();
213 this.jumpToIndex(startIndex);
214 } else if (3 == this.mode) {
215 this.firstIndex = startIndex;
216 this.prepareThumbnailView();
217 this.jumpToIndex(startIndex);
219 //this.resizePageView();
221 this.displayedIndices=[0];
222 this.firstIndex = startIndex;
223 this.displayedIndices = [this.firstIndex];
224 //console.log('titleLeaf: %d', this.titleLeaf);
225 //console.log('displayedIndices: %s', this.displayedIndices);
226 this.prepareTwoPageView();
229 // Enact other parts of initial params
230 this.updateFromParams(params);
233 BookReader.prototype.setupKeyListeners = function() {
246 // We use document here instead of window to avoid a bug in jQuery on IE7
247 $(document).keydown(function(e) {
249 // Keyboard navigation
250 if (!self.keyboardNavigationIsDisabled(e)) {
254 // In 1up mode page scrolling is handled by browser
255 if (2 == self.mode) {
262 if (2 == self.mode) {
276 if (2 == self.mode) {
282 if (2 == self.mode) {
293 //______________________________________________________________________________
294 BookReader.prototype.drawLeafs = function() {
295 if (1 == this.mode) {
296 this.drawLeafsOnePage();
297 } else if (3 == this.mode) {
298 this.drawLeafsThumbnail();
300 this.drawLeafsTwoPage();
305 // bindGestures(jElement)
306 //______________________________________________________________________________
307 BookReader.prototype.bindGestures = function(jElement) {
309 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
311 if (e.originalEvent.scale > 1.5) {
313 } else if (e.originalEvent.scale < 0.6) {
320 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
321 //console.log('setting handler');
322 //console.log(element.tagName);
324 $(element).unbind('tap').bind('tap', data, function(e) {
329 // drawLeafsOnePage()
330 //______________________________________________________________________________
331 BookReader.prototype.drawLeafsOnePage = function() {
332 //alert('drawing leafs!');
336 var scrollTop = $('#BRcontainer').attr('scrollTop');
337 var scrollBottom = scrollTop + $('#BRcontainer').height();
338 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
340 var indicesToDisplay = [];
345 for (i=0; i<this.numLeafs; i++) {
346 var height = parseInt(this._getPageHeight(i)/this.reduce);
348 leafBottom += height;
349 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
350 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
351 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
352 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
353 if (topInView | bottomInView | middleInView) {
354 //console.log('displayed: ' + this.displayedIndices);
355 //console.log('to display: ' + i);
356 indicesToDisplay.push(i);
358 leafTop += height +10;
362 var firstIndexToDraw = indicesToDisplay[0];
363 this.firstIndex = firstIndexToDraw;
365 // Update hash, but only if we're currently displaying a leaf
366 // Hack that fixes #365790
367 if (this.displayedIndices.length > 0) {
368 this.updateLocationHash();
371 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
373 indicesToDisplay.unshift(firstIndexToDraw);
376 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
377 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
378 indicesToDisplay.push(lastIndexToDraw+1);
383 for (i=0; i<firstIndexToDraw; i++) {
384 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
387 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
388 var viewWidth = $('#BRcontainer').attr('scrollWidth');
391 for (i=0; i<indicesToDisplay.length; i++) {
392 var index = indicesToDisplay[i];
393 var height = parseInt(this._getPageHeight(index)/this.reduce);
395 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
396 var width = parseInt(this._getPageWidth(index)/this.reduce);
397 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
398 var div = document.createElement("div");
399 div.className = 'BRpagediv1up';
400 div.id = 'pagediv'+index;
401 div.style.position = "absolute";
402 $(div).css('top', leafTop + 'px');
403 var left = (viewWidth-width)>>1;
404 if (left<0) left = 0;
405 $(div).css('left', left+'px');
406 $(div).css('width', width+'px');
407 $(div).css('height', height+'px');
408 //$(div).text('loading...');
410 $('#BRpageview').append(div);
412 var img = document.createElement("img");
413 img.src = this._getPageURI(index, this.reduce, 0);
414 $(img).css('width', width+'px');
415 $(img).css('height', height+'px');
419 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
422 leafTop += height +10;
426 for (i=0; i<this.displayedIndices.length; i++) {
427 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
428 var index = this.displayedIndices[i];
429 //console.log('Removing leaf ' + index);
430 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
431 $('#pagediv'+index).remove();
433 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
437 this.displayedIndices = indicesToDisplay.slice();
438 this.updateSearchHilites();
440 if (null != this.getPageNum(firstIndexToDraw)) {
441 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
443 $("#BRpagenum").val('');
446 this.updateToolbarZoom(this.reduce);
450 // drawLeafsThumbnail()
451 //______________________________________________________________________________
452 // If seekIndex is defined, the view will be drawn with that page visible (without any
453 // animated scrolling)
454 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
455 //alert('drawing leafs!');
458 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
460 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
474 // Will be set to top of requested seek index, if set
477 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
478 for (i=0; i<this.numLeafs; i++) {
479 leafWidth = this.thumbWidth;
480 if (rightPos + (leafWidth + this.padding) > viewWidth){
486 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
487 if (leafMap[currentRow].leafs===undefined) {
488 leafMap[currentRow].leafs = [];
489 leafMap[currentRow].height = 0;
490 leafMap[currentRow].top = 0;
492 leafMap[currentRow].leafs[leafIndex] = {};
493 leafMap[currentRow].leafs[leafIndex].num = i;
494 leafMap[currentRow].leafs[leafIndex].left = rightPos;
496 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
497 if (leafHeight > leafMap[currentRow].height) {
498 leafMap[currentRow].height = leafHeight;
500 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
501 rightPos += leafWidth + this.padding;
502 if (rightPos > maxRight) { maxRight = rightPos; }
505 if (i == seekIndex) {
506 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
510 // reset the bottom position based on thumbnails
511 $('#BRpageview').height(bottomPos);
513 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
515 // If seekTop is defined, seeking was requested and target found
516 if (typeof(seekTop) != 'undefined') {
517 $('#BRcontainer').scrollTop( seekTop );
520 var scrollTop = $('#BRcontainer').attr('scrollTop');
521 var scrollBottom = scrollTop + $('#BRcontainer').height();
525 var rowsToDisplay = [];
527 // Visible leafs with least/greatest index
528 var leastVisible = this.numLeafs - 1;
531 // Determine the thumbnails in view
532 for (i=0; i<leafMap.length; i++) {
533 leafBottom += this.padding + leafMap[i].height;
534 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
535 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
536 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
537 if (topInView | bottomInView | middleInView) {
538 //console.log('row to display: ' + j);
539 rowsToDisplay.push(i);
540 if (leafMap[i].leafs[0].num < leastVisible) {
541 leastVisible = leafMap[i].leafs[0].num;
543 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
544 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
547 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
548 leafTop = leafBottom;
551 // create a buffer of preloaded rows before and after the visible rows
552 var firstRow = rowsToDisplay[0];
553 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
554 for (i=1; i<this.thumbRowBuffer+1; i++) {
555 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
557 for (i=1; i<this.thumbRowBuffer+1; i++) {
558 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
561 // Create the thumbnail divs and images (lazy loaded)
570 for (i=0; i<rowsToDisplay.length; i++) {
571 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
572 row = rowsToDisplay[i];
574 for (j=0; j<leafMap[row].leafs.length; j++) {
576 leaf = leafMap[row].leafs[j].num;
578 leafWidth = this.thumbWidth;
579 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
580 leafTop = leafMap[row].top;
581 left = leafMap[row].leafs[index].left + pageViewBuffer;
582 if ('rl' == this.pageProgression){
583 left = viewWidth - leafWidth - left;
586 div = document.createElement("div");
587 div.id = 'pagediv'+leaf;
588 div.style.position = "absolute";
589 div.className = "BRpagedivthumb";
591 left += this.padding;
592 $(div).css('top', leafTop + 'px');
593 $(div).css('left', left+'px');
594 $(div).css('width', leafWidth+'px');
595 $(div).css('height', leafHeight+'px');
596 //$(div).text('loading...');
598 // link to page in single page mode
599 link = document.createElement("a");
600 $(link).data('leaf', leaf);
601 $(link).bind('tap', function(event) {
602 self.firstIndex = $(this).data('leaf');
603 self.switchMode(self.constMode1up);
604 event.preventDefault();
607 // $$$ we don't actually go to this URL (click is handled in handler above)
608 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
611 $('#BRpageview').append(div);
613 img = document.createElement("img");
614 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
616 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
617 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
618 .addClass('BRlazyload')
619 // Store the URL of the image that will replace this one
620 .data('srcURL', this._getPageURI(leaf, thumbReduce));
622 //console.log('displaying thumbnail: ' + leaf);
627 // Remove thumbnails that are not to be displayed
629 for (i=0; i<this.displayedRows.length; i++) {
630 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
631 row = this.displayedRows[i];
633 // $$$ Safari doesn't like the comprehension
634 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
635 //console.log('Removing row ' + row + ' ' + rowLeafs);
637 for (k=0; k<leafMap[row].leafs.length; k++) {
638 index = leafMap[row].leafs[k].num;
639 //console.log('Removing leaf ' + index);
640 $('#pagediv'+index).remove();
644 var mRow = this.displayedRows[i];
645 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
646 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
651 // Update which page is considered current to make sure a visible page is the current one
652 var currentIndex = this.currentIndex();
653 // console.log('current ' + currentIndex);
654 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
655 if (currentIndex < leastVisible) {
656 this.setCurrentIndex(leastVisible);
657 } else if (currentIndex > mostVisible) {
658 this.setCurrentIndex(mostVisible);
661 this.displayedRows = rowsToDisplay.slice();
663 // Update hash, but only if we're currently displaying a leaf
664 // Hack that fixes #365790
665 if (this.displayedRows.length > 0) {
666 this.updateLocationHash();
669 // remove previous highlights
670 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
672 // highlight current page
673 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
675 this.lazyLoadThumbnails();
677 // Update page number box. $$$ refactor to function
678 if (null !== this.getPageNum(this.currentIndex())) {
679 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
681 $("#BRpagenum").val('');
684 this.updateToolbarZoom(this.reduce);
687 BookReader.prototype.lazyLoadThumbnails = function() {
689 // console.log('lazy load');
691 // We check the complete property since load may not be fired if loading from the cache
692 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
694 var loading = $('.BRlazyloading').length;
695 var toLoad = this.thumbMaxLoading - loading;
697 // console.log(' ' + loading + ' thumbnails loading');
698 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
703 // $$$ TODO load those near top (but not beyond) page view first
704 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
705 self.lazyLoadImage(this);
710 BookReader.prototype.lazyLoadImage = function (dummyImage) {
711 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
713 var img = new Image();
717 .addClass('BRlazyloading')
718 .one('load', function() {
719 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
721 $(this).removeClass('BRlazyloading');
723 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
724 // we call the function after a slight delay. Also the img.complete property
725 // is not yet set in IE8 inside this onload handler
726 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
728 .one('error', function() {
729 // Remove class so we no longer count as loading
730 $(this).removeClass('BRlazyloading');
732 .attr( { width: $(dummyImage).width(),
733 height: $(dummyImage).height(),
734 src: $(dummyImage).data('srcURL')
737 // replace with the new img
738 $(dummyImage).before(img).remove();
740 img = null; // tidy up closure
744 // drawLeafsTwoPage()
745 //______________________________________________________________________________
746 BookReader.prototype.drawLeafsTwoPage = function() {
747 var scrollTop = $('#BRtwopageview').attr('scrollTop');
748 var scrollBottom = scrollTop + $('#BRtwopageview').height();
750 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
752 var indexL = this.twoPage.currentIndexL;
754 var heightL = this._getPageHeight(indexL);
755 var widthL = this._getPageWidth(indexL);
757 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
758 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
759 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
760 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
761 //console.log(leafEdgeWidthL);
763 var middle = this.twoPage.middle; // $$$ getter instead?
764 var top = this.twoPageTop();
765 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
767 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
768 this.twoPage.gutter = this.twoPageGutter();
770 this.prefetchImg(indexL);
771 $(this.prefetchedImgs[indexL]).css({
772 position: 'absolute',
773 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
776 backgroundColor: this.getPageBackgroundColor(indexL),
777 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
778 width: this.twoPage.scaledWL + 'px',
779 borderRight: '1px solid black',
781 }).appendTo('#BRtwopageview');
783 var indexR = this.twoPage.currentIndexR;
784 var heightR = this._getPageHeight(indexR);
785 var widthR = this._getPageWidth(indexR);
787 // $$$ should use getwidth2up?
788 //var scaledWR = this.twoPage.height*widthR/heightR;
789 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
790 this.prefetchImg(indexR);
791 $(this.prefetchedImgs[indexR]).css({
792 position: 'absolute',
793 left: this.twoPage.gutter+'px',
796 backgroundColor: this.getPageBackgroundColor(indexR),
797 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
798 width: this.twoPage.scaledWR + 'px',
799 borderLeft: '1px solid black',
801 }).appendTo('#BRtwopageview');
804 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
805 this.setMouseHandlers2UP();
806 this.twoPageSetCursor();
808 this.updatePageNumBox2UP();
809 this.updateToolbarZoom(this.reduce);
811 // this.twoPagePlaceFlipAreas(); // No longer used
815 // updatePageNumBox2UP
816 //______________________________________________________________________________
817 BookReader.prototype.updatePageNumBox2UP = function() {
818 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
819 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
821 $("#BRpagenum").val('');
823 this.updateLocationHash();
827 //______________________________________________________________________________
828 BookReader.prototype.loadLeafs = function() {
832 if (null == this.timer) {
833 this.timer=setTimeout(function(){self.drawLeafs()},250);
835 clearTimeout(this.timer);
836 this.timer=setTimeout(function(){self.drawLeafs()},250);
842 // Pass 1 to zoom in, anything else to zoom out
843 //______________________________________________________________________________
844 BookReader.prototype.zoom = function(direction) {
846 case this.constMode1up:
847 if (direction == 1) {
849 return this.zoom1up('in');
851 return this.zoom1up('out');
854 case this.constMode2up:
855 if (direction == 1) {
857 return this.zoom2up('in');
859 return this.zoom2up('out');
862 case this.constModeThumb:
863 // XXX update zoomThumb for named directions
864 return this.zoomThumb(direction);
870 //______________________________________________________________________________
871 BookReader.prototype.zoom1up = function(direction) {
873 if (2 == this.mode) { //can only zoom in 1-page mode
878 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
879 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
880 this.autofit = reduceFactor.autofit;
882 this.pageScale = this.reduce; // preserve current reduce
883 this.resizePageView();
885 $('#BRpageview').empty()
886 this.displayedIndices = [];
889 this.updateToolbarZoom(this.reduce);
891 // Recalculate search hilites
892 this.removeSearchHilites();
893 this.updateSearchHilites();
898 //______________________________________________________________________________
899 BookReader.prototype.resizePageView = function() {
901 // $$$ This code assumes 1up mode
902 // e.g. does not preserve position in thumbnail mode
903 // See http://bugs.launchpad.net/bookreader/+bug/552972
906 case this.constMode1up:
907 case this.constMode2up:
908 this.resizePageView1up();
910 case this.constModeThumb:
911 this.prepareThumbnailView( this.currentIndex() );
914 alert('Resize not implemented for this mode');
918 BookReader.prototype.resizePageView1up = function() {
921 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
922 var viewWidth = $('#BRcontainer').attr('clientWidth');
924 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
925 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
926 var oldPageViewHeight = $('#BRpageview').height();
927 var oldPageViewWidth = $('#BRpageview').width();
929 var oldCenterY = this.centerY1up();
930 var oldCenterX = this.centerX1up();
932 if (0 != oldPageViewHeight) {
933 var scrollRatio = oldCenterY / oldPageViewHeight;
938 // Recalculate 1up reduction factors
939 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
940 $('#BRcontainer').attr('clientHeight') );
941 // Update current reduce (if in autofit)
942 // this.onePageUpdateReduce(); // XXX
944 for (i=0; i<this.numLeafs; i++) {
945 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
946 var width = parseInt(this._getPageWidth(i)/this.reduce);
947 if (width>viewWidth) viewWidth=width;
949 $('#BRpageview').height(viewHeight);
950 $('#BRpageview').width(viewWidth);
952 var newCenterY = scrollRatio*viewHeight;
953 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
954 $('#BRcontainer').attr('scrollTop', newTop);
956 // We use clientWidth here to avoid miscalculating due to scroll bar
957 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
958 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
959 newLeft = Math.max(newLeft, 0);
960 $('#BRcontainer').attr('scrollLeft', newLeft);
961 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
963 //this.centerPageView();
966 this.removeSearchHilites();
967 this.updateSearchHilites();
972 //______________________________________________________________________________
973 // Returns the current offset of the viewport center in scaled document coordinates.
974 BookReader.prototype.centerX1up = function() {
976 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
977 centerX = $('#BRpageview').width();
979 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
981 centerX = Math.floor(centerX);
986 //______________________________________________________________________________
987 // Returns the current offset of the viewport center in scaled document coordinates.
988 BookReader.prototype.centerY1up = function() {
989 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
990 return Math.floor(centerY);
994 //______________________________________________________________________________
995 BookReader.prototype.centerPageView = function() {
997 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
998 var clientWidth = $('#BRcontainer').attr('clientWidth');
999 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1000 if (scrollWidth > clientWidth) {
1001 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1006 // zoom2up(direction)
1007 //______________________________________________________________________________
1008 BookReader.prototype.zoom2up = function(direction) {
1010 // Hard stop autoplay
1011 this.stopFlipAnimations();
1013 // Recalculate autofit factors
1014 this.twoPageCalculateReductionFactors();
1016 // Get new zoom state
1017 var reductionFactor = this.nextReduce(this.reduce, direction, this.twoPage.reductionFactors);
1018 if ((this.reduce == reductionFactor.reduce) && (this.twoPage.autofit == reductionFactor.autofit)) {
1022 this.twoPage.autofit = reductionFactor.autofit;
1023 this.reduce = reductionFactor.reduce;
1024 this.pageScale = this.reduce; // preserve current reduce
1026 // Preserve view center position
1027 var oldCenter = this.twoPageGetViewCenter();
1029 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1030 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1031 if (1 == direction) {
1032 for (var img in this.prefetchedImgs) {
1033 delete this.prefetchedImgs[img];
1037 // Prepare view with new center to minimize visual glitches
1038 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1041 BookReader.prototype.zoomThumb = function(direction) {
1042 var oldColumns = this.thumbColumns;
1043 switch (direction) {
1045 this.thumbColumns += 1;
1048 this.thumbColumns -= 1;
1053 if (this.thumbColumns < 2) {
1054 this.thumbColumns = 2;
1055 } else if (this.thumbColumns > 8) {
1056 this.thumbColumns = 8;
1059 if (this.thumbColumns != oldColumns) {
1060 this.prepareThumbnailView();
1064 // Returns the width per thumbnail to display the requested number of columns
1065 // Note: #BRpageview must already exist since its width is used to calculate the
1067 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1068 var padding = (thumbnailColumns + 1) * this.padding;
1069 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1070 return parseInt(width);
1073 // quantizeReduce(reduce)
1074 //______________________________________________________________________________
1075 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1076 BookReader.prototype.quantizeReduce = function(reduce) {
1077 var quantized = this.reductionFactors[0].reduce;
1078 var distance = Math.abs(reduce - quantized);
1079 for (var i = 1; i < this.reductionFactors.length; i++) {
1080 newDistance = Math.abs(reduce - this.reductionFactors[i].reduce);
1081 if (newDistance < distance) {
1082 distance = newDistance;
1083 quantized = this.reductionFactors[i].reduce;
1090 // reductionFactors should be array of sorted reduction factors
1091 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1092 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1094 // XXX add 'closest', to replace quantize function
1096 if (direction == 'in') {
1097 var newReduceIndex = 0;
1099 for (var i = 1; i < reductionFactors.length; i++) {
1100 if (reductionFactors[i].reduce < currentReduce) {
1104 return reductionFactors[newReduceIndex];
1106 } else if (direction == 'out') { // zoom out
1107 var lastIndex = reductionFactors.length - 1;
1108 var newReduceIndex = lastIndex;
1110 for (var i = lastIndex; i >= 0; i--) {
1111 if (reductionFactors[i].reduce > currentReduce) {
1115 return reductionFactors[newReduceIndex];
1118 // Asked for specific autofit mode
1119 for (var i = 0; i < reductionFactors.length; i++) {
1120 if (reductionFactors[i].autofit == direction) {
1121 return reductionFactors[i];
1125 alert('Could not find reduction factor for direction ' + direction);
1126 return reductionFactors[0];
1130 BookReader.prototype._reduceSort = function(a, b) {
1131 return a.reduce - b.reduce;
1135 //______________________________________________________________________________
1136 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1137 BookReader.prototype.jumpToPage = function(pageNum) {
1139 var pageIndex = this.getPageIndex(pageNum);
1141 if ('undefined' != typeof(pageIndex)) {
1144 this.jumpToIndex(pageIndex);
1145 $('#BRcontainer').attr('scrollTop', leafTop);
1154 //______________________________________________________________________________
1155 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1157 if (2 == this.mode) {
1160 // By checking against min/max we do nothing if requested index
1162 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1163 this.flipBackToIndex(index);
1164 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1165 this.flipFwdToIndex(index);
1168 } else if (3 == this.mode) {
1169 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1179 for (i=0; i<(index+1); i++) {
1180 leafWidth = this.thumbWidth;
1181 if (rightPos + (leafWidth + this.padding) > viewWidth){
1187 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1188 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1189 if (leafIndex==0) { leafTop = bottomPos; }
1190 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1191 rightPos += leafWidth + this.padding;
1194 this.firstIndex=index;
1195 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1198 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1205 for (i=0; i<index; i++) {
1206 h = parseInt(this._getPageHeight(i)/this.reduce);
1207 leafTop += h + this.padding;
1211 //console.log('pageY ' + pageY);
1212 var offset = parseInt( (pageY) / this.reduce);
1213 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1214 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1219 var offset = parseInt( (pageX) / this.reduce);
1220 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1224 //$('#BRcontainer').attr('scrollTop', leafTop);
1225 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1231 //______________________________________________________________________________
1232 BookReader.prototype.switchMode = function(mode) {
1234 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1236 if (mode == this.mode) {
1240 if (!this.canSwitchToMode(mode)) {
1245 this.removeSearchHilites();
1248 this.switchToolbarMode(mode);
1250 // reinstate scale if moving from thumbnail view
1251 if (this.pageScale != this.reduce) {
1252 this.reduce = this.pageScale;
1255 // $$$ TODO preserve center of view when switching between mode
1256 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1259 this.reduce = this.quantizeReduce(this.reduce);
1260 this.prepareOnePageView();
1261 } else if (3 == mode) {
1262 this.reduce = this.quantizeReduce(this.reduce);
1263 this.prepareThumbnailView();
1265 // $$$ why don't we save autofit?
1266 this.twoPage.autofit = false; // Take zoom level from other mode
1267 this.reduce = this.quantizeReduce(this.reduce);
1268 this.prepareTwoPageView();
1269 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1274 //prepareOnePageView()
1275 //______________________________________________________________________________
1276 BookReader.prototype.prepareOnePageView = function() {
1278 // var startLeaf = this.displayedIndices[0];
1279 var startLeaf = this.currentIndex();
1281 $('#BRcontainer').empty();
1282 $('#BRcontainer').css({
1283 overflowY: 'scroll',
1287 $("#BRcontainer").append("<div id='BRpageview'></div>");
1289 // Attaches to first child - child must be present
1290 $('#BRcontainer').dragscrollable();
1291 this.bindGestures($('#BRcontainer'));
1293 // $$$ keep select enabled for now since disabling it breaks keyboard
1294 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1295 // BookReader.util.disableSelect($('#BRpageview'));
1297 this.resizePageView();
1299 this.jumpToIndex(startLeaf);
1300 this.displayedIndices = [];
1302 this.drawLeafsOnePage();
1305 //prepareThumbnailView()
1306 //______________________________________________________________________________
1307 BookReader.prototype.prepareThumbnailView = function() {
1309 $('#BRcontainer').empty();
1310 $('#BRcontainer').css({
1311 overflowY: 'scroll',
1315 $("#BRcontainer").append("<div id='BRpageview'></div>");
1317 $('#BRcontainer').dragscrollable();
1318 this.bindGestures($('#BRcontainer'));
1320 // $$$ keep select enabled for now since disabling it breaks keyboard
1321 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1322 // BookReader.util.disableSelect($('#BRpageview'));
1324 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1325 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1327 this.displayedRows = [];
1329 // Draw leafs with current index directly in view (no animating to the index)
1330 this.drawLeafsThumbnail( this.currentIndex() );
1334 // prepareTwoPageView()
1335 //______________________________________________________________________________
1336 // Some decisions about two page view:
1338 // Both pages will be displayed at the same height, even if they were different physical/scanned
1339 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1340 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1341 // aspect ratio to determine the height.
1343 // The two page view div is resized to keep the middle of the book in the middle of the div
1344 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1345 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1346 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1347 $('#BRcontainer').empty();
1348 $('#BRcontainer').css('overflow', 'auto');
1350 // We want to display two facing pages. We may be missing
1351 // one side of the spread because it is the first/last leaf,
1352 // foldouts, missing pages, etc
1354 //var targetLeaf = this.displayedIndices[0];
1355 var targetLeaf = this.firstIndex;
1357 if (targetLeaf < this.firstDisplayableIndex()) {
1358 targetLeaf = this.firstDisplayableIndex();
1361 if (targetLeaf > this.lastDisplayableIndex()) {
1362 targetLeaf = this.lastDisplayableIndex();
1365 //this.twoPage.currentIndexL = null;
1366 //this.twoPage.currentIndexR = null;
1367 //this.pruneUnusedImgs();
1369 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1370 this.twoPage.currentIndexL = currentSpreadIndices[0];
1371 this.twoPage.currentIndexR = currentSpreadIndices[1];
1372 this.firstIndex = this.twoPage.currentIndexL;
1374 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1376 this.pruneUnusedImgs();
1377 this.prefetch(); // Preload images or reload if scaling has changed
1379 //console.dir(this.twoPage);
1381 // Add the two page view
1382 // $$$ Can we get everything set up and then append?
1383 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1385 // Attaches to first child, so must come after we add the page view
1386 $('#BRcontainer').dragscrollable();
1387 this.bindGestures($('#BRcontainer'));
1389 // $$$ calculate first then set
1390 $('#BRtwopageview').css( {
1391 height: this.twoPage.totalHeight + 'px',
1392 width: this.twoPage.totalWidth + 'px',
1393 position: 'absolute'
1396 // If there will not be scrollbars (e.g. when zooming out) we center the book
1397 // since otherwise the book will be stuck off-center
1398 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1399 centerPercentageX = 0.5;
1401 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1402 centerPercentageY = 0.5;
1405 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1407 this.twoPage.coverDiv = document.createElement('div');
1408 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1409 width: this.twoPage.bookCoverDivWidth + 'px',
1410 height: this.twoPage.bookCoverDivHeight+'px',
1411 visibility: 'visible',
1412 position: 'absolute',
1413 left: this.twoPage.bookCoverDivLeft + 'px',
1414 top: this.twoPage.bookCoverDivTop+'px',
1415 }).appendTo('#BRtwopageview');
1417 this.leafEdgeR = document.createElement('div');
1418 this.leafEdgeR.className = 'BRleafEdgeR';
1419 $(this.leafEdgeR).css({
1420 width: this.twoPage.leafEdgeWidthR + 'px',
1421 height: this.twoPage.height-1 + 'px',
1422 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1423 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1424 }).appendTo('#BRtwopageview');
1426 this.leafEdgeL = document.createElement('div');
1427 this.leafEdgeL.className = 'BRleafEdgeL';
1428 $(this.leafEdgeL).css({
1429 width: this.twoPage.leafEdgeWidthL + 'px',
1430 height: this.twoPage.height-1 + 'px',
1431 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1432 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1433 }).appendTo('#BRtwopageview');
1435 div = document.createElement('div');
1436 $(div).attr('id', 'BRbookspine').css({
1437 width: this.twoPage.bookSpineDivWidth+'px',
1438 height: this.twoPage.bookSpineDivHeight+'px',
1439 left: this.twoPage.bookSpineDivLeft+'px',
1440 top: this.twoPage.bookSpineDivTop+'px'
1441 }).appendTo('#BRtwopageview');
1443 var self = this; // for closure
1445 /* Flip areas no longer used
1446 this.twoPage.leftFlipArea = document.createElement('div');
1447 this.twoPage.leftFlipArea.className = 'BRfliparea';
1448 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1450 width: this.twoPageFlipAreaWidth() + 'px',
1451 height: this.twoPageFlipAreaHeight() + 'px',
1452 position: 'absolute',
1453 left: this.twoPageLeftFlipAreaLeft() + 'px',
1454 top: this.twoPageFlipAreaTop() + 'px',
1457 }).bind('click', function(e) {
1459 }).bind('mousedown', function(e) {
1461 }).appendTo('#BRtwopageview');
1463 this.twoPage.rightFlipArea = document.createElement('div');
1464 this.twoPage.rightFlipArea.className = 'BRfliparea';
1465 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1467 width: this.twoPageFlipAreaWidth() + 'px',
1468 height: this.twoPageFlipAreaHeight() + 'px',
1469 position: 'absolute',
1470 left: this.twoPageRightFlipAreaLeft() + 'px',
1471 top: this.twoPageFlipAreaTop() + 'px',
1474 }).bind('click', function(e) {
1476 }).bind('mousedown', function(e) {
1478 }).appendTo('#BRtwopageview');
1481 this.prepareTwoPagePopUp();
1483 this.displayedIndices = [];
1485 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1486 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1488 this.drawLeafsTwoPage();
1489 this.updateToolbarZoom(this.reduce);
1493 this.removeSearchHilites();
1494 this.updateSearchHilites();
1498 // prepareTwoPagePopUp()
1500 // This function prepares the "View Page n" popup that shows while the mouse is
1501 // over the left/right "stack of sheets" edges. It also binds the mouse
1502 // events for these divs.
1503 //______________________________________________________________________________
1504 BookReader.prototype.prepareTwoPagePopUp = function() {
1506 this.twoPagePopUp = document.createElement('div');
1507 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1508 $(this.twoPagePopUp).css({
1510 }).appendTo('#BRcontainer');
1511 $(this.twoPagePopUp).hide();
1513 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1514 $(e.data.twoPagePopUp).show();
1517 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1518 $(e.data.twoPagePopUp).hide();
1521 $(this.leafEdgeL).bind('click', this, function(e) {
1523 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1524 e.data.jumpToIndex(jumpIndex);
1527 $(this.leafEdgeR).bind('click', this, function(e) {
1529 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1530 e.data.jumpToIndex(jumpIndex);
1533 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1535 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1536 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1538 // $$$ TODO: Make sure popup is positioned so that it is in view
1539 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1540 $(e.data.twoPagePopUp).css({
1541 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1542 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1546 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1548 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1549 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1551 // $$$ TODO: Make sure popup is positioned so that it is in view
1552 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1553 $(e.data.twoPagePopUp).css({
1554 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1555 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1560 // calculateSpreadSize()
1561 //______________________________________________________________________________
1562 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1563 // this.twoPage.currentIndexR
1564 // This function sets this.twoPage.height, twoPage.width
1566 BookReader.prototype.calculateSpreadSize = function() {
1568 var firstIndex = this.twoPage.currentIndexL;
1569 var secondIndex = this.twoPage.currentIndexR;
1570 //console.log('first page is ' + firstIndex);
1572 // Calculate page sizes and total leaf width
1574 if ( this.twoPage.autofit) {
1575 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1577 // set based on reduction factor
1578 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1581 // Both pages together
1582 this.twoPage.height = spreadSize.height;
1583 this.twoPage.width = spreadSize.width;
1586 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1587 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1590 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1591 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1592 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1596 // The width of the book cover div. The combined width of both pages, twice the width
1597 // of the book cover internal padding (2*10) and the page edges
1598 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1599 // The height of the book cover div
1600 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1603 // We calculate the total width and height for the div so that we can make the book
1605 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1606 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1607 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1608 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1609 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1610 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1612 // We want to minimize the unused space in two-up mode (maximize the amount of page
1613 // shown). We give width to the leaf edges and these widths change (though the sum
1614 // of the two remains constant) as we flip through the book. With the book
1615 // cover centered and fixed in the BRcontainer div the page images will meet
1616 // at the "gutter" which is generally offset from the center.
1617 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1618 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1620 // The left edge of the book cover moves depending on the width of the pages
1621 // $$$ change to getter
1622 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1623 // The top edge of the book cover stays a fixed distance from the top
1624 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1627 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1628 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1629 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1632 this.reduce = spreadSize.reduce; // $$$ really set this here?
1635 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1638 // We check which page is closest to a "normal" page and use that to set the height
1639 // for both pages. This means that foldouts and other odd size pages will be displayed
1640 // smaller than the nominal zoom amount.
1641 var canon5Dratio = 1.5;
1644 height: this._getPageHeight(firstIndex),
1645 width: this._getPageWidth(firstIndex)
1649 height: this._getPageHeight(secondIndex),
1650 width: this._getPageWidth(secondIndex)
1653 var firstIndexRatio = first.height / first.width;
1654 var secondIndexRatio = second.height / second.width;
1655 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1658 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1659 ratio = firstIndexRatio;
1660 //console.log('using firstIndexRatio ' + ratio);
1662 ratio = secondIndexRatio;
1663 //console.log('using secondIndexRatio ' + ratio);
1666 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1667 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1668 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1670 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1671 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1673 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1674 ideal.width -= 10; // $$$ fudge factor
1675 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1676 ideal.height -= 20; // fudge factor
1677 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1679 if (ideal.height/ratio <= ideal.width) {
1681 ideal.width = parseInt(ideal.height/ratio);
1684 ideal.height = parseInt(ideal.width*ratio);
1687 // $$$ check this logic with large spreads
1688 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1693 // getSpreadSizeFromReduce()
1694 //______________________________________________________________________________
1695 // Returns the spread size calculated from the reduction factor for the given pages
1696 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1697 var spreadSize = {};
1698 // $$$ Scale this based on reduce?
1699 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1700 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1701 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1703 // $$$ Possibly incorrect -- we should make height "dominant"
1704 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1705 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1706 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1707 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1708 spreadSize.reduce = reduce;
1713 // twoPageGetAutofitReduce()
1714 //______________________________________________________________________________
1715 // Returns the current ideal reduction factor
1716 BookReader.prototype.twoPageGetAutofitReduce = function() {
1717 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1718 return spreadSize.reduce;
1721 BookReader.prototype.onePageGetAutofitWidth = function() {
1722 var widthPadding = 50;
1723 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1726 BookReader.prototype.onePageGetAutofitHeight = function() {
1727 var heightPadding = 10;
1728 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - heightPadding * 2);
1731 BookReader.prototype.getMedianPageSize = function() {
1732 if (this._medianPageSize) {
1733 return this._medianPageSize;
1736 // A little expensive but we just do it once
1739 for (var i = 0; i < this.numLeafs; i++) {
1740 widths.push(this.getPageWidth(i));
1741 heights.push(this.getPageHeight(i));
1747 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1748 return this._medianPageSize;
1751 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1752 // the autofit reduction factors.
1753 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1754 this.onePage.reductionFactors = this.reductionFactors.concat(
1756 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1757 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1759 this.onePage.reductionFactors.sort(this._reduceSort);
1762 BookReader.prototype.twoPageCalculateReductionFactors = function() {
1763 this.twoPage.reductionFactors = this.reductionFactors.concat(
1765 { reduce: this.getIdealSpreadSize( this.twoPage.currentIndexL, this.twoPage.currentIndexR ).reduce,
1768 this.twoPage.reductionFactors.sort(this._reduceSort);
1771 // twoPageSetCursor()
1772 //______________________________________________________________________________
1773 // Set the cursor for two page view
1774 BookReader.prototype.twoPageSetCursor = function() {
1775 // console.log('setting cursor');
1776 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1777 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1778 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1779 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1781 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1782 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1787 //______________________________________________________________________________
1788 // Returns the currently active index.
1789 BookReader.prototype.currentIndex = function() {
1790 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1791 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1792 return this.firstIndex; // $$$ TODO page in center of view would be better
1793 } else if (this.mode == this.constMode2up) {
1794 // Only allow indices that are actually present in book
1795 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1797 throw 'currentIndex called for unimplemented mode ' + this.mode;
1801 // setCurrentIndex(index)
1802 //______________________________________________________________________________
1803 // Sets the idea of current index without triggering other actions such as animation.
1804 // Compare to jumpToIndex which animates to that index
1805 BookReader.prototype.setCurrentIndex = function(index) {
1806 this.firstIndex = index;
1811 //______________________________________________________________________________
1812 // Flip the right page over onto the left
1813 BookReader.prototype.right = function() {
1814 if ('rl' != this.pageProgression) {
1824 //______________________________________________________________________________
1825 // Flip to the rightmost page
1826 BookReader.prototype.rightmost = function() {
1827 if ('rl' != this.pageProgression) {
1835 //______________________________________________________________________________
1836 // Flip the left page over onto the right.
1837 BookReader.prototype.left = function() {
1838 if ('rl' != this.pageProgression) {
1848 //______________________________________________________________________________
1849 // Flip to the leftmost page
1850 BookReader.prototype.leftmost = function() {
1851 if ('rl' != this.pageProgression) {
1859 //______________________________________________________________________________
1860 BookReader.prototype.next = function() {
1861 if (2 == this.mode) {
1863 this.flipFwdToIndex(null);
1865 if (this.firstIndex < this.lastDisplayableIndex()) {
1866 this.jumpToIndex(this.firstIndex+1);
1872 //______________________________________________________________________________
1873 BookReader.prototype.prev = function() {
1874 if (2 == this.mode) {
1876 this.flipBackToIndex(null);
1878 if (this.firstIndex >= 1) {
1879 this.jumpToIndex(this.firstIndex-1);
1884 BookReader.prototype.first = function() {
1885 this.jumpToIndex(this.firstDisplayableIndex());
1888 BookReader.prototype.last = function() {
1889 this.jumpToIndex(this.lastDisplayableIndex());
1893 //______________________________________________________________________________
1894 // Scrolls down one screen view
1895 BookReader.prototype.scrollDown = function() {
1896 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1897 $('#BRcontainer').animate(
1898 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1899 450, 'easeInOutQuint'
1908 //______________________________________________________________________________
1909 // Scrolls up one screen view
1910 BookReader.prototype.scrollUp = function() {
1911 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1912 $('#BRcontainer').animate(
1913 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1914 450, 'easeInOutQuint'
1923 // flipBackToIndex()
1924 //______________________________________________________________________________
1925 // to flip back one spread, pass index=null
1926 BookReader.prototype.flipBackToIndex = function(index) {
1928 if (1 == this.mode) return;
1930 var leftIndex = this.twoPage.currentIndexL;
1932 if (this.animating) return;
1934 if (null != this.leafEdgeTmp) {
1935 alert('error: leafEdgeTmp should be null!');
1939 if (null == index) {
1940 index = leftIndex-2;
1942 //if (index<0) return;
1944 var previousIndices = this.getSpreadIndices(index);
1946 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1950 this.animating = true;
1952 if ('rl' != this.pageProgression) {
1953 // Assume LTR and we are going backward
1954 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1955 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1957 // RTL and going backward
1958 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1959 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1963 // flipLeftToRight()
1964 //______________________________________________________________________________
1965 // Flips the page on the left towards the page on the right
1966 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1968 var leftLeaf = this.twoPage.currentIndexL;
1970 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1971 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1972 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1974 var currWidthL = this.getPageWidth2UP(leftLeaf);
1975 var newWidthL = this.getPageWidth2UP(newIndexL);
1976 var newWidthR = this.getPageWidth2UP(newIndexR);
1978 var top = this.twoPageTop();
1979 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1981 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1982 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1984 //animation strategy:
1985 // 0. remove search highlight, if any.
1986 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1987 // of the left leaf and where the user clicked in the leaf edge.
1988 // Note that if this function was triggered by left() and not a
1989 // mouse click, the width of leafEdgeTmp is very small (zero px).
1990 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1991 // leftLeaf to width=0.
1992 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1993 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1994 // its new full width.
1995 // 4. After step 3 is finished, do the following:
1996 // - remove leafEdgeTmp from the dom.
1997 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1998 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1999 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2000 // and width=newLeafEdgeWidthL.
2001 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2002 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2003 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2004 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2005 // - prefetch new adjacent leafs.
2006 // - set up click handlers for both new left and right leafs.
2007 // - redraw the search highlight.
2008 // - update the pagenum box and the url.
2011 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2013 this.leafEdgeTmp = document.createElement('div');
2014 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2015 $(this.leafEdgeTmp).css({
2016 width: leafEdgeTmpW + 'px',
2017 height: this.twoPage.height-1 + 'px',
2018 left: leftEdgeTmpLeft + 'px',
2021 }).appendTo('#BRtwopageview');
2023 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2024 $(this.leafEdgeL).css({
2025 width: newLeafEdgeWidthL+'px',
2026 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2029 // Left gets the offset of the current left leaf from the document
2030 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2031 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2032 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2034 // We change the left leaf to right positioning
2035 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2036 $(this.prefetchedImgs[leftLeaf]).css({
2041 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2042 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2046 this.removeSearchHilites();
2048 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2049 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2051 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2052 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2054 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2055 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2056 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2058 $(self.leafEdgeR).css({
2059 // Moves the right leaf edge
2060 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2061 left: gutter+newWidthR+'px'
2064 $(self.leafEdgeL).css({
2065 // Moves and resizes the left leaf edge
2066 width: newLeafEdgeWidthL+'px',
2067 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2070 // Resizes the brown border div
2071 $(self.twoPage.coverDiv).css({
2072 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2073 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2076 $(self.leafEdgeTmp).remove();
2077 self.leafEdgeTmp = null;
2079 // $$$ TODO refactor with opposite direction flip
2081 self.twoPage.currentIndexL = newIndexL;
2082 self.twoPage.currentIndexR = newIndexR;
2083 self.twoPage.scaledWL = newWidthL;
2084 self.twoPage.scaledWR = newWidthR;
2085 self.twoPage.gutter = gutter;
2087 self.firstIndex = self.twoPage.currentIndexL;
2088 self.displayedIndices = [newIndexL, newIndexR];
2089 self.pruneUnusedImgs();
2091 self.animating = false;
2093 self.updateSearchHilites2UP();
2094 self.updatePageNumBox2UP();
2096 // self.twoPagePlaceFlipAreas(); // No longer used
2097 self.setMouseHandlers2UP();
2098 self.twoPageSetCursor();
2100 if (self.animationFinishedCallback) {
2101 self.animationFinishedCallback();
2102 self.animationFinishedCallback = null;
2110 //______________________________________________________________________________
2111 // Whether we flip left or right is dependent on the page progression
2112 // to flip forward one spread, pass index=null
2113 BookReader.prototype.flipFwdToIndex = function(index) {
2115 if (this.animating) return;
2117 if (null != this.leafEdgeTmp) {
2118 alert('error: leafEdgeTmp should be null!');
2122 if (null == index) {
2123 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2125 if (index > this.lastDisplayableIndex()) return;
2127 this.animating = true;
2129 var nextIndices = this.getSpreadIndices(index);
2131 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2133 if ('rl' != this.pageProgression) {
2134 // We did not specify RTL
2135 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2136 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2139 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2140 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2144 // flipRightToLeft(nextL, nextR, gutter)
2145 // $$$ better not to have to pass gutter in
2146 //______________________________________________________________________________
2147 // Flip from left to right and show the nextL and nextR indices on those sides
2148 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2149 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2150 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2151 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2152 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2154 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2156 var top = this.twoPageTop();
2157 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2159 var middle = this.twoPage.middle;
2160 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2162 this.leafEdgeTmp = document.createElement('div');
2163 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2164 $(this.leafEdgeTmp).css({
2165 width: leafEdgeTmpW + 'px',
2166 height: this.twoPage.height-1 + 'px',
2167 left: gutter+scaledW+'px',
2170 }).appendTo('#BRtwopageview');
2172 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2173 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2175 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2176 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2177 var newWidthL = this.getPageWidth2UP(newIndexL);
2178 var newWidthR = this.getPageWidth2UP(newIndexR);
2180 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2182 var self = this; // closure-tastic!
2184 var speed = this.flipSpeed;
2186 this.removeSearchHilites();
2188 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2189 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2190 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2191 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2192 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2194 $(self.leafEdgeL).css({
2195 width: newLeafEdgeWidthL+'px',
2196 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2199 // Resizes the book cover
2200 $(self.twoPage.coverDiv).css({
2201 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2202 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2205 $(self.leafEdgeTmp).remove();
2206 self.leafEdgeTmp = null;
2208 self.twoPage.currentIndexL = newIndexL;
2209 self.twoPage.currentIndexR = newIndexR;
2210 self.twoPage.scaledWL = newWidthL;
2211 self.twoPage.scaledWR = newWidthR;
2212 self.twoPage.gutter = gutter;
2214 self.firstIndex = self.twoPage.currentIndexL;
2215 self.displayedIndices = [newIndexL, newIndexR];
2216 self.pruneUnusedImgs();
2218 self.animating = false;
2221 self.updateSearchHilites2UP();
2222 self.updatePageNumBox2UP();
2224 // self.twoPagePlaceFlipAreas(); // No longer used
2225 self.setMouseHandlers2UP();
2226 self.twoPageSetCursor();
2228 if (self.animationFinishedCallback) {
2229 self.animationFinishedCallback();
2230 self.animationFinishedCallback = null;
2236 // setMouseHandlers2UP
2237 //______________________________________________________________________________
2238 BookReader.prototype.setMouseHandlers2UP = function() {
2239 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2247 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2250 e.data.self.right();
2257 //______________________________________________________________________________
2258 BookReader.prototype.prefetchImg = function(index) {
2259 var pageURI = this._getPageURI(index);
2261 // Load image if not loaded or URI has changed (e.g. due to scaling)
2262 var loadImage = false;
2263 if (undefined == this.prefetchedImgs[index]) {
2264 //console.log('no image for ' + index);
2266 } else if (pageURI != this.prefetchedImgs[index].uri) {
2267 //console.log('uri changed for ' + index);
2272 //console.log('prefetching ' + index);
2273 var img = document.createElement("img");
2275 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2276 this.prefetchedImgs[index] = img;
2281 // prepareFlipLeftToRight()
2283 //______________________________________________________________________________
2285 // Prepare to flip the left page towards the right. This corresponds to moving
2286 // backward when the page progression is left to right.
2287 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2289 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2291 this.prefetchImg(prevL);
2292 this.prefetchImg(prevR);
2294 var height = this._getPageHeight(prevL);
2295 var width = this._getPageWidth(prevL);
2296 var middle = this.twoPage.middle;
2297 var top = this.twoPageTop();
2298 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2300 // The gutter is the dividing line between the left and right pages.
2301 // It is offset from the middle to create the illusion of thickness to the pages
2302 var gutter = middle + this.gutterOffsetForIndex(prevL);
2304 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2305 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2306 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2309 position: 'absolute',
2310 left: gutter-scaledW+'px',
2311 right: '', // clear right property
2313 height: this.twoPage.height,
2314 width: scaledW+'px',
2315 backgroundColor: this.getPageBackgroundColor(prevL),
2316 borderRight: '1px solid black',
2320 $(this.prefetchedImgs[prevL]).css(leftCSS);
2322 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2324 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2327 position: 'absolute',
2331 height: this.twoPage.height,
2333 backgroundColor: this.getPageBackgroundColor(prevR),
2334 borderLeft: '1px solid black',
2338 $(this.prefetchedImgs[prevR]).css(rightCSS);
2340 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2344 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2345 // prepareFlipRightToLeft()
2346 //______________________________________________________________________________
2347 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2349 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2352 this.prefetchImg(nextL);
2353 this.prefetchImg(nextR);
2355 var height = this._getPageHeight(nextR);
2356 var width = this._getPageWidth(nextR);
2357 var middle = this.twoPage.middle;
2358 var top = this.twoPageTop();
2359 var scaledW = this.twoPage.height*width/height;
2361 var gutter = middle + this.gutterOffsetForIndex(nextL);
2363 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2364 $(this.prefetchedImgs[nextR]).css({
2365 position: 'absolute',
2368 backgroundColor: this.getPageBackgroundColor(nextR),
2369 height: this.twoPage.height,
2370 width: scaledW+'px',
2371 borderLeft: '1px solid black',
2375 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2377 height = this._getPageHeight(nextL);
2378 width = this._getPageWidth(nextL);
2379 scaledW = this.twoPage.height*width/height;
2381 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2382 $(this.prefetchedImgs[nextL]).css({
2383 position: 'absolute',
2384 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2386 backgroundColor: this.getPageBackgroundColor(nextL),
2387 height: this.twoPage.height,
2388 width: 0+'px', // Start at 0 width, then grow to the left
2389 borderRight: '1px solid black',
2393 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2397 // getNextLeafs() -- NOT RTL AWARE
2398 //______________________________________________________________________________
2399 // BookReader.prototype.getNextLeafs = function(o) {
2400 // //TODO: we might have two left or two right leafs in a row (damaged book)
2401 // //For now, assume that leafs are contiguous.
2403 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2404 // o.L = this.twoPage.currentIndexL+2;
2405 // o.R = this.twoPage.currentIndexL+3;
2408 // getprevLeafs() -- NOT RTL AWARE
2409 //______________________________________________________________________________
2410 // BookReader.prototype.getPrevLeafs = function(o) {
2411 // //TODO: we might have two left or two right leafs in a row (damaged book)
2412 // //For now, assume that leafs are contiguous.
2414 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2415 // o.L = this.twoPage.currentIndexL-2;
2416 // o.R = this.twoPage.currentIndexL-1;
2419 // pruneUnusedImgs()
2420 //______________________________________________________________________________
2421 BookReader.prototype.pruneUnusedImgs = function() {
2422 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2423 for (var key in this.prefetchedImgs) {
2424 //console.log('key is ' + key);
2425 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2426 //console.log('removing key '+ key);
2427 $(this.prefetchedImgs[key]).remove();
2429 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2430 //console.log('deleting key '+ key);
2431 delete this.prefetchedImgs[key];
2437 //______________________________________________________________________________
2438 BookReader.prototype.prefetch = function() {
2440 // $$$ We should check here if the current indices have finished
2441 // loading (with some timeout) before loading more page images
2442 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2444 // prefetch visible pages first
2445 this.prefetchImg(this.twoPage.currentIndexL);
2446 this.prefetchImg(this.twoPage.currentIndexR);
2448 var adjacentPagesToLoad = 3;
2450 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2451 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2453 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2454 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2456 // Load images spreading out from current
2457 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2458 var goingDown = lowCurrent - i;
2459 if (goingDown >= start) {
2460 this.prefetchImg(goingDown);
2462 var goingUp = highCurrent + i;
2463 if (goingUp <= end) {
2464 this.prefetchImg(goingUp);
2469 var lim = this.twoPage.currentIndexL-4;
2471 lim = Math.max(lim, 0);
2472 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2473 this.prefetchImg(i);
2476 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2477 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2478 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2479 this.prefetchImg(i);
2485 // getPageWidth2UP()
2486 //______________________________________________________________________________
2487 BookReader.prototype.getPageWidth2UP = function(index) {
2488 // We return the width based on the dominant height
2489 var height = this._getPageHeight(index);
2490 var width = this._getPageWidth(index);
2491 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2495 //______________________________________________________________________________
2496 BookReader.prototype.search = function(term) {
2497 term = term.replace(/\//g, ' '); // strip slashes
2498 this.searchTerm = term;
2499 $('#BookReaderSearchScript').remove();
2500 var script = document.createElement("script");
2501 script.setAttribute('id', 'BookReaderSearchScript');
2502 script.setAttribute("type", "text/javascript");
2503 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2504 document.getElementsByTagName('head')[0].appendChild(script);
2505 $('#BookReaderSearchBox').val(term);
2506 $('#BookReaderSearchResults').html('Searching...');
2509 // BRSearchCallback()
2510 //______________________________________________________________________________
2511 BookReader.prototype.BRSearchCallback = function(txt) {
2513 if (jQuery.browser.msie) {
2514 var dom=new ActiveXObject("Microsoft.XMLDOM");
2518 var parser = new DOMParser();
2519 var dom = parser.parseFromString(txt, "text/xml");
2522 $('#BookReaderSearchResults').empty();
2523 $('#BookReaderSearchResults').append('<ul>');
2525 for (var key in this.searchResults) {
2526 if (null != this.searchResults[key].div) {
2527 $(this.searchResults[key].div).remove();
2529 delete this.searchResults[key];
2532 var pages = dom.getElementsByTagName('PAGE');
2534 if (0 == pages.length) {
2535 // $$$ it would be nice to echo the (sanitized) search result here
2536 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2538 for (var i = 0; i < pages.length; i++){
2539 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2542 var re = new RegExp (/_(\d{4})\.djvu/);
2543 var reMatch = re.exec(pages[i].getAttribute('file'));
2544 var index = parseInt(reMatch[1], 10);
2545 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2547 var children = pages[i].childNodes;
2549 for (var j=0; j<children.length; j++) {
2550 //console.log(j + ' - ' + children[j].nodeName);
2551 //console.log(children[j].firstChild.nodeValue);
2552 if ('CONTEXT' == children[j].nodeName) {
2553 context += children[j].firstChild.nodeValue;
2554 } else if ('WORD' == children[j].nodeName) {
2555 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2557 var index = this.leafNumToIndex(index);
2558 if (null != index) {
2559 //coordinates are [left, bottom, right, top, [baseline]]
2560 //we'll skip baseline for now...
2561 var coords = children[j].getAttribute('coords').split(',',4);
2562 if (4 == coords.length) {
2563 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2568 var pageName = this.getPageName(index);
2569 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2570 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2571 //TODO: remove hardcoded instance name
2572 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2575 $('#BookReaderSearchResults').append('</ul>');
2577 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2578 $('#BookReaderSearchBox').val(this.searchTerm);
2580 this.updateSearchHilites();
2583 // updateSearchHilites()
2584 //______________________________________________________________________________
2585 BookReader.prototype.updateSearchHilites = function() {
2586 if (2 == this.mode) {
2587 this.updateSearchHilites2UP();
2589 this.updateSearchHilites1UP();
2593 // showSearchHilites1UP()
2594 //______________________________________________________________________________
2595 BookReader.prototype.updateSearchHilites1UP = function() {
2597 for (var key in this.searchResults) {
2599 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2600 var result = this.searchResults[key];
2601 if (null == result.div) {
2602 result.div = document.createElement('div');
2603 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2604 //console.log('appending ' + key);
2607 width: (result.r-result.l)/this.reduce + 'px',
2608 height: (result.b-result.t)/this.reduce + 'px',
2609 left: (result.l)/this.reduce + 'px',
2610 top: (result.t)/this.reduce +'px'
2614 //console.log(key + ' not displayed');
2615 this.searchResults[key].div=null;
2621 //______________________________________________________________________________
2622 // Returns the position of the gutter (line between the page images)
2623 BookReader.prototype.twoPageGutter = function() {
2624 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2628 //______________________________________________________________________________
2629 // Returns the offset for the top of the page images
2630 BookReader.prototype.twoPageTop = function() {
2631 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2634 // twoPageCoverWidth()
2635 //______________________________________________________________________________
2636 // Returns the width of the cover div given the total page width
2637 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2638 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2641 // twoPageGetViewCenter()
2642 //______________________________________________________________________________
2643 // Returns the percentage offset into twopageview div at the center of container div
2644 // { percentageX: float, percentageY: float }
2645 BookReader.prototype.twoPageGetViewCenter = function() {
2648 var containerOffset = $('#BRcontainer').offset();
2649 var viewOffset = $('#BRtwopageview').offset();
2650 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2651 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2656 // twoPageCenterView(percentageX, percentageY)
2657 //______________________________________________________________________________
2658 // Centers the point given by percentage from left,top of twopageview
2659 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2660 if ('undefined' == typeof(percentageX)) {
2663 if ('undefined' == typeof(percentageY)) {
2667 var viewWidth = $('#BRtwopageview').width();
2668 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2669 var intoViewX = percentageX * viewWidth;
2671 var viewHeight = $('#BRtwopageview').height();
2672 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2673 var intoViewY = percentageY * viewHeight;
2675 if (viewWidth < containerClientWidth) {
2676 // Can fit width without scrollbars - center by adjusting offset
2677 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2679 // Need to scroll to center
2680 $('#BRtwopageview').css('left', 0);
2681 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2684 if (viewHeight < containerClientHeight) {
2685 // Fits with scrollbars - add offset
2686 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2688 $('#BRtwopageview').css('top', 0);
2689 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2693 // twoPageFlipAreaHeight
2694 //______________________________________________________________________________
2695 // Returns the integer height of the click-to-flip areas at the edges of the book
2696 BookReader.prototype.twoPageFlipAreaHeight = function() {
2697 return parseInt(this.twoPage.height);
2700 // twoPageFlipAreaWidth
2701 //______________________________________________________________________________
2702 // Returns the integer width of the flip areas
2703 BookReader.prototype.twoPageFlipAreaWidth = function() {
2704 var max = 100; // $$$ TODO base on view width?
2707 var width = this.twoPage.width * 0.15;
2708 return parseInt(BookReader.util.clamp(width, min, max));
2711 // twoPageFlipAreaTop
2712 //______________________________________________________________________________
2713 // Returns integer top offset for flip areas
2714 BookReader.prototype.twoPageFlipAreaTop = function() {
2715 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2718 // twoPageLeftFlipAreaLeft
2719 //______________________________________________________________________________
2720 // Left offset for left flip area
2721 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2722 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2725 // twoPageRightFlipAreaLeft
2726 //______________________________________________________________________________
2727 // Left offset for right flip area
2728 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2729 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2732 // twoPagePlaceFlipAreas
2733 //______________________________________________________________________________
2734 // Readjusts position of flip areas based on current layout
2735 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2736 // We don't set top since it shouldn't change relative to view
2737 $(this.twoPage.leftFlipArea).css({
2738 left: this.twoPageLeftFlipAreaLeft() + 'px',
2739 width: this.twoPageFlipAreaWidth() + 'px'
2741 $(this.twoPage.rightFlipArea).css({
2742 left: this.twoPageRightFlipAreaLeft() + 'px',
2743 width: this.twoPageFlipAreaWidth() + 'px'
2747 // showSearchHilites2UP()
2748 //______________________________________________________________________________
2749 BookReader.prototype.updateSearchHilites2UP = function() {
2751 for (var key in this.searchResults) {
2752 key = parseInt(key, 10);
2753 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2754 var result = this.searchResults[key];
2755 if (null == result.div) {
2756 result.div = document.createElement('div');
2757 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2758 //console.log('appending ' + key);
2761 // We calculate the reduction factor for the specific page because it can be different
2762 // for each page in the spread
2763 var height = this._getPageHeight(key);
2764 var width = this._getPageWidth(key)
2765 var reduce = this.twoPage.height/height;
2766 var scaledW = parseInt(width*reduce);
2768 var gutter = this.twoPageGutter();
2770 if ('L' == this.getPageSide(key)) {
2771 pageL = gutter-scaledW;
2775 var pageT = this.twoPageTop();
2778 width: (result.r-result.l)*reduce + 'px',
2779 height: (result.b-result.t)*reduce + 'px',
2780 left: pageL+(result.l)*reduce + 'px',
2781 top: pageT+(result.t)*reduce +'px'
2785 //console.log(key + ' not displayed');
2786 if (null != this.searchResults[key].div) {
2787 //console.log('removing ' + key);
2788 $(this.searchResults[key].div).remove();
2790 this.searchResults[key].div=null;
2795 // removeSearchHilites()
2796 //______________________________________________________________________________
2797 BookReader.prototype.removeSearchHilites = function() {
2798 for (var key in this.searchResults) {
2799 if (null != this.searchResults[key].div) {
2800 $(this.searchResults[key].div).remove();
2801 this.searchResults[key].div=null;
2807 //______________________________________________________________________________
2808 BookReader.prototype.printPage = function() {
2809 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2811 /* iframe implementation
2813 if (null != this.printPopup) { // check if already showing
2816 this.printPopup = document.createElement("div");
2817 $(this.printPopup).css({
2818 position: 'absolute',
2820 left: ($('#BRcontainer').width()-400)/2 + 'px',
2823 border: "3px double #999999",
2825 backgroundColor: "#fff"
2826 }).appendTo('#BookReader');
2829 if (this.constMode1up == this.mode) {
2830 indexToPrint = this.firstIndex;
2832 indexToPrint = this.twoPage.currentIndexL;
2835 this.indexToPrint = indexToPrint;
2837 var htmlStr = '<div style="text-align: center;">';
2838 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2839 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2840 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2841 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2842 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2843 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2845 htmlStr += '</div>';
2846 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2847 htmlStr += '</div>';
2849 this.printPopup.innerHTML = htmlStr;
2851 var iframe = document.createElement('iframe');
2852 iframe.id = 'printFrame';
2853 iframe.name = 'printFrame';
2854 iframe.width = '233px'; // 8.5 x 11 aspect
2855 iframe.height = '300px';
2857 var self = this; // closure
2859 $(iframe).load(function() {
2860 var doc = BookReader.util.getIFrameDocument(this);
2861 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2864 $('#printDiv').prepend(iframe);
2868 // Get print URI from current indices and mode
2869 BookReader.prototype.getPrintURI = function() {
2871 if (this.constMode2up == this.mode) {
2872 indexToPrint = this.twoPage.currentIndexL;
2874 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2877 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2878 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2879 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2881 if (this.constMode2up == this.mode) {
2882 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2883 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2884 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2886 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2889 return '/bookreader/print.php?' + options;
2892 /* iframe implementation
2893 BookReader.prototype.getPrintFrameContent = function(index) {
2894 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2895 // 8.5x11 so we should end up not overflowing on either paper size.
2896 var paperAspect = 8.5 / 11;
2897 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2901 // Rotate if possible and appropriate, to get larger image size on printed page
2902 if (this.canRotatePage(index)) {
2903 if (imageAspect > 1 && imageAspect > paperAspect) {
2904 // more wide than square, and more wide than paper
2906 imageAspect = 1/imageAspect;
2911 if (imageAspect > paperAspect) {
2912 // wider than paper, fit width
2913 fitAttrs = 'width="95%"';
2915 // taller than paper, fit height
2916 fitAttrs = 'height="95%"';
2919 var imageURL = this._getPageURI(index, 1, rotate);
2920 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2921 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2922 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2923 iframeStr += '</div>';
2924 iframeStr += '</body></html>';
2929 BookReader.prototype.updatePrintFrame = function(delta) {
2930 var newIndex = this.indexToPrint + delta;
2931 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2932 if (newIndex == this.indexToPrint) {
2935 this.indexToPrint = newIndex;
2936 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2937 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2942 //______________________________________________________________________________
2943 BookReader.prototype.showEmbedCode = function() {
2944 if (null != this.embedPopup) { // check if already showing
2948 this.embedPopup = document.createElement("div");
2949 $(this.embedPopup).css({
2950 position: 'absolute',
2952 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2955 border: "3px double #999999",
2957 backgroundColor: "#fff"
2958 }).appendTo('#BookReader');
2960 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2961 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>';
2962 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2963 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2965 this.embedPopup.innerHTML = htmlStr;
2966 $(this.embedPopup).find('input').bind('click', function() {
2972 //______________________________________________________________________________
2973 BookReader.prototype.autoToggle = function() {
2975 var bComingFrom1up = false;
2976 if (2 != this.mode) {
2977 bComingFrom1up = true;
2981 // Change to autofit if book is too large
2982 if (this.reduce < this.twoPageGetAutofitReduce()) {
2983 this.zoom2up('auto');
2987 if (null == this.autoTimer) {
2988 this.flipSpeed = 2000;
2990 // $$$ Draw events currently cause layout problems when they occur during animation.
2991 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2992 // we workaround for now by not triggering immediate animation in that case.
2993 // See https://bugs.launchpad.net/gnubook/+bug/328327
2994 if (('rl' == this.pageProgression) && bComingFrom1up) {
2995 // don't flip immediately -- wait until timer fires
2998 this.flipFwdToIndex();
3001 $('#BRtoolbar .play').hide();
3002 $('#BRtoolbar .pause').show();
3003 this.autoTimer=setInterval(function(){
3004 if (self.animating) {return;}
3006 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3007 self.flipBackToIndex(1); // $$$ really what we want?
3009 self.flipFwdToIndex();
3018 //______________________________________________________________________________
3019 // Stop autoplay mode, allowing animations to finish
3020 BookReader.prototype.autoStop = function() {
3021 if (null != this.autoTimer) {
3022 clearInterval(this.autoTimer);
3023 this.flipSpeed = 'fast';
3024 $('#BRtoolbar .pause').hide();
3025 $('#BRtoolbar .play').show();
3026 this.autoTimer = null;
3030 // stopFlipAnimations
3031 //______________________________________________________________________________
3032 // Immediately stop flip animations. Callbacks are triggered.
3033 BookReader.prototype.stopFlipAnimations = function() {
3035 this.autoStop(); // Clear timers
3037 // Stop animation, clear queue, trigger callbacks
3038 if (this.leafEdgeTmp) {
3039 $(this.leafEdgeTmp).stop(false, true);
3041 jQuery.each(this.prefetchedImgs, function() {
3042 $(this).stop(false, true);
3045 // And again since animations also queued in callbacks
3046 if (this.leafEdgeTmp) {
3047 $(this.leafEdgeTmp).stop(false, true);
3049 jQuery.each(this.prefetchedImgs, function() {
3050 $(this).stop(false, true);
3055 // keyboardNavigationIsDisabled(event)
3056 // - returns true if keyboard navigation should be disabled for the event
3057 //______________________________________________________________________________
3058 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3059 if (event.target.tagName == "INPUT") {
3065 // gutterOffsetForIndex
3066 //______________________________________________________________________________
3068 // Returns the gutter offset for the spread containing the given index.
3069 // This function supports RTL
3070 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3072 // To find the offset of the gutter from the middle we calculate our percentage distance
3073 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3074 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3076 // But then again for RTL it's the opposite
3077 if ('rl' == this.pageProgression) {
3085 //______________________________________________________________________________
3086 // Returns the width of the leaf edge div for the page with index given
3087 BookReader.prototype.leafEdgeWidth = function(pindex) {
3088 // $$$ could there be single pixel rounding errors for L vs R?
3089 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3090 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3092 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3096 // jumpIndexForLeftEdgePageX
3097 //______________________________________________________________________________
3098 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3099 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3100 if ('rl' != this.pageProgression) {
3101 // LTR - flipping backward
3102 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3104 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3105 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3109 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3110 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3115 // jumpIndexForRightEdgePageX
3116 //______________________________________________________________________________
3117 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3118 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3119 if ('rl' != this.pageProgression) {
3121 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3122 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3125 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3126 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3131 BookReader.prototype.initToolbar = function(mode, ui) {
3133 $("#BookReader").append("<div id='BRtoolbar'>"
3134 + "<span id='BRtoolbarbuttons' style='float: right'>"
3135 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3136 + "<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>"
3137 + "<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>"
3138 + "<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>"
3139 + "<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>"
3140 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3144 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3145 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3146 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3147 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3148 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3149 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3150 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3153 + "<span id='#BRbooktitle'>"
3154 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3158 this.updateToolbarZoom(this.reduce); // Pretty format
3160 if (ui == "embed" || ui == "touch") {
3161 $("#BookReader a.logo").attr("target","_blank");
3164 // $$$ turn this into a member variable
3165 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3167 // We build in mode 2
3170 this.bindToolbarNavHandlers(jToolbar);
3172 // Setup tooltips -- later we could load these from a file for i18n
3173 var titles = { '.logo': 'Go to Archive.org',
3174 '.zoom_in': 'Zoom in',
3175 '.zoom_out': 'Zoom out',
3176 '.one_page_mode': 'One-page view',
3177 '.two_page_mode': 'Two-page view',
3178 '.thumbnail_mode': 'Thumbnail view',
3179 '.print': 'Print this page',
3180 '.embed': 'Embed bookreader',
3181 '.book_left': 'Flip left',
3182 '.book_right': 'Flip right',
3183 '.book_up': 'Page up',
3184 '.book_down': 'Page down',
3187 '.book_top': 'First page',
3188 '.book_bottom': 'Last page'
3190 if ('rl' == this.pageProgression) {
3191 titles['.book_leftmost'] = 'Last page';
3192 titles['.book_rightmost'] = 'First page';
3194 titles['.book_leftmost'] = 'First page';
3195 titles['.book_rightmost'] = 'Last page';
3198 for (var icon in titles) {
3199 jToolbar.find(icon).attr('title', titles[icon]);
3202 // Hide mode buttons and autoplay if 2up is not available
3203 // $$$ if we end up with more than two modes we should show the applicable buttons
3204 if ( !this.canSwitchToMode(this.constMode2up) ) {
3205 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3208 // Switch to requested mode -- binds other click handlers
3209 this.switchToolbarMode(mode);
3214 // switchToolbarMode
3215 //______________________________________________________________________________
3216 // Update the toolbar for the given mode (changes navigation buttons)
3217 // $$$ we should soon split the toolbar out into its own module
3218 BookReader.prototype.switchToolbarMode = function(mode) {
3221 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3222 $('#BRtoolbar .BRtoolbarmode2').hide();
3223 $('#BRtoolbar .BRtoolbarmode3').hide();
3224 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3225 } else if (2 == mode) {
3227 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3228 $('#BRtoolbar .BRtoolbarmode1').hide();
3229 $('#BRtoolbar .BRtoolbarmode3').hide();
3230 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3233 $('#BRtoolbar .BRtoolbarzoom').hide();
3234 $('#BRtoolbar .BRtoolbarmode2').hide();
3235 $('#BRtoolbar .BRtoolbarmode1').hide();
3236 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3240 // bindToolbarNavHandlers
3241 //______________________________________________________________________________
3242 // Binds the toolbar handlers
3243 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3245 var self = this; // closure
3247 jToolbar.find('.book_left').bind('click', function(e) {
3252 jToolbar.find('.book_right').bind('click', function(e) {
3257 jToolbar.find('.book_up').bind('click', function(e) {
3258 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3266 jToolbar.find('.book_down').bind('click', function(e) {
3267 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3275 jToolbar.find('.print').bind('click', function(e) {
3280 jToolbar.find('.embed').bind('click', function(e) {
3281 self.showEmbedCode();
3285 jToolbar.find('.play').bind('click', function(e) {
3290 jToolbar.find('.pause').bind('click', function(e) {
3295 jToolbar.find('.book_top').bind('click', function(e) {
3300 jToolbar.find('.book_bottom').bind('click', function(e) {
3305 jToolbar.find('.book_leftmost').bind('click', function(e) {
3310 jToolbar.find('.book_rightmost').bind('click', function(e) {
3316 // updateToolbarZoom(reduce)
3317 //______________________________________________________________________________
3318 // Update the displayed zoom factor based on reduction factor
3319 BookReader.prototype.updateToolbarZoom = function(reduce) {
3321 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3324 value = (100 / reduce).toFixed(2);
3325 // Strip trailing zeroes and decimal if all zeroes
3326 value = value.replace(/0+$/,'');
3327 value = value.replace(/\.$/,'');
3330 $('#BRzoom').text(value);
3333 // firstDisplayableIndex
3334 //______________________________________________________________________________
3335 // Returns the index of the first visible page, dependent on the mode.
3336 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3337 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3338 BookReader.prototype.firstDisplayableIndex = function() {
3339 if (this.mode != this.constMode2up) {
3343 if ('rl' != this.pageProgression) {
3345 if (this.getPageSide(0) == 'L') {
3352 if (this.getPageSide(0) == 'R') {
3360 // lastDisplayableIndex
3361 //______________________________________________________________________________
3362 // Returns the index of the last visible page, dependent on the mode.
3363 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3364 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3365 BookReader.prototype.lastDisplayableIndex = function() {
3367 var lastIndex = this.numLeafs - 1;
3369 if (this.mode != this.constMode2up) {
3373 if ('rl' != this.pageProgression) {
3375 if (this.getPageSide(lastIndex) == 'R') {
3378 return lastIndex + 1;
3382 if (this.getPageSide(lastIndex) == 'L') {
3385 return lastIndex + 1;
3390 // shortTitle(maximumCharacters)
3392 // Returns a shortened version of the title with the maximum number of characters
3393 BookReader.prototype.shortTitle = function(maximumCharacters) {
3394 if (this.bookTitle.length < maximumCharacters) {
3395 return this.bookTitle;
3398 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3403 // Parameter related functions
3405 // updateFromParams(params)
3407 // Update ourselves from the params object.
3409 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3410 BookReader.prototype.updateFromParams = function(params) {
3411 if ('undefined' != typeof(params.mode)) {
3412 this.switchMode(params.mode);
3416 if ('undefined' != typeof(params.searchTerm)) {
3417 if (this.searchTerm != params.searchTerm) {
3418 this.search(params.searchTerm);
3422 // $$$ process /zoom
3424 // We only respect page if index is not set
3425 if ('undefined' != typeof(params.index)) {
3426 if (params.index != this.currentIndex()) {
3427 this.jumpToIndex(params.index);
3429 } else if ('undefined' != typeof(params.page)) {
3430 // $$$ this assumes page numbers are unique
3431 if (params.page != this.getPageNum(this.currentIndex())) {
3432 this.jumpToPage(params.page);
3436 // $$$ process /region
3437 // $$$ process /highlight
3440 // paramsFromFragment(urlFragment)
3442 // Returns a object with configuration parametes from a URL fragment.
3444 // E.g paramsFromFragment(window.location.hash)
3445 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3446 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3450 // For convenience we allow an initial # character (as from window.location.hash)
3451 // but don't require it
3452 if (urlFragment.substr(0,1) == '#') {
3453 urlFragment = urlFragment.substr(1);
3456 // Simple #nn syntax
3457 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3458 if ( !isNaN(oldStyleLeafNum) ) {
3459 params.index = oldStyleLeafNum;
3461 // Done processing if using old-style syntax
3465 // Split into key-value pairs
3466 var urlArray = urlFragment.split('/');
3468 for (var i = 0; i < urlArray.length; i += 2) {
3469 urlHash[urlArray[i]] = urlArray[i+1];
3473 if ('1up' == urlHash['mode']) {
3474 params.mode = this.constMode1up;
3475 } else if ('2up' == urlHash['mode']) {
3476 params.mode = this.constMode2up;
3477 } else if ('thumb' == urlHash['mode']) {
3478 params.mode = this.constModeThumb;
3482 if ('undefined' != typeof(urlHash['page'])) {
3483 // page was set -- may not be int
3484 params.page = urlHash['page'];
3487 // $$$ process /region
3488 // $$$ process /search
3490 if (urlHash['search'] != undefined) {
3491 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3494 // $$$ process /highlight
3499 // paramsFromCurrent()
3501 // Create a params object from the current parameters.
3502 BookReader.prototype.paramsFromCurrent = function() {
3506 var index = this.currentIndex();
3507 var pageNum = this.getPageNum(index);
3508 if ((pageNum === 0) || pageNum) {
3509 params.page = pageNum;
3512 params.index = index;
3513 params.mode = this.mode;
3519 if (this.searchHighlightVisible()) {
3520 params.searchTerm = this.searchTerm;
3526 // fragmentFromParams(params)
3528 // Create a fragment string from the params object.
3529 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3530 BookReader.prototype.fragmentFromParams = function(params) {
3531 var separator = '/';
3535 if ('undefined' != typeof(params.page)) {
3536 fragments.push('page', params.page);
3538 // Don't have page numbering -- use index instead
3539 fragments.push('page', 'n' + params.index);
3546 if ('undefined' != typeof(params.mode)) {
3547 if (params.mode == this.constMode1up) {
3548 fragments.push('mode', '1up');
3549 } else if (params.mode == this.constMode2up) {
3550 fragments.push('mode', '2up');
3551 } else if (params.mode == this.constModeThumb) {
3552 fragments.push('mode', 'thumb');
3554 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3559 if (params.searchTerm) {
3560 fragments.push('search', params.searchTerm);
3563 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3566 // getPageIndex(pageNum)
3568 // Returns the *highest* index the given page number, or undefined
3569 BookReader.prototype.getPageIndex = function(pageNum) {
3570 var pageIndices = this.getPageIndices(pageNum);
3572 if (pageIndices.length > 0) {
3573 return pageIndices[pageIndices.length - 1];
3579 // getPageIndices(pageNum)
3581 // Returns an array (possibly empty) of the indices with the given page number
3582 BookReader.prototype.getPageIndices = function(pageNum) {
3585 // Check for special "nXX" page number
3586 if (pageNum.slice(0,1) == 'n') {
3588 var pageIntStr = pageNum.slice(1, pageNum.length);
3589 var pageIndex = parseInt(pageIntStr);
3590 indices.push(pageIndex);
3593 // Do nothing... will run through page names and see if one matches
3598 for (i=0; i<this.numLeafs; i++) {
3599 if (this.getPageNum(i) == pageNum) {
3607 // getPageName(index)
3609 // Returns the name of the page as it should be displayed in the user interface
3610 BookReader.prototype.getPageName = function(index) {
3611 return 'Page ' + this.getPageNum(index);
3614 // updateLocationHash
3616 // Update the location hash from the current parameters. Call this instead of manually
3617 // using window.location.replace
3618 BookReader.prototype.updateLocationHash = function() {
3619 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3620 window.location.replace(newHash);
3622 // This is the variable checked in the timer. Only user-generated changes
3623 // to the URL will trigger the event.
3624 this.oldLocationHash = newHash;
3627 // startLocationPolling
3629 // Starts polling of window.location to see hash fragment changes
3630 BookReader.prototype.startLocationPolling = function() {
3631 var self = this; // remember who I am
3632 self.oldLocationHash = window.location.hash;
3634 if (this.locationPollId) {
3635 clearInterval(this.locationPollID);
3636 this.locationPollId = null;
3639 this.locationPollId = setInterval(function() {
3640 var newHash = window.location.hash;
3641 if (newHash != self.oldLocationHash) {
3642 if (newHash != self.oldUserHash) { // Only process new user hash once
3643 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3645 // Queue change if animating
3646 if (self.animating) {
3648 self.animationFinishedCallback = function() {
3649 self.updateFromParams(self.paramsFromFragment(newHash));
3651 } else { // update immediately
3652 self.updateFromParams(self.paramsFromFragment(newHash));
3654 self.oldUserHash = newHash;
3662 // Returns true if we can switch to the requested mode
3663 BookReader.prototype.canSwitchToMode = function(mode) {
3664 if (mode == this.constMode2up) {
3665 // check there are enough pages to display
3666 // $$$ this is a workaround for the mis-feature that we can't display
3667 // short books in 2up mode
3668 if (this.numLeafs < 6) {
3676 // searchHighlightVisible
3678 // Returns true if a search highlight is currently being displayed
3679 BookReader.prototype.searchHighlightVisible = function() {
3680 if (this.constMode2up == this.mode) {
3681 if (this.searchResults[this.twoPage.currentIndexL]
3682 || this.searchResults[this.twoPage.currentIndexR]) {
3686 if (this.searchResults[this.currentIndex()]) {
3693 // getPageBackgroundColor
3695 // Returns a CSS property string for the background color for the given page
3696 // $$$ turn into regular CSS?
3697 BookReader.prototype.getPageBackgroundColor = function(index) {
3698 if (index >= 0 && index < this.numLeafs) {
3700 return this.pageDefaultBackgroundColor;
3708 // Returns the page width for the given index, or first or last page if out of range
3709 BookReader.prototype._getPageWidth = function(index) {
3710 // Synthesize a page width for pages not actually present in book.
3711 // May or may not be the best approach.
3712 // If index is out of range we return the width of first or last page
3713 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3714 return this.getPageWidth(index);
3719 // Returns the page height for the given index, or first or last page if out of range
3720 BookReader.prototype._getPageHeight= function(index) {
3721 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3722 return this.getPageHeight(index);
3727 // Returns the page URI or transparent image if out of range
3728 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3729 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3730 return this.imagesBaseURL + "/transparent.png";
3733 if ('undefined' == typeof(reduce)) {
3734 // reduce not passed in
3735 // $$$ this probably won't work for thumbnail mode
3736 var ratio = this.getPageHeight(index) / this.twoPage.height;
3738 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3741 } else if (ratio < 4) {
3743 } else if (ratio < 8) {
3745 } else if (ratio < 16) {
3747 } else if (ratio < 32) {
3755 return this.getPageURI(index, reduce, rotate);
3758 // Library functions
3760 disableSelect: function(jObject) {
3761 // Bind mouse handlers
3762 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3763 jObject.bind('mousedown', function(e) {
3764 // $$$ check here for right-click and don't disable. Also use jQuery style
3765 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3768 // Special hack for IE7
3769 jObject[0].onselectstart = function(e) { return false; };
3772 clamp: function(value, min, max) {
3773 return Math.min(Math.max(value, min), max);
3776 notInArray: function(value, array) {
3777 // inArray returns -1 or undefined if value not in array
3778 return ! (jQuery.inArray(value, array) >= 0);
3781 getIFrameDocument: function(iframe) {
3782 // Adapted from http://xkr.us/articles/dom/iframe-document/
3783 var outer = (iframe.contentWindow || iframe.contentDocument);
3784 return (outer.document || outer);
3787 decodeURIComponentPlus: function(value) {
3788 // Decodes a URI component and converts '+' to ' '
3789 return decodeURIComponent(value).replace(/\+/g, ' ');
3792 encodeURIComponentPlus: function(value) {
3793 // Encodes a URI component and converts ' ' to '+'
3794 return encodeURIComponent(value).replace(/%20/g, '+');
3796 // The final property here must NOT have a comma after it - IE7