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 if (e.data.autofit) {
171 e.data.resizePageView();
173 e.data.centerPageView();
174 $('#BRpageview').empty()
175 e.data.displayedIndices = [];
176 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
178 } else if (3 == e.data.mode){
179 e.data.prepareThumbnailView();
181 //console.log('drawing 2 page view');
183 // We only need to prepare again in autofit (size of spread changes)
184 if (e.data.twoPage.autofit) {
185 e.data.prepareTwoPageView();
187 // Re-center if the scrollbars have disappeared
188 var center = e.data.twoPageGetViewCenter();
189 var doRecenter = false;
190 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
191 center.percentageX = 0.5;
194 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
195 center.percentageY = 0.5;
199 e.data.twoPageCenterView(center.percentageX, center.percentageY);
205 $('.BRpagediv1up').bind('mousedown', this, function(e) {
206 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
207 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
211 // $$$ refactor this so it's enough to set the first index and call preparePageView
212 // (get rid of mode-specific logic at this point)
213 if (1 == this.mode) {
214 this.firstIndex = startIndex;
215 this.prepareOnePageView();
216 this.jumpToIndex(startIndex);
217 } else if (3 == this.mode) {
218 this.firstIndex = startIndex;
219 this.prepareThumbnailView();
220 this.jumpToIndex(startIndex);
222 //this.resizePageView();
224 this.displayedIndices=[0];
225 this.firstIndex = startIndex;
226 this.displayedIndices = [this.firstIndex];
227 //console.log('titleLeaf: %d', this.titleLeaf);
228 //console.log('displayedIndices: %s', this.displayedIndices);
229 this.prepareTwoPageView();
232 // Enact other parts of initial params
233 this.updateFromParams(params);
236 BookReader.prototype.setupKeyListeners = function() {
249 // We use document here instead of window to avoid a bug in jQuery on IE7
250 $(document).keydown(function(e) {
252 // Keyboard navigation
253 if (!self.keyboardNavigationIsDisabled(e)) {
257 // In 1up mode page scrolling is handled by browser
258 if (2 == self.mode) {
265 if (2 == self.mode) {
279 if (2 == self.mode) {
285 if (2 == self.mode) {
296 //______________________________________________________________________________
297 BookReader.prototype.drawLeafs = function() {
298 if (1 == this.mode) {
299 this.drawLeafsOnePage();
300 } else if (3 == this.mode) {
301 this.drawLeafsThumbnail();
303 this.drawLeafsTwoPage();
308 // bindGestures(jElement)
309 //______________________________________________________________________________
310 BookReader.prototype.bindGestures = function(jElement) {
312 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
314 if (e.originalEvent.scale > 1.5) {
316 } else if (e.originalEvent.scale < 0.6) {
323 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
324 //console.log('setting handler');
325 //console.log(element.tagName);
327 $(element).unbind('tap').bind('tap', data, function(e) {
332 // drawLeafsOnePage()
333 //______________________________________________________________________________
334 BookReader.prototype.drawLeafsOnePage = function() {
335 //alert('drawing leafs!');
339 var scrollTop = $('#BRcontainer').attr('scrollTop');
340 var scrollBottom = scrollTop + $('#BRcontainer').height();
341 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
343 var indicesToDisplay = [];
348 for (i=0; i<this.numLeafs; i++) {
349 var height = parseInt(this._getPageHeight(i)/this.reduce);
351 leafBottom += height;
352 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
353 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
354 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
355 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
356 if (topInView | bottomInView | middleInView) {
357 //console.log('displayed: ' + this.displayedIndices);
358 //console.log('to display: ' + i);
359 indicesToDisplay.push(i);
361 leafTop += height +10;
365 var firstIndexToDraw = indicesToDisplay[0];
366 this.firstIndex = firstIndexToDraw;
368 // Update hash, but only if we're currently displaying a leaf
369 // Hack that fixes #365790
370 if (this.displayedIndices.length > 0) {
371 this.updateLocationHash();
374 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
376 indicesToDisplay.unshift(firstIndexToDraw);
379 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
380 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
381 indicesToDisplay.push(lastIndexToDraw+1);
386 for (i=0; i<firstIndexToDraw; i++) {
387 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
390 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
391 var viewWidth = $('#BRcontainer').attr('scrollWidth');
394 for (i=0; i<indicesToDisplay.length; i++) {
395 var index = indicesToDisplay[i];
396 var height = parseInt(this._getPageHeight(index)/this.reduce);
398 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
399 var width = parseInt(this._getPageWidth(index)/this.reduce);
400 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
401 var div = document.createElement("div");
402 div.className = 'BRpagediv1up';
403 div.id = 'pagediv'+index;
404 div.style.position = "absolute";
405 $(div).css('top', leafTop + 'px');
406 var left = (viewWidth-width)>>1;
407 if (left<0) left = 0;
408 $(div).css('left', left+'px');
409 $(div).css('width', width+'px');
410 $(div).css('height', height+'px');
411 //$(div).text('loading...');
413 $('#BRpageview').append(div);
415 var img = document.createElement("img");
416 img.src = this._getPageURI(index, this.reduce, 0);
417 $(img).css('width', width+'px');
418 $(img).css('height', height+'px');
422 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
425 leafTop += height +10;
429 for (i=0; i<this.displayedIndices.length; i++) {
430 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
431 var index = this.displayedIndices[i];
432 //console.log('Removing leaf ' + index);
433 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
434 $('#pagediv'+index).remove();
436 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
440 this.displayedIndices = indicesToDisplay.slice();
441 this.updateSearchHilites();
443 if (null != this.getPageNum(firstIndexToDraw)) {
444 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
446 $("#BRpagenum").val('');
449 this.updateToolbarZoom(this.reduce);
453 // drawLeafsThumbnail()
454 //______________________________________________________________________________
455 // If seekIndex is defined, the view will be drawn with that page visible (without any
456 // animated scrolling)
457 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
458 //alert('drawing leafs!');
461 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
463 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
477 // Will be set to top of requested seek index, if set
480 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
481 for (i=0; i<this.numLeafs; i++) {
482 leafWidth = this.thumbWidth;
483 if (rightPos + (leafWidth + this.padding) > viewWidth){
489 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
490 if (leafMap[currentRow].leafs===undefined) {
491 leafMap[currentRow].leafs = [];
492 leafMap[currentRow].height = 0;
493 leafMap[currentRow].top = 0;
495 leafMap[currentRow].leafs[leafIndex] = {};
496 leafMap[currentRow].leafs[leafIndex].num = i;
497 leafMap[currentRow].leafs[leafIndex].left = rightPos;
499 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
500 if (leafHeight > leafMap[currentRow].height) {
501 leafMap[currentRow].height = leafHeight;
503 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
504 rightPos += leafWidth + this.padding;
505 if (rightPos > maxRight) { maxRight = rightPos; }
508 if (i == seekIndex) {
509 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
513 // reset the bottom position based on thumbnails
514 $('#BRpageview').height(bottomPos);
516 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
518 // If seekTop is defined, seeking was requested and target found
519 if (typeof(seekTop) != 'undefined') {
520 $('#BRcontainer').scrollTop( seekTop );
523 var scrollTop = $('#BRcontainer').attr('scrollTop');
524 var scrollBottom = scrollTop + $('#BRcontainer').height();
528 var rowsToDisplay = [];
530 // Visible leafs with least/greatest index
531 var leastVisible = this.numLeafs - 1;
534 // Determine the thumbnails in view
535 for (i=0; i<leafMap.length; i++) {
536 leafBottom += this.padding + leafMap[i].height;
537 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
538 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
539 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
540 if (topInView | bottomInView | middleInView) {
541 //console.log('row to display: ' + j);
542 rowsToDisplay.push(i);
543 if (leafMap[i].leafs[0].num < leastVisible) {
544 leastVisible = leafMap[i].leafs[0].num;
546 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
547 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
550 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
551 leafTop = leafBottom;
554 // create a buffer of preloaded rows before and after the visible rows
555 var firstRow = rowsToDisplay[0];
556 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
557 for (i=1; i<this.thumbRowBuffer+1; i++) {
558 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
560 for (i=1; i<this.thumbRowBuffer+1; i++) {
561 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
564 // Create the thumbnail divs and images (lazy loaded)
573 for (i=0; i<rowsToDisplay.length; i++) {
574 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
575 row = rowsToDisplay[i];
577 for (j=0; j<leafMap[row].leafs.length; j++) {
579 leaf = leafMap[row].leafs[j].num;
581 leafWidth = this.thumbWidth;
582 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
583 leafTop = leafMap[row].top;
584 left = leafMap[row].leafs[index].left + pageViewBuffer;
585 if ('rl' == this.pageProgression){
586 left = viewWidth - leafWidth - left;
589 div = document.createElement("div");
590 div.id = 'pagediv'+leaf;
591 div.style.position = "absolute";
592 div.className = "BRpagedivthumb";
594 left += this.padding;
595 $(div).css('top', leafTop + 'px');
596 $(div).css('left', left+'px');
597 $(div).css('width', leafWidth+'px');
598 $(div).css('height', leafHeight+'px');
599 //$(div).text('loading...');
601 // link to page in single page mode
602 link = document.createElement("a");
603 $(link).data('leaf', leaf);
604 $(link).bind('tap', function(event) {
605 self.firstIndex = $(this).data('leaf');
606 self.switchMode(self.constMode1up);
607 event.preventDefault();
610 // $$$ we don't actually go to this URL (click is handled in handler above)
611 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
614 $('#BRpageview').append(div);
616 img = document.createElement("img");
617 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
619 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
620 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
621 .addClass('BRlazyload')
622 // Store the URL of the image that will replace this one
623 .data('srcURL', this._getPageURI(leaf, thumbReduce));
625 //console.log('displaying thumbnail: ' + leaf);
630 // Remove thumbnails that are not to be displayed
632 for (i=0; i<this.displayedRows.length; i++) {
633 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
634 row = this.displayedRows[i];
636 // $$$ Safari doesn't like the comprehension
637 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
638 //console.log('Removing row ' + row + ' ' + rowLeafs);
640 for (k=0; k<leafMap[row].leafs.length; k++) {
641 index = leafMap[row].leafs[k].num;
642 //console.log('Removing leaf ' + index);
643 $('#pagediv'+index).remove();
647 var mRow = this.displayedRows[i];
648 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
649 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
654 // Update which page is considered current to make sure a visible page is the current one
655 var currentIndex = this.currentIndex();
656 // console.log('current ' + currentIndex);
657 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
658 if (currentIndex < leastVisible) {
659 this.setCurrentIndex(leastVisible);
660 } else if (currentIndex > mostVisible) {
661 this.setCurrentIndex(mostVisible);
664 this.displayedRows = rowsToDisplay.slice();
666 // Update hash, but only if we're currently displaying a leaf
667 // Hack that fixes #365790
668 if (this.displayedRows.length > 0) {
669 this.updateLocationHash();
672 // remove previous highlights
673 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
675 // highlight current page
676 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
678 this.lazyLoadThumbnails();
680 // Update page number box. $$$ refactor to function
681 if (null !== this.getPageNum(this.currentIndex())) {
682 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
684 $("#BRpagenum").val('');
687 this.updateToolbarZoom(this.reduce);
690 BookReader.prototype.lazyLoadThumbnails = function() {
692 // console.log('lazy load');
694 // We check the complete property since load may not be fired if loading from the cache
695 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
697 var loading = $('.BRlazyloading').length;
698 var toLoad = this.thumbMaxLoading - loading;
700 // console.log(' ' + loading + ' thumbnails loading');
701 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
706 // $$$ TODO load those near top (but not beyond) page view first
707 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
708 self.lazyLoadImage(this);
713 BookReader.prototype.lazyLoadImage = function (dummyImage) {
714 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
716 var img = new Image();
720 .addClass('BRlazyloading')
721 .one('load', function() {
722 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
724 $(this).removeClass('BRlazyloading');
726 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
727 // we call the function after a slight delay. Also the img.complete property
728 // is not yet set in IE8 inside this onload handler
729 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
731 .one('error', function() {
732 // Remove class so we no longer count as loading
733 $(this).removeClass('BRlazyloading');
735 .attr( { width: $(dummyImage).width(),
736 height: $(dummyImage).height(),
737 src: $(dummyImage).data('srcURL')
740 // replace with the new img
741 $(dummyImage).before(img).remove();
743 img = null; // tidy up closure
747 // drawLeafsTwoPage()
748 //______________________________________________________________________________
749 BookReader.prototype.drawLeafsTwoPage = function() {
750 var scrollTop = $('#BRtwopageview').attr('scrollTop');
751 var scrollBottom = scrollTop + $('#BRtwopageview').height();
753 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
755 var indexL = this.twoPage.currentIndexL;
757 var heightL = this._getPageHeight(indexL);
758 var widthL = this._getPageWidth(indexL);
760 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
761 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
762 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
763 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
764 //console.log(leafEdgeWidthL);
766 var middle = this.twoPage.middle; // $$$ getter instead?
767 var top = this.twoPageTop();
768 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
770 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
771 this.twoPage.gutter = this.twoPageGutter();
773 this.prefetchImg(indexL);
774 $(this.prefetchedImgs[indexL]).css({
775 position: 'absolute',
776 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
779 backgroundColor: this.getPageBackgroundColor(indexL),
780 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
781 width: this.twoPage.scaledWL + 'px',
782 borderRight: '1px solid black',
784 }).appendTo('#BRtwopageview');
786 var indexR = this.twoPage.currentIndexR;
787 var heightR = this._getPageHeight(indexR);
788 var widthR = this._getPageWidth(indexR);
790 // $$$ should use getwidth2up?
791 //var scaledWR = this.twoPage.height*widthR/heightR;
792 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
793 this.prefetchImg(indexR);
794 $(this.prefetchedImgs[indexR]).css({
795 position: 'absolute',
796 left: this.twoPage.gutter+'px',
799 backgroundColor: this.getPageBackgroundColor(indexR),
800 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
801 width: this.twoPage.scaledWR + 'px',
802 borderLeft: '1px solid black',
804 }).appendTo('#BRtwopageview');
807 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
808 this.setMouseHandlers2UP();
809 this.twoPageSetCursor();
811 this.updatePageNumBox2UP();
812 this.updateToolbarZoom(this.reduce);
814 // this.twoPagePlaceFlipAreas(); // No longer used
818 // updatePageNumBox2UP
819 //______________________________________________________________________________
820 BookReader.prototype.updatePageNumBox2UP = function() {
821 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
822 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
824 $("#BRpagenum").val('');
826 this.updateLocationHash();
830 //______________________________________________________________________________
831 BookReader.prototype.loadLeafs = function() {
835 if (null == this.timer) {
836 this.timer=setTimeout(function(){self.drawLeafs()},250);
838 clearTimeout(this.timer);
839 this.timer=setTimeout(function(){self.drawLeafs()},250);
845 // Pass 1 to zoom in, anything else to zoom out
846 //______________________________________________________________________________
847 BookReader.prototype.zoom = function(direction) {
849 case this.constMode1up:
850 if (direction == 1) {
852 return this.zoom1up('in');
854 return this.zoom1up('out');
857 case this.constMode2up:
858 if (direction == 1) {
860 return this.zoom2up('in');
862 return this.zoom2up('out');
865 case this.constModeThumb:
866 // XXX update zoomThumb for named directions
867 return this.zoomThumb(direction);
873 //______________________________________________________________________________
874 BookReader.prototype.zoom1up = function(direction) {
876 if (2 == this.mode) { //can only zoom in 1-page mode
881 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
883 if (this.reduce == reduceFactor.reduce) {
884 // Already at this level
888 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
889 this.onePage.autofit = reduceFactor.autofit;
891 this.pageScale = this.reduce; // preserve current reduce
892 this.resizePageView();
894 $('#BRpageview').empty()
895 this.displayedIndices = [];
898 this.updateToolbarZoom(this.reduce);
900 // Recalculate search hilites
901 this.removeSearchHilites();
902 this.updateSearchHilites();
907 //______________________________________________________________________________
908 BookReader.prototype.resizePageView = function() {
910 // $$$ This code assumes 1up mode
911 // e.g. does not preserve position in thumbnail mode
912 // See http://bugs.launchpad.net/bookreader/+bug/552972
915 case this.constMode1up:
916 case this.constMode2up:
917 this.resizePageView1up();
919 case this.constModeThumb:
920 this.prepareThumbnailView( this.currentIndex() );
923 alert('Resize not implemented for this mode');
927 BookReader.prototype.resizePageView1up = function() {
930 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
931 var viewWidth = $('#BRcontainer').attr('clientWidth');
933 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
934 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
935 var oldPageViewHeight = $('#BRpageview').height();
936 var oldPageViewWidth = $('#BRpageview').width();
938 var oldCenterY = this.centerY1up();
939 var oldCenterX = this.centerX1up();
941 if (0 != oldPageViewHeight) {
942 var scrollRatio = oldCenterY / oldPageViewHeight;
947 // Recalculate 1up reduction factors
948 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
949 $('#BRcontainer').attr('clientHeight') );
950 // Update current reduce (if in autofit)
951 if (this.onePage.autofit) {
952 var reductionFactor = this.nextReduce(this.reduce, this.onePage.autofit, this.onePage.reductionFactors);
953 this.reduce = reductionFactor.reduce;
956 for (i=0; i<this.numLeafs; i++) {
957 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
958 var width = parseInt(this._getPageWidth(i)/this.reduce);
959 if (width>viewWidth) viewWidth=width;
961 $('#BRpageview').height(viewHeight);
962 $('#BRpageview').width(viewWidth);
964 var newCenterY = scrollRatio*viewHeight;
965 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
966 $('#BRcontainer').attr('scrollTop', newTop);
968 // We use clientWidth here to avoid miscalculating due to scroll bar
969 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
970 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
971 newLeft = Math.max(newLeft, 0);
972 $('#BRcontainer').attr('scrollLeft', newLeft);
973 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
975 //this.centerPageView();
978 this.removeSearchHilites();
979 this.updateSearchHilites();
984 //______________________________________________________________________________
985 // Returns the current offset of the viewport center in scaled document coordinates.
986 BookReader.prototype.centerX1up = function() {
988 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
989 centerX = $('#BRpageview').width();
991 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
993 centerX = Math.floor(centerX);
998 //______________________________________________________________________________
999 // Returns the current offset of the viewport center in scaled document coordinates.
1000 BookReader.prototype.centerY1up = function() {
1001 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1002 return Math.floor(centerY);
1006 //______________________________________________________________________________
1007 BookReader.prototype.centerPageView = function() {
1009 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1010 var clientWidth = $('#BRcontainer').attr('clientWidth');
1011 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1012 if (scrollWidth > clientWidth) {
1013 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1018 // zoom2up(direction)
1019 //______________________________________________________________________________
1020 BookReader.prototype.zoom2up = function(direction) {
1022 // Hard stop autoplay
1023 this.stopFlipAnimations();
1025 // Recalculate autofit factors
1026 this.twoPageCalculateReductionFactors();
1028 // Get new zoom state
1029 var reductionFactor = this.nextReduce(this.reduce, direction, this.twoPage.reductionFactors);
1030 if ((this.reduce == reductionFactor.reduce) && (this.twoPage.autofit == reductionFactor.autofit)) {
1034 this.twoPage.autofit = reductionFactor.autofit;
1035 this.reduce = reductionFactor.reduce;
1036 this.pageScale = this.reduce; // preserve current reduce
1038 // Preserve view center position
1039 var oldCenter = this.twoPageGetViewCenter();
1041 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1042 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1043 if (1 == direction) {
1044 for (var img in this.prefetchedImgs) {
1045 delete this.prefetchedImgs[img];
1049 // Prepare view with new center to minimize visual glitches
1050 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1053 BookReader.prototype.zoomThumb = function(direction) {
1054 var oldColumns = this.thumbColumns;
1055 switch (direction) {
1057 this.thumbColumns += 1;
1060 this.thumbColumns -= 1;
1065 if (this.thumbColumns < 2) {
1066 this.thumbColumns = 2;
1067 } else if (this.thumbColumns > 8) {
1068 this.thumbColumns = 8;
1071 if (this.thumbColumns != oldColumns) {
1072 this.prepareThumbnailView();
1076 // Returns the width per thumbnail to display the requested number of columns
1077 // Note: #BRpageview must already exist since its width is used to calculate the
1079 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1080 var padding = (thumbnailColumns + 1) * this.padding;
1081 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1082 return parseInt(width);
1085 // quantizeReduce(reduce)
1086 //______________________________________________________________________________
1087 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1088 BookReader.prototype.quantizeReduce = function(reduce, reductionFactors) {
1089 var quantized = reductionFactors[0].reduce;
1090 var distance = Math.abs(reduce - quantized);
1091 for (var i = 1; i < reductionFactors.length; i++) {
1092 newDistance = Math.abs(reduce - reductionFactors[i].reduce);
1093 if (newDistance < distance) {
1094 distance = newDistance;
1095 quantized = reductionFactors[i].reduce;
1102 // reductionFactors should be array of sorted reduction factors
1103 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1104 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1106 // XXX add 'closest', to replace quantize function
1108 if (direction == 'in') {
1109 var newReduceIndex = 0;
1111 for (var i = 1; i < reductionFactors.length; i++) {
1112 if (reductionFactors[i].reduce < currentReduce) {
1116 return reductionFactors[newReduceIndex];
1118 } else if (direction == 'out') { // zoom out
1119 var lastIndex = reductionFactors.length - 1;
1120 var newReduceIndex = lastIndex;
1122 for (var i = lastIndex; i >= 0; i--) {
1123 if (reductionFactors[i].reduce > currentReduce) {
1127 return reductionFactors[newReduceIndex];
1130 // Asked for specific autofit mode
1131 for (var i = 0; i < reductionFactors.length; i++) {
1132 if (reductionFactors[i].autofit == direction) {
1133 return reductionFactors[i];
1137 alert('Could not find reduction factor for direction ' + direction);
1138 return reductionFactors[0];
1142 BookReader.prototype._reduceSort = function(a, b) {
1143 return a.reduce - b.reduce;
1147 //______________________________________________________________________________
1148 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1149 BookReader.prototype.jumpToPage = function(pageNum) {
1151 var pageIndex = this.getPageIndex(pageNum);
1153 if ('undefined' != typeof(pageIndex)) {
1156 this.jumpToIndex(pageIndex);
1157 $('#BRcontainer').attr('scrollTop', leafTop);
1166 //______________________________________________________________________________
1167 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1169 if (this.constMode2up == this.mode) {
1172 // By checking against min/max we do nothing if requested index
1174 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1175 this.flipBackToIndex(index);
1176 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1177 this.flipFwdToIndex(index);
1180 } else if (this.constModeThumb == this.mode) {
1181 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1191 for (i=0; i<(index+1); i++) {
1192 leafWidth = this.thumbWidth;
1193 if (rightPos + (leafWidth + this.padding) > viewWidth){
1199 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1200 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1201 if (leafIndex==0) { leafTop = bottomPos; }
1202 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1203 rightPos += leafWidth + this.padding;
1206 this.firstIndex=index;
1207 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1210 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1218 for (i=0; i<index; i++) {
1219 h = parseInt(this._getPageHeight(i)/this.reduce);
1220 leafTop += h + this.padding;
1224 //console.log('pageY ' + pageY);
1225 var offset = parseInt( (pageY) / this.reduce);
1226 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1227 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1230 // Show page just a little below the top
1231 leafTop -= this.padding / 2;
1235 var offset = parseInt( (pageX) / this.reduce);
1236 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1239 // Preserve left position
1240 leafLeft = $('#BRcontainer').scrollLeft();
1243 //$('#BRcontainer').attr('scrollTop', leafTop);
1244 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1250 //______________________________________________________________________________
1251 BookReader.prototype.switchMode = function(mode) {
1253 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1255 if (mode == this.mode) {
1259 if (!this.canSwitchToMode(mode)) {
1264 this.removeSearchHilites();
1267 this.switchToolbarMode(mode);
1269 // reinstate scale if moving from thumbnail view
1270 if (this.pageScale != this.reduce) {
1271 this.reduce = this.pageScale;
1274 // $$$ TODO preserve center of view when switching between mode
1275 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1277 // XXX maybe better to preserve zoom in each mode
1279 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'), $('#BRcontainer').attr('clientHeight'));
1280 this.reduce = this.quantizeReduce(this.reduce, this.onePage.reductionFactors);
1281 this.prepareOnePageView();
1282 } else if (3 == mode) {
1283 this.reduce = this.quantizeReduce(this.reduce, this.reductionFactors);
1284 this.prepareThumbnailView();
1286 // $$$ why don't we save autofit?
1287 this.twoPage.autofit = null; // Take zoom level from other mode
1288 this.twoPageCalculateReductionFactors();
1289 this.reduce = this.quantizeReduce(this.reduce, this.twoPage.reductionFactors);
1290 this.prepareTwoPageView();
1291 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1296 //prepareOnePageView()
1297 //______________________________________________________________________________
1298 BookReader.prototype.prepareOnePageView = function() {
1300 // var startLeaf = this.displayedIndices[0];
1301 var startLeaf = this.currentIndex();
1303 $('#BRcontainer').empty();
1304 $('#BRcontainer').css({
1305 overflowY: 'scroll',
1309 $("#BRcontainer").append("<div id='BRpageview'></div>");
1311 // Attaches to first child - child must be present
1312 $('#BRcontainer').dragscrollable();
1313 this.bindGestures($('#BRcontainer'));
1315 // $$$ keep select enabled for now since disabling it breaks keyboard
1316 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1317 // BookReader.util.disableSelect($('#BRpageview'));
1319 this.resizePageView();
1321 this.jumpToIndex(startLeaf);
1322 this.displayedIndices = [];
1324 this.drawLeafsOnePage();
1327 //prepareThumbnailView()
1328 //______________________________________________________________________________
1329 BookReader.prototype.prepareThumbnailView = function() {
1331 $('#BRcontainer').empty();
1332 $('#BRcontainer').css({
1333 overflowY: 'scroll',
1337 $("#BRcontainer").append("<div id='BRpageview'></div>");
1339 $('#BRcontainer').dragscrollable();
1340 this.bindGestures($('#BRcontainer'));
1342 // $$$ keep select enabled for now since disabling it breaks keyboard
1343 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1344 // BookReader.util.disableSelect($('#BRpageview'));
1346 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1347 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1349 this.displayedRows = [];
1351 // Draw leafs with current index directly in view (no animating to the index)
1352 this.drawLeafsThumbnail( this.currentIndex() );
1356 // prepareTwoPageView()
1357 //______________________________________________________________________________
1358 // Some decisions about two page view:
1360 // Both pages will be displayed at the same height, even if they were different physical/scanned
1361 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1362 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1363 // aspect ratio to determine the height.
1365 // The two page view div is resized to keep the middle of the book in the middle of the div
1366 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1367 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1368 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1369 $('#BRcontainer').empty();
1370 $('#BRcontainer').css('overflow', 'auto');
1372 // We want to display two facing pages. We may be missing
1373 // one side of the spread because it is the first/last leaf,
1374 // foldouts, missing pages, etc
1376 //var targetLeaf = this.displayedIndices[0];
1377 var targetLeaf = this.firstIndex;
1379 if (targetLeaf < this.firstDisplayableIndex()) {
1380 targetLeaf = this.firstDisplayableIndex();
1383 if (targetLeaf > this.lastDisplayableIndex()) {
1384 targetLeaf = this.lastDisplayableIndex();
1387 //this.twoPage.currentIndexL = null;
1388 //this.twoPage.currentIndexR = null;
1389 //this.pruneUnusedImgs();
1391 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1392 this.twoPage.currentIndexL = currentSpreadIndices[0];
1393 this.twoPage.currentIndexR = currentSpreadIndices[1];
1394 this.firstIndex = this.twoPage.currentIndexL;
1396 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1398 this.pruneUnusedImgs();
1399 this.prefetch(); // Preload images or reload if scaling has changed
1401 //console.dir(this.twoPage);
1403 // Add the two page view
1404 // $$$ Can we get everything set up and then append?
1405 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1407 // Attaches to first child, so must come after we add the page view
1408 $('#BRcontainer').dragscrollable();
1409 this.bindGestures($('#BRcontainer'));
1411 // $$$ calculate first then set
1412 $('#BRtwopageview').css( {
1413 height: this.twoPage.totalHeight + 'px',
1414 width: this.twoPage.totalWidth + 'px',
1415 position: 'absolute'
1418 // If there will not be scrollbars (e.g. when zooming out) we center the book
1419 // since otherwise the book will be stuck off-center
1420 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1421 centerPercentageX = 0.5;
1423 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1424 centerPercentageY = 0.5;
1427 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1429 this.twoPage.coverDiv = document.createElement('div');
1430 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1431 width: this.twoPage.bookCoverDivWidth + 'px',
1432 height: this.twoPage.bookCoverDivHeight+'px',
1433 visibility: 'visible',
1434 position: 'absolute',
1435 left: this.twoPage.bookCoverDivLeft + 'px',
1436 top: this.twoPage.bookCoverDivTop+'px',
1437 }).appendTo('#BRtwopageview');
1439 this.leafEdgeR = document.createElement('div');
1440 this.leafEdgeR.className = 'BRleafEdgeR';
1441 $(this.leafEdgeR).css({
1442 width: this.twoPage.leafEdgeWidthR + 'px',
1443 height: this.twoPage.height-1 + 'px',
1444 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1445 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1446 }).appendTo('#BRtwopageview');
1448 this.leafEdgeL = document.createElement('div');
1449 this.leafEdgeL.className = 'BRleafEdgeL';
1450 $(this.leafEdgeL).css({
1451 width: this.twoPage.leafEdgeWidthL + 'px',
1452 height: this.twoPage.height-1 + 'px',
1453 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1454 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1455 }).appendTo('#BRtwopageview');
1457 div = document.createElement('div');
1458 $(div).attr('id', 'BRbookspine').css({
1459 width: this.twoPage.bookSpineDivWidth+'px',
1460 height: this.twoPage.bookSpineDivHeight+'px',
1461 left: this.twoPage.bookSpineDivLeft+'px',
1462 top: this.twoPage.bookSpineDivTop+'px'
1463 }).appendTo('#BRtwopageview');
1465 var self = this; // for closure
1467 /* Flip areas no longer used
1468 this.twoPage.leftFlipArea = document.createElement('div');
1469 this.twoPage.leftFlipArea.className = 'BRfliparea';
1470 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1472 width: this.twoPageFlipAreaWidth() + 'px',
1473 height: this.twoPageFlipAreaHeight() + 'px',
1474 position: 'absolute',
1475 left: this.twoPageLeftFlipAreaLeft() + 'px',
1476 top: this.twoPageFlipAreaTop() + 'px',
1479 }).bind('click', function(e) {
1481 }).bind('mousedown', function(e) {
1483 }).appendTo('#BRtwopageview');
1485 this.twoPage.rightFlipArea = document.createElement('div');
1486 this.twoPage.rightFlipArea.className = 'BRfliparea';
1487 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1489 width: this.twoPageFlipAreaWidth() + 'px',
1490 height: this.twoPageFlipAreaHeight() + 'px',
1491 position: 'absolute',
1492 left: this.twoPageRightFlipAreaLeft() + 'px',
1493 top: this.twoPageFlipAreaTop() + 'px',
1496 }).bind('click', function(e) {
1498 }).bind('mousedown', function(e) {
1500 }).appendTo('#BRtwopageview');
1503 this.prepareTwoPagePopUp();
1505 this.displayedIndices = [];
1507 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1508 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1510 this.drawLeafsTwoPage();
1511 this.updateToolbarZoom(this.reduce);
1515 this.removeSearchHilites();
1516 this.updateSearchHilites();
1520 // prepareTwoPagePopUp()
1522 // This function prepares the "View Page n" popup that shows while the mouse is
1523 // over the left/right "stack of sheets" edges. It also binds the mouse
1524 // events for these divs.
1525 //______________________________________________________________________________
1526 BookReader.prototype.prepareTwoPagePopUp = function() {
1528 this.twoPagePopUp = document.createElement('div');
1529 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1530 $(this.twoPagePopUp).css({
1532 }).appendTo('#BRcontainer');
1533 $(this.twoPagePopUp).hide();
1535 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1536 $(e.data.twoPagePopUp).show();
1539 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1540 $(e.data.twoPagePopUp).hide();
1543 $(this.leafEdgeL).bind('click', this, function(e) {
1545 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1546 e.data.jumpToIndex(jumpIndex);
1549 $(this.leafEdgeR).bind('click', this, function(e) {
1551 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1552 e.data.jumpToIndex(jumpIndex);
1555 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1557 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1558 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1560 // $$$ TODO: Make sure popup is positioned so that it is in view
1561 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1562 $(e.data.twoPagePopUp).css({
1563 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1564 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1568 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1570 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1571 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1573 // $$$ TODO: Make sure popup is positioned so that it is in view
1574 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1575 $(e.data.twoPagePopUp).css({
1576 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1577 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1582 // calculateSpreadSize()
1583 //______________________________________________________________________________
1584 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1585 // this.twoPage.currentIndexR
1586 // This function sets this.twoPage.height, twoPage.width
1588 BookReader.prototype.calculateSpreadSize = function() {
1590 var firstIndex = this.twoPage.currentIndexL;
1591 var secondIndex = this.twoPage.currentIndexR;
1592 //console.log('first page is ' + firstIndex);
1594 // Calculate page sizes and total leaf width
1596 if ( this.twoPage.autofit) {
1597 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1599 // set based on reduction factor
1600 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1603 // Both pages together
1604 this.twoPage.height = spreadSize.height;
1605 this.twoPage.width = spreadSize.width;
1608 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1609 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1612 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1613 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1614 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1618 // The width of the book cover div. The combined width of both pages, twice the width
1619 // of the book cover internal padding (2*10) and the page edges
1620 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1621 // The height of the book cover div
1622 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1625 // We calculate the total width and height for the div so that we can make the book
1627 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1628 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1629 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1630 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1631 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1632 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1634 // We want to minimize the unused space in two-up mode (maximize the amount of page
1635 // shown). We give width to the leaf edges and these widths change (though the sum
1636 // of the two remains constant) as we flip through the book. With the book
1637 // cover centered and fixed in the BRcontainer div the page images will meet
1638 // at the "gutter" which is generally offset from the center.
1639 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1640 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1642 // The left edge of the book cover moves depending on the width of the pages
1643 // $$$ change to getter
1644 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1645 // The top edge of the book cover stays a fixed distance from the top
1646 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1649 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1650 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1651 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1654 this.reduce = spreadSize.reduce; // $$$ really set this here?
1657 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1660 // We check which page is closest to a "normal" page and use that to set the height
1661 // for both pages. This means that foldouts and other odd size pages will be displayed
1662 // smaller than the nominal zoom amount.
1663 var canon5Dratio = 1.5;
1666 height: this._getPageHeight(firstIndex),
1667 width: this._getPageWidth(firstIndex)
1671 height: this._getPageHeight(secondIndex),
1672 width: this._getPageWidth(secondIndex)
1675 var firstIndexRatio = first.height / first.width;
1676 var secondIndexRatio = second.height / second.width;
1677 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1680 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1681 ratio = firstIndexRatio;
1682 //console.log('using firstIndexRatio ' + ratio);
1684 ratio = secondIndexRatio;
1685 //console.log('using secondIndexRatio ' + ratio);
1688 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1689 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1690 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1692 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1693 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1695 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1696 ideal.width -= 10; // $$$ fudge factor
1697 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1698 ideal.height -= 20; // fudge factor
1699 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1701 if (ideal.height/ratio <= ideal.width) {
1703 ideal.width = parseInt(ideal.height/ratio);
1706 ideal.height = parseInt(ideal.width*ratio);
1709 // $$$ check this logic with large spreads
1710 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1715 // getSpreadSizeFromReduce()
1716 //______________________________________________________________________________
1717 // Returns the spread size calculated from the reduction factor for the given pages
1718 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1719 var spreadSize = {};
1720 // $$$ Scale this based on reduce?
1721 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1722 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1723 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1725 // $$$ Possibly incorrect -- we should make height "dominant"
1726 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1727 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1728 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1729 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1730 spreadSize.reduce = reduce;
1735 // twoPageGetAutofitReduce()
1736 //______________________________________________________________________________
1737 // Returns the current ideal reduction factor
1738 BookReader.prototype.twoPageGetAutofitReduce = function() {
1739 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1740 return spreadSize.reduce;
1743 BookReader.prototype.onePageGetAutofitWidth = function() {
1744 var widthPadding = 20;
1745 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1748 BookReader.prototype.onePageGetAutofitHeight = function() {
1749 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - this.padding * 2); // make sure a little of adjacent pages show
1752 BookReader.prototype.getMedianPageSize = function() {
1753 if (this._medianPageSize) {
1754 return this._medianPageSize;
1757 // A little expensive but we just do it once
1760 for (var i = 0; i < this.numLeafs; i++) {
1761 widths.push(this.getPageWidth(i));
1762 heights.push(this.getPageHeight(i));
1768 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1769 return this._medianPageSize;
1772 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1773 // the autofit reduction factors.
1774 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1775 this.onePage.reductionFactors = this.reductionFactors.concat(
1777 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1778 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1780 this.onePage.reductionFactors.sort(this._reduceSort);
1783 BookReader.prototype.twoPageCalculateReductionFactors = function() {
1784 this.twoPage.reductionFactors = this.reductionFactors.concat(
1786 { reduce: this.getIdealSpreadSize( this.twoPage.currentIndexL, this.twoPage.currentIndexR ).reduce,
1789 this.twoPage.reductionFactors.sort(this._reduceSort);
1792 // twoPageSetCursor()
1793 //______________________________________________________________________________
1794 // Set the cursor for two page view
1795 BookReader.prototype.twoPageSetCursor = function() {
1796 // console.log('setting cursor');
1797 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1798 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1799 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1800 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1802 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1803 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1808 //______________________________________________________________________________
1809 // Returns the currently active index.
1810 BookReader.prototype.currentIndex = function() {
1811 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1812 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1813 return this.firstIndex; // $$$ TODO page in center of view would be better
1814 } else if (this.mode == this.constMode2up) {
1815 // Only allow indices that are actually present in book
1816 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1818 throw 'currentIndex called for unimplemented mode ' + this.mode;
1822 // setCurrentIndex(index)
1823 //______________________________________________________________________________
1824 // Sets the idea of current index without triggering other actions such as animation.
1825 // Compare to jumpToIndex which animates to that index
1826 BookReader.prototype.setCurrentIndex = function(index) {
1827 this.firstIndex = index;
1832 //______________________________________________________________________________
1833 // Flip the right page over onto the left
1834 BookReader.prototype.right = function() {
1835 if ('rl' != this.pageProgression) {
1845 //______________________________________________________________________________
1846 // Flip to the rightmost page
1847 BookReader.prototype.rightmost = function() {
1848 if ('rl' != this.pageProgression) {
1856 //______________________________________________________________________________
1857 // Flip the left page over onto the right.
1858 BookReader.prototype.left = function() {
1859 if ('rl' != this.pageProgression) {
1869 //______________________________________________________________________________
1870 // Flip to the leftmost page
1871 BookReader.prototype.leftmost = function() {
1872 if ('rl' != this.pageProgression) {
1880 //______________________________________________________________________________
1881 BookReader.prototype.next = function() {
1882 if (2 == this.mode) {
1884 this.flipFwdToIndex(null);
1886 if (this.firstIndex < this.lastDisplayableIndex()) {
1887 this.jumpToIndex(this.firstIndex+1);
1893 //______________________________________________________________________________
1894 BookReader.prototype.prev = function() {
1895 if (2 == this.mode) {
1897 this.flipBackToIndex(null);
1899 if (this.firstIndex >= 1) {
1900 this.jumpToIndex(this.firstIndex-1);
1905 BookReader.prototype.first = function() {
1906 this.jumpToIndex(this.firstDisplayableIndex());
1909 BookReader.prototype.last = function() {
1910 this.jumpToIndex(this.lastDisplayableIndex());
1914 //______________________________________________________________________________
1915 // Scrolls down one screen view
1916 BookReader.prototype.scrollDown = function() {
1917 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1918 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1919 // Whole pages are visible, scroll whole page only
1923 $('#BRcontainer').animate(
1924 { scrollTop: '+=' + this._scrollAmount() + 'px'},
1925 400, 'easeInOutExpo'
1934 //______________________________________________________________________________
1935 // Scrolls up one screen view
1936 BookReader.prototype.scrollUp = function() {
1937 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1938 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1939 // Whole pages are visible, scroll whole page only
1943 $('#BRcontainer').animate(
1944 { scrollTop: '-=' + this._scrollAmount() + 'px'},
1945 400, 'easeInOutExpo'
1954 //______________________________________________________________________________
1955 // The amount to scroll vertically in integer pixels
1956 BookReader.prototype._scrollAmount = function() {
1957 if (this.constMode1up == this.mode) {
1958 // Overlap by % of page size
1959 return parseInt($('#BRcontainer').attr('clientHeight') - this.getPageHeight(this.currentIndex()) / this.reduce * 0.03);
1962 return parseInt(0.9 * $('#BRcontainer').attr('clientHeight'));
1966 // flipBackToIndex()
1967 //______________________________________________________________________________
1968 // to flip back one spread, pass index=null
1969 BookReader.prototype.flipBackToIndex = function(index) {
1971 if (1 == this.mode) return;
1973 var leftIndex = this.twoPage.currentIndexL;
1975 if (this.animating) return;
1977 if (null != this.leafEdgeTmp) {
1978 alert('error: leafEdgeTmp should be null!');
1982 if (null == index) {
1983 index = leftIndex-2;
1985 //if (index<0) return;
1987 var previousIndices = this.getSpreadIndices(index);
1989 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1993 this.animating = true;
1995 if ('rl' != this.pageProgression) {
1996 // Assume LTR and we are going backward
1997 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1998 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
2000 // RTL and going backward
2001 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2002 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2006 // flipLeftToRight()
2007 //______________________________________________________________________________
2008 // Flips the page on the left towards the page on the right
2009 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2011 var leftLeaf = this.twoPage.currentIndexL;
2013 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2014 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2015 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2017 var currWidthL = this.getPageWidth2UP(leftLeaf);
2018 var newWidthL = this.getPageWidth2UP(newIndexL);
2019 var newWidthR = this.getPageWidth2UP(newIndexR);
2021 var top = this.twoPageTop();
2022 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2024 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2025 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2027 //animation strategy:
2028 // 0. remove search highlight, if any.
2029 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2030 // of the left leaf and where the user clicked in the leaf edge.
2031 // Note that if this function was triggered by left() and not a
2032 // mouse click, the width of leafEdgeTmp is very small (zero px).
2033 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2034 // leftLeaf to width=0.
2035 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2036 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2037 // its new full width.
2038 // 4. After step 3 is finished, do the following:
2039 // - remove leafEdgeTmp from the dom.
2040 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2041 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2042 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2043 // and width=newLeafEdgeWidthL.
2044 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2045 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2046 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2047 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2048 // - prefetch new adjacent leafs.
2049 // - set up click handlers for both new left and right leafs.
2050 // - redraw the search highlight.
2051 // - update the pagenum box and the url.
2054 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2056 this.leafEdgeTmp = document.createElement('div');
2057 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2058 $(this.leafEdgeTmp).css({
2059 width: leafEdgeTmpW + 'px',
2060 height: this.twoPage.height-1 + 'px',
2061 left: leftEdgeTmpLeft + 'px',
2064 }).appendTo('#BRtwopageview');
2066 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2067 $(this.leafEdgeL).css({
2068 width: newLeafEdgeWidthL+'px',
2069 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2072 // Left gets the offset of the current left leaf from the document
2073 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2074 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2075 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2077 // We change the left leaf to right positioning
2078 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2079 $(this.prefetchedImgs[leftLeaf]).css({
2084 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2085 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2089 this.removeSearchHilites();
2091 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2092 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2094 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2095 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2097 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2098 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2099 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2101 $(self.leafEdgeR).css({
2102 // Moves the right leaf edge
2103 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2104 left: gutter+newWidthR+'px'
2107 $(self.leafEdgeL).css({
2108 // Moves and resizes the left leaf edge
2109 width: newLeafEdgeWidthL+'px',
2110 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2113 // Resizes the brown border div
2114 $(self.twoPage.coverDiv).css({
2115 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2116 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2119 $(self.leafEdgeTmp).remove();
2120 self.leafEdgeTmp = null;
2122 // $$$ TODO refactor with opposite direction flip
2124 self.twoPage.currentIndexL = newIndexL;
2125 self.twoPage.currentIndexR = newIndexR;
2126 self.twoPage.scaledWL = newWidthL;
2127 self.twoPage.scaledWR = newWidthR;
2128 self.twoPage.gutter = gutter;
2130 self.firstIndex = self.twoPage.currentIndexL;
2131 self.displayedIndices = [newIndexL, newIndexR];
2132 self.pruneUnusedImgs();
2134 self.animating = false;
2136 self.updateSearchHilites2UP();
2137 self.updatePageNumBox2UP();
2139 // self.twoPagePlaceFlipAreas(); // No longer used
2140 self.setMouseHandlers2UP();
2141 self.twoPageSetCursor();
2143 if (self.animationFinishedCallback) {
2144 self.animationFinishedCallback();
2145 self.animationFinishedCallback = null;
2153 //______________________________________________________________________________
2154 // Whether we flip left or right is dependent on the page progression
2155 // to flip forward one spread, pass index=null
2156 BookReader.prototype.flipFwdToIndex = function(index) {
2158 if (this.animating) return;
2160 if (null != this.leafEdgeTmp) {
2161 alert('error: leafEdgeTmp should be null!');
2165 if (null == index) {
2166 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2168 if (index > this.lastDisplayableIndex()) return;
2170 this.animating = true;
2172 var nextIndices = this.getSpreadIndices(index);
2174 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2176 if ('rl' != this.pageProgression) {
2177 // We did not specify RTL
2178 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2179 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2182 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2183 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2187 // flipRightToLeft(nextL, nextR, gutter)
2188 // $$$ better not to have to pass gutter in
2189 //______________________________________________________________________________
2190 // Flip from left to right and show the nextL and nextR indices on those sides
2191 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2192 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2193 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2194 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2195 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2197 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2199 var top = this.twoPageTop();
2200 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2202 var middle = this.twoPage.middle;
2203 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2205 this.leafEdgeTmp = document.createElement('div');
2206 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2207 $(this.leafEdgeTmp).css({
2208 width: leafEdgeTmpW + 'px',
2209 height: this.twoPage.height-1 + 'px',
2210 left: gutter+scaledW+'px',
2213 }).appendTo('#BRtwopageview');
2215 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2216 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2218 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2219 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2220 var newWidthL = this.getPageWidth2UP(newIndexL);
2221 var newWidthR = this.getPageWidth2UP(newIndexR);
2223 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2225 var self = this; // closure-tastic!
2227 var speed = this.flipSpeed;
2229 this.removeSearchHilites();
2231 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2232 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2233 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2234 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2235 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2237 $(self.leafEdgeL).css({
2238 width: newLeafEdgeWidthL+'px',
2239 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2242 // Resizes the book cover
2243 $(self.twoPage.coverDiv).css({
2244 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2245 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2248 $(self.leafEdgeTmp).remove();
2249 self.leafEdgeTmp = null;
2251 self.twoPage.currentIndexL = newIndexL;
2252 self.twoPage.currentIndexR = newIndexR;
2253 self.twoPage.scaledWL = newWidthL;
2254 self.twoPage.scaledWR = newWidthR;
2255 self.twoPage.gutter = gutter;
2257 self.firstIndex = self.twoPage.currentIndexL;
2258 self.displayedIndices = [newIndexL, newIndexR];
2259 self.pruneUnusedImgs();
2261 self.animating = false;
2264 self.updateSearchHilites2UP();
2265 self.updatePageNumBox2UP();
2267 // self.twoPagePlaceFlipAreas(); // No longer used
2268 self.setMouseHandlers2UP();
2269 self.twoPageSetCursor();
2271 if (self.animationFinishedCallback) {
2272 self.animationFinishedCallback();
2273 self.animationFinishedCallback = null;
2279 // setMouseHandlers2UP
2280 //______________________________________________________________________________
2281 BookReader.prototype.setMouseHandlers2UP = function() {
2282 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2290 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2293 e.data.self.right();
2300 //______________________________________________________________________________
2301 BookReader.prototype.prefetchImg = function(index) {
2302 var pageURI = this._getPageURI(index);
2304 // Load image if not loaded or URI has changed (e.g. due to scaling)
2305 var loadImage = false;
2306 if (undefined == this.prefetchedImgs[index]) {
2307 //console.log('no image for ' + index);
2309 } else if (pageURI != this.prefetchedImgs[index].uri) {
2310 //console.log('uri changed for ' + index);
2315 //console.log('prefetching ' + index);
2316 var img = document.createElement("img");
2318 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2319 this.prefetchedImgs[index] = img;
2324 // prepareFlipLeftToRight()
2326 //______________________________________________________________________________
2328 // Prepare to flip the left page towards the right. This corresponds to moving
2329 // backward when the page progression is left to right.
2330 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2332 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2334 this.prefetchImg(prevL);
2335 this.prefetchImg(prevR);
2337 var height = this._getPageHeight(prevL);
2338 var width = this._getPageWidth(prevL);
2339 var middle = this.twoPage.middle;
2340 var top = this.twoPageTop();
2341 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2343 // The gutter is the dividing line between the left and right pages.
2344 // It is offset from the middle to create the illusion of thickness to the pages
2345 var gutter = middle + this.gutterOffsetForIndex(prevL);
2347 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2348 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2349 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2352 position: 'absolute',
2353 left: gutter-scaledW+'px',
2354 right: '', // clear right property
2356 height: this.twoPage.height,
2357 width: scaledW+'px',
2358 backgroundColor: this.getPageBackgroundColor(prevL),
2359 borderRight: '1px solid black',
2363 $(this.prefetchedImgs[prevL]).css(leftCSS);
2365 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2367 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2370 position: 'absolute',
2374 height: this.twoPage.height,
2376 backgroundColor: this.getPageBackgroundColor(prevR),
2377 borderLeft: '1px solid black',
2381 $(this.prefetchedImgs[prevR]).css(rightCSS);
2383 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2387 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2388 // prepareFlipRightToLeft()
2389 //______________________________________________________________________________
2390 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2392 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2395 this.prefetchImg(nextL);
2396 this.prefetchImg(nextR);
2398 var height = this._getPageHeight(nextR);
2399 var width = this._getPageWidth(nextR);
2400 var middle = this.twoPage.middle;
2401 var top = this.twoPageTop();
2402 var scaledW = this.twoPage.height*width/height;
2404 var gutter = middle + this.gutterOffsetForIndex(nextL);
2406 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2407 $(this.prefetchedImgs[nextR]).css({
2408 position: 'absolute',
2411 backgroundColor: this.getPageBackgroundColor(nextR),
2412 height: this.twoPage.height,
2413 width: scaledW+'px',
2414 borderLeft: '1px solid black',
2418 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2420 height = this._getPageHeight(nextL);
2421 width = this._getPageWidth(nextL);
2422 scaledW = this.twoPage.height*width/height;
2424 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2425 $(this.prefetchedImgs[nextL]).css({
2426 position: 'absolute',
2427 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2429 backgroundColor: this.getPageBackgroundColor(nextL),
2430 height: this.twoPage.height,
2431 width: 0+'px', // Start at 0 width, then grow to the left
2432 borderRight: '1px solid black',
2436 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2440 // getNextLeafs() -- NOT RTL AWARE
2441 //______________________________________________________________________________
2442 // BookReader.prototype.getNextLeafs = function(o) {
2443 // //TODO: we might have two left or two right leafs in a row (damaged book)
2444 // //For now, assume that leafs are contiguous.
2446 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2447 // o.L = this.twoPage.currentIndexL+2;
2448 // o.R = this.twoPage.currentIndexL+3;
2451 // getprevLeafs() -- NOT RTL AWARE
2452 //______________________________________________________________________________
2453 // BookReader.prototype.getPrevLeafs = function(o) {
2454 // //TODO: we might have two left or two right leafs in a row (damaged book)
2455 // //For now, assume that leafs are contiguous.
2457 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2458 // o.L = this.twoPage.currentIndexL-2;
2459 // o.R = this.twoPage.currentIndexL-1;
2462 // pruneUnusedImgs()
2463 //______________________________________________________________________________
2464 BookReader.prototype.pruneUnusedImgs = function() {
2465 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2466 for (var key in this.prefetchedImgs) {
2467 //console.log('key is ' + key);
2468 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2469 //console.log('removing key '+ key);
2470 $(this.prefetchedImgs[key]).remove();
2472 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2473 //console.log('deleting key '+ key);
2474 delete this.prefetchedImgs[key];
2480 //______________________________________________________________________________
2481 BookReader.prototype.prefetch = function() {
2483 // $$$ We should check here if the current indices have finished
2484 // loading (with some timeout) before loading more page images
2485 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2487 // prefetch visible pages first
2488 this.prefetchImg(this.twoPage.currentIndexL);
2489 this.prefetchImg(this.twoPage.currentIndexR);
2491 var adjacentPagesToLoad = 3;
2493 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2494 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2496 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2497 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2499 // Load images spreading out from current
2500 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2501 var goingDown = lowCurrent - i;
2502 if (goingDown >= start) {
2503 this.prefetchImg(goingDown);
2505 var goingUp = highCurrent + i;
2506 if (goingUp <= end) {
2507 this.prefetchImg(goingUp);
2512 var lim = this.twoPage.currentIndexL-4;
2514 lim = Math.max(lim, 0);
2515 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2516 this.prefetchImg(i);
2519 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2520 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2521 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2522 this.prefetchImg(i);
2528 // getPageWidth2UP()
2529 //______________________________________________________________________________
2530 BookReader.prototype.getPageWidth2UP = function(index) {
2531 // We return the width based on the dominant height
2532 var height = this._getPageHeight(index);
2533 var width = this._getPageWidth(index);
2534 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2538 //______________________________________________________________________________
2539 BookReader.prototype.search = function(term) {
2540 term = term.replace(/\//g, ' '); // strip slashes
2541 this.searchTerm = term;
2542 $('#BookReaderSearchScript').remove();
2543 var script = document.createElement("script");
2544 script.setAttribute('id', 'BookReaderSearchScript');
2545 script.setAttribute("type", "text/javascript");
2546 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2547 document.getElementsByTagName('head')[0].appendChild(script);
2548 $('#BookReaderSearchBox').val(term);
2549 $('#BookReaderSearchResults').html('Searching...');
2552 // BRSearchCallback()
2553 //______________________________________________________________________________
2554 BookReader.prototype.BRSearchCallback = function(txt) {
2556 if (jQuery.browser.msie) {
2557 var dom=new ActiveXObject("Microsoft.XMLDOM");
2561 var parser = new DOMParser();
2562 var dom = parser.parseFromString(txt, "text/xml");
2565 $('#BookReaderSearchResults').empty();
2566 $('#BookReaderSearchResults').append('<ul>');
2568 for (var key in this.searchResults) {
2569 if (null != this.searchResults[key].div) {
2570 $(this.searchResults[key].div).remove();
2572 delete this.searchResults[key];
2575 var pages = dom.getElementsByTagName('PAGE');
2577 if (0 == pages.length) {
2578 // $$$ it would be nice to echo the (sanitized) search result here
2579 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2581 for (var i = 0; i < pages.length; i++){
2582 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2585 var re = new RegExp (/_(\d{4})\.djvu/);
2586 var reMatch = re.exec(pages[i].getAttribute('file'));
2587 var index = parseInt(reMatch[1], 10);
2588 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2590 var children = pages[i].childNodes;
2592 for (var j=0; j<children.length; j++) {
2593 //console.log(j + ' - ' + children[j].nodeName);
2594 //console.log(children[j].firstChild.nodeValue);
2595 if ('CONTEXT' == children[j].nodeName) {
2596 context += children[j].firstChild.nodeValue;
2597 } else if ('WORD' == children[j].nodeName) {
2598 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2600 var index = this.leafNumToIndex(index);
2601 if (null != index) {
2602 //coordinates are [left, bottom, right, top, [baseline]]
2603 //we'll skip baseline for now...
2604 var coords = children[j].getAttribute('coords').split(',',4);
2605 if (4 == coords.length) {
2606 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2611 var pageName = this.getPageName(index);
2612 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2613 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2614 //TODO: remove hardcoded instance name
2615 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2618 $('#BookReaderSearchResults').append('</ul>');
2620 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2621 $('#BookReaderSearchBox').val(this.searchTerm);
2623 this.updateSearchHilites();
2626 // updateSearchHilites()
2627 //______________________________________________________________________________
2628 BookReader.prototype.updateSearchHilites = function() {
2629 if (2 == this.mode) {
2630 this.updateSearchHilites2UP();
2632 this.updateSearchHilites1UP();
2636 // showSearchHilites1UP()
2637 //______________________________________________________________________________
2638 BookReader.prototype.updateSearchHilites1UP = function() {
2640 for (var key in this.searchResults) {
2642 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2643 var result = this.searchResults[key];
2644 if (null == result.div) {
2645 result.div = document.createElement('div');
2646 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2647 //console.log('appending ' + key);
2650 width: (result.r-result.l)/this.reduce + 'px',
2651 height: (result.b-result.t)/this.reduce + 'px',
2652 left: (result.l)/this.reduce + 'px',
2653 top: (result.t)/this.reduce +'px'
2657 //console.log(key + ' not displayed');
2658 this.searchResults[key].div=null;
2664 //______________________________________________________________________________
2665 // Returns the position of the gutter (line between the page images)
2666 BookReader.prototype.twoPageGutter = function() {
2667 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2671 //______________________________________________________________________________
2672 // Returns the offset for the top of the page images
2673 BookReader.prototype.twoPageTop = function() {
2674 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2677 // twoPageCoverWidth()
2678 //______________________________________________________________________________
2679 // Returns the width of the cover div given the total page width
2680 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2681 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2684 // twoPageGetViewCenter()
2685 //______________________________________________________________________________
2686 // Returns the percentage offset into twopageview div at the center of container div
2687 // { percentageX: float, percentageY: float }
2688 BookReader.prototype.twoPageGetViewCenter = function() {
2691 var containerOffset = $('#BRcontainer').offset();
2692 var viewOffset = $('#BRtwopageview').offset();
2693 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2694 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2699 // twoPageCenterView(percentageX, percentageY)
2700 //______________________________________________________________________________
2701 // Centers the point given by percentage from left,top of twopageview
2702 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2703 if ('undefined' == typeof(percentageX)) {
2706 if ('undefined' == typeof(percentageY)) {
2710 var viewWidth = $('#BRtwopageview').width();
2711 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2712 var intoViewX = percentageX * viewWidth;
2714 var viewHeight = $('#BRtwopageview').height();
2715 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2716 var intoViewY = percentageY * viewHeight;
2718 if (viewWidth < containerClientWidth) {
2719 // Can fit width without scrollbars - center by adjusting offset
2720 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2722 // Need to scroll to center
2723 $('#BRtwopageview').css('left', 0);
2724 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2727 if (viewHeight < containerClientHeight) {
2728 // Fits with scrollbars - add offset
2729 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2731 $('#BRtwopageview').css('top', 0);
2732 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2736 // twoPageFlipAreaHeight
2737 //______________________________________________________________________________
2738 // Returns the integer height of the click-to-flip areas at the edges of the book
2739 BookReader.prototype.twoPageFlipAreaHeight = function() {
2740 return parseInt(this.twoPage.height);
2743 // twoPageFlipAreaWidth
2744 //______________________________________________________________________________
2745 // Returns the integer width of the flip areas
2746 BookReader.prototype.twoPageFlipAreaWidth = function() {
2747 var max = 100; // $$$ TODO base on view width?
2750 var width = this.twoPage.width * 0.15;
2751 return parseInt(BookReader.util.clamp(width, min, max));
2754 // twoPageFlipAreaTop
2755 //______________________________________________________________________________
2756 // Returns integer top offset for flip areas
2757 BookReader.prototype.twoPageFlipAreaTop = function() {
2758 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2761 // twoPageLeftFlipAreaLeft
2762 //______________________________________________________________________________
2763 // Left offset for left flip area
2764 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2765 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2768 // twoPageRightFlipAreaLeft
2769 //______________________________________________________________________________
2770 // Left offset for right flip area
2771 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2772 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2775 // twoPagePlaceFlipAreas
2776 //______________________________________________________________________________
2777 // Readjusts position of flip areas based on current layout
2778 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2779 // We don't set top since it shouldn't change relative to view
2780 $(this.twoPage.leftFlipArea).css({
2781 left: this.twoPageLeftFlipAreaLeft() + 'px',
2782 width: this.twoPageFlipAreaWidth() + 'px'
2784 $(this.twoPage.rightFlipArea).css({
2785 left: this.twoPageRightFlipAreaLeft() + 'px',
2786 width: this.twoPageFlipAreaWidth() + 'px'
2790 // showSearchHilites2UP()
2791 //______________________________________________________________________________
2792 BookReader.prototype.updateSearchHilites2UP = function() {
2794 for (var key in this.searchResults) {
2795 key = parseInt(key, 10);
2796 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2797 var result = this.searchResults[key];
2798 if (null == result.div) {
2799 result.div = document.createElement('div');
2800 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2801 //console.log('appending ' + key);
2804 // We calculate the reduction factor for the specific page because it can be different
2805 // for each page in the spread
2806 var height = this._getPageHeight(key);
2807 var width = this._getPageWidth(key)
2808 var reduce = this.twoPage.height/height;
2809 var scaledW = parseInt(width*reduce);
2811 var gutter = this.twoPageGutter();
2813 if ('L' == this.getPageSide(key)) {
2814 pageL = gutter-scaledW;
2818 var pageT = this.twoPageTop();
2821 width: (result.r-result.l)*reduce + 'px',
2822 height: (result.b-result.t)*reduce + 'px',
2823 left: pageL+(result.l)*reduce + 'px',
2824 top: pageT+(result.t)*reduce +'px'
2828 //console.log(key + ' not displayed');
2829 if (null != this.searchResults[key].div) {
2830 //console.log('removing ' + key);
2831 $(this.searchResults[key].div).remove();
2833 this.searchResults[key].div=null;
2838 // removeSearchHilites()
2839 //______________________________________________________________________________
2840 BookReader.prototype.removeSearchHilites = function() {
2841 for (var key in this.searchResults) {
2842 if (null != this.searchResults[key].div) {
2843 $(this.searchResults[key].div).remove();
2844 this.searchResults[key].div=null;
2850 //______________________________________________________________________________
2851 BookReader.prototype.printPage = function() {
2852 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2854 /* iframe implementation
2856 if (null != this.printPopup) { // check if already showing
2859 this.printPopup = document.createElement("div");
2860 $(this.printPopup).css({
2861 position: 'absolute',
2863 left: ($('#BRcontainer').width()-400)/2 + 'px',
2866 border: "3px double #999999",
2868 backgroundColor: "#fff"
2869 }).appendTo('#BookReader');
2872 if (this.constMode1up == this.mode) {
2873 indexToPrint = this.firstIndex;
2875 indexToPrint = this.twoPage.currentIndexL;
2878 this.indexToPrint = indexToPrint;
2880 var htmlStr = '<div style="text-align: center;">';
2881 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>';
2882 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2883 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2884 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2885 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2886 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2888 htmlStr += '</div>';
2889 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2890 htmlStr += '</div>';
2892 this.printPopup.innerHTML = htmlStr;
2894 var iframe = document.createElement('iframe');
2895 iframe.id = 'printFrame';
2896 iframe.name = 'printFrame';
2897 iframe.width = '233px'; // 8.5 x 11 aspect
2898 iframe.height = '300px';
2900 var self = this; // closure
2902 $(iframe).load(function() {
2903 var doc = BookReader.util.getIFrameDocument(this);
2904 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2907 $('#printDiv').prepend(iframe);
2911 // Get print URI from current indices and mode
2912 BookReader.prototype.getPrintURI = function() {
2914 if (this.constMode2up == this.mode) {
2915 indexToPrint = this.twoPage.currentIndexL;
2917 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2920 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2921 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2922 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2924 if (this.constMode2up == this.mode) {
2925 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2926 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2927 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2929 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2932 return '/bookreader/print.php?' + options;
2935 /* iframe implementation
2936 BookReader.prototype.getPrintFrameContent = function(index) {
2937 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2938 // 8.5x11 so we should end up not overflowing on either paper size.
2939 var paperAspect = 8.5 / 11;
2940 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2944 // Rotate if possible and appropriate, to get larger image size on printed page
2945 if (this.canRotatePage(index)) {
2946 if (imageAspect > 1 && imageAspect > paperAspect) {
2947 // more wide than square, and more wide than paper
2949 imageAspect = 1/imageAspect;
2954 if (imageAspect > paperAspect) {
2955 // wider than paper, fit width
2956 fitAttrs = 'width="95%"';
2958 // taller than paper, fit height
2959 fitAttrs = 'height="95%"';
2962 var imageURL = this._getPageURI(index, 1, rotate);
2963 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2964 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2965 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2966 iframeStr += '</div>';
2967 iframeStr += '</body></html>';
2972 BookReader.prototype.updatePrintFrame = function(delta) {
2973 var newIndex = this.indexToPrint + delta;
2974 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2975 if (newIndex == this.indexToPrint) {
2978 this.indexToPrint = newIndex;
2979 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2980 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2985 //______________________________________________________________________________
2986 BookReader.prototype.showEmbedCode = function() {
2987 if (null != this.embedPopup) { // check if already showing
2991 this.embedPopup = document.createElement("div");
2992 $(this.embedPopup).css({
2993 position: 'absolute',
2995 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2998 border: "3px double #999999",
3000 backgroundColor: "#fff"
3001 }).appendTo('#BookReader');
3003 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
3004 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>';
3005 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
3006 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
3008 this.embedPopup.innerHTML = htmlStr;
3009 $(this.embedPopup).find('input').bind('click', function() {
3015 //______________________________________________________________________________
3016 BookReader.prototype.autoToggle = function() {
3018 var bComingFrom1up = false;
3019 if (2 != this.mode) {
3020 bComingFrom1up = true;
3024 // Change to autofit if book is too large
3025 if (this.reduce < this.twoPageGetAutofitReduce()) {
3026 this.zoom2up('auto');
3030 if (null == this.autoTimer) {
3031 this.flipSpeed = 2000;
3033 // $$$ Draw events currently cause layout problems when they occur during animation.
3034 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3035 // we workaround for now by not triggering immediate animation in that case.
3036 // See https://bugs.launchpad.net/gnubook/+bug/328327
3037 if (('rl' == this.pageProgression) && bComingFrom1up) {
3038 // don't flip immediately -- wait until timer fires
3041 this.flipFwdToIndex();
3044 $('#BRtoolbar .play').hide();
3045 $('#BRtoolbar .pause').show();
3046 this.autoTimer=setInterval(function(){
3047 if (self.animating) {return;}
3049 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3050 self.flipBackToIndex(1); // $$$ really what we want?
3052 self.flipFwdToIndex();
3061 //______________________________________________________________________________
3062 // Stop autoplay mode, allowing animations to finish
3063 BookReader.prototype.autoStop = function() {
3064 if (null != this.autoTimer) {
3065 clearInterval(this.autoTimer);
3066 this.flipSpeed = 'fast';
3067 $('#BRtoolbar .pause').hide();
3068 $('#BRtoolbar .play').show();
3069 this.autoTimer = null;
3073 // stopFlipAnimations
3074 //______________________________________________________________________________
3075 // Immediately stop flip animations. Callbacks are triggered.
3076 BookReader.prototype.stopFlipAnimations = function() {
3078 this.autoStop(); // Clear timers
3080 // Stop animation, clear queue, trigger callbacks
3081 if (this.leafEdgeTmp) {
3082 $(this.leafEdgeTmp).stop(false, true);
3084 jQuery.each(this.prefetchedImgs, function() {
3085 $(this).stop(false, true);
3088 // And again since animations also queued in callbacks
3089 if (this.leafEdgeTmp) {
3090 $(this.leafEdgeTmp).stop(false, true);
3092 jQuery.each(this.prefetchedImgs, function() {
3093 $(this).stop(false, true);
3098 // keyboardNavigationIsDisabled(event)
3099 // - returns true if keyboard navigation should be disabled for the event
3100 //______________________________________________________________________________
3101 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3102 if (event.target.tagName == "INPUT") {
3108 // gutterOffsetForIndex
3109 //______________________________________________________________________________
3111 // Returns the gutter offset for the spread containing the given index.
3112 // This function supports RTL
3113 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3115 // To find the offset of the gutter from the middle we calculate our percentage distance
3116 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3117 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3119 // But then again for RTL it's the opposite
3120 if ('rl' == this.pageProgression) {
3128 //______________________________________________________________________________
3129 // Returns the width of the leaf edge div for the page with index given
3130 BookReader.prototype.leafEdgeWidth = function(pindex) {
3131 // $$$ could there be single pixel rounding errors for L vs R?
3132 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3133 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3135 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3139 // jumpIndexForLeftEdgePageX
3140 //______________________________________________________________________________
3141 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3142 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3143 if ('rl' != this.pageProgression) {
3144 // LTR - flipping backward
3145 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3147 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3148 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3152 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3153 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3158 // jumpIndexForRightEdgePageX
3159 //______________________________________________________________________________
3160 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3161 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3162 if ('rl' != this.pageProgression) {
3164 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3165 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3168 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3169 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3174 BookReader.prototype.initToolbar = function(mode, ui) {
3176 $("#BookReader").append("<div id='BRtoolbar'>"
3177 + "<span id='BRtoolbarbuttons' style='float: right'>"
3178 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3179 + "<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>"
3180 + "<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>"
3181 + "<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>"
3182 + "<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>"
3183 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3187 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3188 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3189 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3190 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3191 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3192 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3193 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3196 + "<span id='#BRbooktitle'>"
3197 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3201 this.updateToolbarZoom(this.reduce); // Pretty format
3203 if (ui == "embed" || ui == "touch") {
3204 $("#BookReader a.logo").attr("target","_blank");
3207 // $$$ turn this into a member variable
3208 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3210 // We build in mode 2
3213 this.bindToolbarNavHandlers(jToolbar);
3215 // Setup tooltips -- later we could load these from a file for i18n
3216 var titles = { '.logo': 'Go to Archive.org',
3217 '.zoom_in': 'Zoom in',
3218 '.zoom_out': 'Zoom out',
3219 '.one_page_mode': 'One-page view',
3220 '.two_page_mode': 'Two-page view',
3221 '.thumbnail_mode': 'Thumbnail view',
3222 '.print': 'Print this page',
3223 '.embed': 'Embed bookreader',
3224 '.book_left': 'Flip left',
3225 '.book_right': 'Flip right',
3226 '.book_up': 'Page up',
3227 '.book_down': 'Page down',
3230 '.book_top': 'First page',
3231 '.book_bottom': 'Last page'
3233 if ('rl' == this.pageProgression) {
3234 titles['.book_leftmost'] = 'Last page';
3235 titles['.book_rightmost'] = 'First page';
3237 titles['.book_leftmost'] = 'First page';
3238 titles['.book_rightmost'] = 'Last page';
3241 for (var icon in titles) {
3242 jToolbar.find(icon).attr('title', titles[icon]);
3245 // Hide mode buttons and autoplay if 2up is not available
3246 // $$$ if we end up with more than two modes we should show the applicable buttons
3247 if ( !this.canSwitchToMode(this.constMode2up) ) {
3248 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3251 // Switch to requested mode -- binds other click handlers
3252 this.switchToolbarMode(mode);
3257 // switchToolbarMode
3258 //______________________________________________________________________________
3259 // Update the toolbar for the given mode (changes navigation buttons)
3260 // $$$ we should soon split the toolbar out into its own module
3261 BookReader.prototype.switchToolbarMode = function(mode) {
3264 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3265 $('#BRtoolbar .BRtoolbarmode2').hide();
3266 $('#BRtoolbar .BRtoolbarmode3').hide();
3267 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3268 } else if (2 == mode) {
3270 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3271 $('#BRtoolbar .BRtoolbarmode1').hide();
3272 $('#BRtoolbar .BRtoolbarmode3').hide();
3273 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3276 $('#BRtoolbar .BRtoolbarzoom').hide();
3277 $('#BRtoolbar .BRtoolbarmode2').hide();
3278 $('#BRtoolbar .BRtoolbarmode1').hide();
3279 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3283 // bindToolbarNavHandlers
3284 //______________________________________________________________________________
3285 // Binds the toolbar handlers
3286 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3288 var self = this; // closure
3290 jToolbar.find('.book_left').bind('click', function(e) {
3295 jToolbar.find('.book_right').bind('click', function(e) {
3300 jToolbar.find('.book_up').bind('click', function(e) {
3301 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3309 jToolbar.find('.book_down').bind('click', function(e) {
3310 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3318 jToolbar.find('.print').bind('click', function(e) {
3323 jToolbar.find('.embed').bind('click', function(e) {
3324 self.showEmbedCode();
3328 jToolbar.find('.play').bind('click', function(e) {
3333 jToolbar.find('.pause').bind('click', function(e) {
3338 jToolbar.find('.book_top').bind('click', function(e) {
3343 jToolbar.find('.book_bottom').bind('click', function(e) {
3348 jToolbar.find('.book_leftmost').bind('click', function(e) {
3353 jToolbar.find('.book_rightmost').bind('click', function(e) {
3359 // updateToolbarZoom(reduce)
3360 //______________________________________________________________________________
3361 // Update the displayed zoom factor based on reduction factor
3362 BookReader.prototype.updateToolbarZoom = function(reduce) {
3366 // $$$ TODO preserve zoom/fit for each mode
3367 if (this.mode == this.constMode2up) {
3368 autofit = this.twoPage.autofit;
3370 autofit = this.onePage.autofit;
3374 value = autofit[0].toUpperCase() + autofit.slice(1);
3376 value = (100 / reduce).toFixed(2);
3377 // Strip trailing zeroes and decimal if all zeroes
3378 value = value.replace(/0+$/,'');
3379 value = value.replace(/\.$/,'');
3382 $('#BRzoom').text(value);
3385 // firstDisplayableIndex
3386 //______________________________________________________________________________
3387 // Returns the index of the first visible page, dependent on the mode.
3388 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3389 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3390 BookReader.prototype.firstDisplayableIndex = function() {
3391 if (this.mode != this.constMode2up) {
3395 if ('rl' != this.pageProgression) {
3397 if (this.getPageSide(0) == 'L') {
3404 if (this.getPageSide(0) == 'R') {
3412 // lastDisplayableIndex
3413 //______________________________________________________________________________
3414 // Returns the index of the last visible page, dependent on the mode.
3415 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3416 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3417 BookReader.prototype.lastDisplayableIndex = function() {
3419 var lastIndex = this.numLeafs - 1;
3421 if (this.mode != this.constMode2up) {
3425 if ('rl' != this.pageProgression) {
3427 if (this.getPageSide(lastIndex) == 'R') {
3430 return lastIndex + 1;
3434 if (this.getPageSide(lastIndex) == 'L') {
3437 return lastIndex + 1;
3442 // shortTitle(maximumCharacters)
3444 // Returns a shortened version of the title with the maximum number of characters
3445 BookReader.prototype.shortTitle = function(maximumCharacters) {
3446 if (this.bookTitle.length < maximumCharacters) {
3447 return this.bookTitle;
3450 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3455 // Parameter related functions
3457 // updateFromParams(params)
3459 // Update ourselves from the params object.
3461 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3462 BookReader.prototype.updateFromParams = function(params) {
3463 if ('undefined' != typeof(params.mode)) {
3464 this.switchMode(params.mode);
3468 if ('undefined' != typeof(params.searchTerm)) {
3469 if (this.searchTerm != params.searchTerm) {
3470 this.search(params.searchTerm);
3474 // $$$ process /zoom
3476 // We only respect page if index is not set
3477 if ('undefined' != typeof(params.index)) {
3478 if (params.index != this.currentIndex()) {
3479 this.jumpToIndex(params.index);
3481 } else if ('undefined' != typeof(params.page)) {
3482 // $$$ this assumes page numbers are unique
3483 if (params.page != this.getPageNum(this.currentIndex())) {
3484 this.jumpToPage(params.page);
3488 // $$$ process /region
3489 // $$$ process /highlight
3492 // paramsFromFragment(urlFragment)
3494 // Returns a object with configuration parametes from a URL fragment.
3496 // E.g paramsFromFragment(window.location.hash)
3497 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3498 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3502 // For convenience we allow an initial # character (as from window.location.hash)
3503 // but don't require it
3504 if (urlFragment.substr(0,1) == '#') {
3505 urlFragment = urlFragment.substr(1);
3508 // Simple #nn syntax
3509 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3510 if ( !isNaN(oldStyleLeafNum) ) {
3511 params.index = oldStyleLeafNum;
3513 // Done processing if using old-style syntax
3517 // Split into key-value pairs
3518 var urlArray = urlFragment.split('/');
3520 for (var i = 0; i < urlArray.length; i += 2) {
3521 urlHash[urlArray[i]] = urlArray[i+1];
3525 if ('1up' == urlHash['mode']) {
3526 params.mode = this.constMode1up;
3527 } else if ('2up' == urlHash['mode']) {
3528 params.mode = this.constMode2up;
3529 } else if ('thumb' == urlHash['mode']) {
3530 params.mode = this.constModeThumb;
3534 if ('undefined' != typeof(urlHash['page'])) {
3535 // page was set -- may not be int
3536 params.page = urlHash['page'];
3539 // $$$ process /region
3540 // $$$ process /search
3542 if (urlHash['search'] != undefined) {
3543 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3546 // $$$ process /highlight
3551 // paramsFromCurrent()
3553 // Create a params object from the current parameters.
3554 BookReader.prototype.paramsFromCurrent = function() {
3558 var index = this.currentIndex();
3559 var pageNum = this.getPageNum(index);
3560 if ((pageNum === 0) || pageNum) {
3561 params.page = pageNum;
3564 params.index = index;
3565 params.mode = this.mode;
3571 if (this.searchHighlightVisible()) {
3572 params.searchTerm = this.searchTerm;
3578 // fragmentFromParams(params)
3580 // Create a fragment string from the params object.
3581 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3582 BookReader.prototype.fragmentFromParams = function(params) {
3583 var separator = '/';
3587 if ('undefined' != typeof(params.page)) {
3588 fragments.push('page', params.page);
3590 // Don't have page numbering -- use index instead
3591 fragments.push('page', 'n' + params.index);
3598 if ('undefined' != typeof(params.mode)) {
3599 if (params.mode == this.constMode1up) {
3600 fragments.push('mode', '1up');
3601 } else if (params.mode == this.constMode2up) {
3602 fragments.push('mode', '2up');
3603 } else if (params.mode == this.constModeThumb) {
3604 fragments.push('mode', 'thumb');
3606 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3611 if (params.searchTerm) {
3612 fragments.push('search', params.searchTerm);
3615 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3618 // getPageIndex(pageNum)
3620 // Returns the *highest* index the given page number, or undefined
3621 BookReader.prototype.getPageIndex = function(pageNum) {
3622 var pageIndices = this.getPageIndices(pageNum);
3624 if (pageIndices.length > 0) {
3625 return pageIndices[pageIndices.length - 1];
3631 // getPageIndices(pageNum)
3633 // Returns an array (possibly empty) of the indices with the given page number
3634 BookReader.prototype.getPageIndices = function(pageNum) {
3637 // Check for special "nXX" page number
3638 if (pageNum.slice(0,1) == 'n') {
3640 var pageIntStr = pageNum.slice(1, pageNum.length);
3641 var pageIndex = parseInt(pageIntStr);
3642 indices.push(pageIndex);
3645 // Do nothing... will run through page names and see if one matches
3650 for (i=0; i<this.numLeafs; i++) {
3651 if (this.getPageNum(i) == pageNum) {
3659 // getPageName(index)
3661 // Returns the name of the page as it should be displayed in the user interface
3662 BookReader.prototype.getPageName = function(index) {
3663 return 'Page ' + this.getPageNum(index);
3666 // updateLocationHash
3668 // Update the location hash from the current parameters. Call this instead of manually
3669 // using window.location.replace
3670 BookReader.prototype.updateLocationHash = function() {
3671 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3672 window.location.replace(newHash);
3674 // This is the variable checked in the timer. Only user-generated changes
3675 // to the URL will trigger the event.
3676 this.oldLocationHash = newHash;
3679 // startLocationPolling
3681 // Starts polling of window.location to see hash fragment changes
3682 BookReader.prototype.startLocationPolling = function() {
3683 var self = this; // remember who I am
3684 self.oldLocationHash = window.location.hash;
3686 if (this.locationPollId) {
3687 clearInterval(this.locationPollID);
3688 this.locationPollId = null;
3691 this.locationPollId = setInterval(function() {
3692 var newHash = window.location.hash;
3693 if (newHash != self.oldLocationHash) {
3694 if (newHash != self.oldUserHash) { // Only process new user hash once
3695 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3697 // Queue change if animating
3698 if (self.animating) {
3700 self.animationFinishedCallback = function() {
3701 self.updateFromParams(self.paramsFromFragment(newHash));
3703 } else { // update immediately
3704 self.updateFromParams(self.paramsFromFragment(newHash));
3706 self.oldUserHash = newHash;
3714 // Returns true if we can switch to the requested mode
3715 BookReader.prototype.canSwitchToMode = function(mode) {
3716 if (mode == this.constMode2up) {
3717 // check there are enough pages to display
3718 // $$$ this is a workaround for the mis-feature that we can't display
3719 // short books in 2up mode
3720 if (this.numLeafs < 6) {
3728 // searchHighlightVisible
3730 // Returns true if a search highlight is currently being displayed
3731 BookReader.prototype.searchHighlightVisible = function() {
3732 if (this.constMode2up == this.mode) {
3733 if (this.searchResults[this.twoPage.currentIndexL]
3734 || this.searchResults[this.twoPage.currentIndexR]) {
3738 if (this.searchResults[this.currentIndex()]) {
3745 // getPageBackgroundColor
3747 // Returns a CSS property string for the background color for the given page
3748 // $$$ turn into regular CSS?
3749 BookReader.prototype.getPageBackgroundColor = function(index) {
3750 if (index >= 0 && index < this.numLeafs) {
3752 return this.pageDefaultBackgroundColor;
3760 // Returns the page width for the given index, or first or last page if out of range
3761 BookReader.prototype._getPageWidth = function(index) {
3762 // Synthesize a page width for pages not actually present in book.
3763 // May or may not be the best approach.
3764 // If index is out of range we return the width of first or last page
3765 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3766 return this.getPageWidth(index);
3771 // Returns the page height for the given index, or first or last page if out of range
3772 BookReader.prototype._getPageHeight= function(index) {
3773 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3774 return this.getPageHeight(index);
3779 // Returns the page URI or transparent image if out of range
3780 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3781 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3782 return this.imagesBaseURL + "/transparent.png";
3785 if ('undefined' == typeof(reduce)) {
3786 // reduce not passed in
3787 // $$$ this probably won't work for thumbnail mode
3788 var ratio = this.getPageHeight(index) / this.twoPage.height;
3790 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3793 } else if (ratio < 4) {
3795 } else if (ratio < 8) {
3797 } else if (ratio < 16) {
3799 } else if (ratio < 32) {
3807 return this.getPageURI(index, reduce, rotate);
3810 // Library functions
3812 disableSelect: function(jObject) {
3813 // Bind mouse handlers
3814 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3815 jObject.bind('mousedown', function(e) {
3816 // $$$ check here for right-click and don't disable. Also use jQuery style
3817 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3820 // Special hack for IE7
3821 jObject[0].onselectstart = function(e) { return false; };
3824 clamp: function(value, min, max) {
3825 return Math.min(Math.max(value, min), max);
3828 notInArray: function(value, array) {
3829 // inArray returns -1 or undefined if value not in array
3830 return ! (jQuery.inArray(value, array) >= 0);
3833 getIFrameDocument: function(iframe) {
3834 // Adapted from http://xkr.us/articles/dom/iframe-document/
3835 var outer = (iframe.contentWindow || iframe.contentDocument);
3836 return (outer.document || outer);
3839 decodeURIComponentPlus: function(value) {
3840 // Decodes a URI component and converts '+' to ' '
3841 return decodeURIComponent(value).replace(/\+/g, ' ');
3844 encodeURIComponentPlus: function(value) {
3845 // Encodes a URI component and converts ' ' to '+'
3846 return encodeURIComponent(value).replace(/%20/g, '+');
3848 // The final property here must NOT have a comma after it - IE7