2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
6 BookReader is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 BookReader is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
45 this.thumbWidth = 100; // will be overridden during prepareThumbnailView
46 this.thumbRowBuffer = 2; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.thumbMaxLoading = 4; // number of thumbnails to load at once
49 this.displayedRows=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 // $$$ provide finer grained zooming
87 this.reductionFactors = [ {reduce: 0.5, autofit: null},
88 {reduce: 1, autofit: null},
89 {reduce: 2, autofit: null},
90 {reduce: 4, autofit: null},
91 {reduce: 8, autofit: null},
92 {reduce: 16, autofit: null} ];
94 // Object to hold parameters related to 1up mode
96 autofit: 'height' // valid values are height, width, none
99 // Object to hold parameters related to 2up mode
101 coverInternalPadding: 10, // Width of cover
102 coverExternalPadding: 10, // Padding outside of cover
103 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
107 // Background color for pages (e.g. when loading page image)
108 // $$$ TODO dynamically calculate based on page images
109 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
115 //______________________________________________________________________________
116 BookReader.prototype.init = function() {
118 var startIndex = undefined;
119 this.pageScale = this.reduce; // preserve current reduce
121 // Find start index and mode if set in location hash
122 var params = this.paramsFromFragment(window.location.hash);
124 if ('undefined' != typeof(params.index)) {
125 startIndex = params.index;
126 } else if ('undefined' != typeof(params.page)) {
127 startIndex = this.getPageIndex(params.page);
130 if ('undefined' == typeof(startIndex)) {
131 if ('undefined' != typeof(this.titleLeaf)) {
132 startIndex = this.leafNumToIndex(this.titleLeaf);
136 if ('undefined' == typeof(startIndex)) {
140 if ('undefined' != typeof(params.mode)) {
141 this.mode = params.mode;
144 // Set document title -- may have already been set in enclosing html for
145 // search engine visibility
146 document.title = this.shortTitle(50);
148 // Sanitize parameters
149 if ( !this.canSwitchToMode( this.mode ) ) {
150 this.mode = this.constMode1up;
153 $("#BookReader").empty();
155 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
156 $("#BookReader").append("<div id='BRcontainer'></div>");
157 $("#BRcontainer").append("<div id='BRpageview'></div>");
159 $("#BRcontainer").bind('scroll', this, function(e) {
163 this.setupKeyListeners();
164 this.startLocationPolling();
166 $(window).bind('resize', this, function(e) {
167 //console.log('resize!');
168 if (1 == e.data.mode) {
169 //console.log('centering 1page view');
170 e.data.centerPageView();
171 $('#BRpageview').empty()
172 e.data.displayedIndices = [];
173 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
175 } else if (3 == e.data.mode){
176 e.data.prepareThumbnailView();
178 //console.log('drawing 2 page view');
180 // We only need to prepare again in autofit (size of spread changes)
181 if (e.data.twoPage.autofit) {
182 e.data.prepareTwoPageView();
184 // Re-center if the scrollbars have disappeared
185 var center = e.data.twoPageGetViewCenter();
186 var doRecenter = false;
187 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
188 center.percentageX = 0.5;
191 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
192 center.percentageY = 0.5;
196 e.data.twoPageCenterView(center.percentageX, center.percentageY);
202 $('.BRpagediv1up').bind('mousedown', this, function(e) {
203 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
204 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
208 // $$$ refactor this so it's enough to set the first index and call preparePageView
209 // (get rid of mode-specific logic at this point)
210 if (1 == this.mode) {
211 this.firstIndex = startIndex;
212 this.prepareOnePageView();
213 this.jumpToIndex(startIndex);
214 } else if (3 == this.mode) {
215 this.firstIndex = startIndex;
216 this.prepareThumbnailView();
217 this.jumpToIndex(startIndex);
219 //this.resizePageView();
221 this.displayedIndices=[0];
222 this.firstIndex = startIndex;
223 this.displayedIndices = [this.firstIndex];
224 //console.log('titleLeaf: %d', this.titleLeaf);
225 //console.log('displayedIndices: %s', this.displayedIndices);
226 this.prepareTwoPageView();
229 // Enact other parts of initial params
230 this.updateFromParams(params);
233 BookReader.prototype.setupKeyListeners = function() {
246 // We use document here instead of window to avoid a bug in jQuery on IE7
247 $(document).keydown(function(e) {
249 // Keyboard navigation
250 if (!self.keyboardNavigationIsDisabled(e)) {
254 // In 1up mode page scrolling is handled by browser
255 if (2 == self.mode) {
262 if (2 == self.mode) {
276 if (2 == self.mode) {
282 if (2 == self.mode) {
293 //______________________________________________________________________________
294 BookReader.prototype.drawLeafs = function() {
295 if (1 == this.mode) {
296 this.drawLeafsOnePage();
297 } else if (3 == this.mode) {
298 this.drawLeafsThumbnail();
300 this.drawLeafsTwoPage();
305 // bindGestures(jElement)
306 //______________________________________________________________________________
307 BookReader.prototype.bindGestures = function(jElement) {
309 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
311 if (e.originalEvent.scale > 1.5) {
313 } else if (e.originalEvent.scale < 0.6) {
320 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
321 //console.log('setting handler');
322 //console.log(element.tagName);
324 $(element).unbind('tap').bind('tap', data, function(e) {
329 // drawLeafsOnePage()
330 //______________________________________________________________________________
331 BookReader.prototype.drawLeafsOnePage = function() {
332 //alert('drawing leafs!');
336 var scrollTop = $('#BRcontainer').attr('scrollTop');
337 var scrollBottom = scrollTop + $('#BRcontainer').height();
338 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
340 var indicesToDisplay = [];
345 for (i=0; i<this.numLeafs; i++) {
346 var height = parseInt(this._getPageHeight(i)/this.reduce);
348 leafBottom += height;
349 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
350 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
351 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
352 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
353 if (topInView | bottomInView | middleInView) {
354 //console.log('displayed: ' + this.displayedIndices);
355 //console.log('to display: ' + i);
356 indicesToDisplay.push(i);
358 leafTop += height +10;
362 var firstIndexToDraw = indicesToDisplay[0];
363 this.firstIndex = firstIndexToDraw;
365 // Update hash, but only if we're currently displaying a leaf
366 // Hack that fixes #365790
367 if (this.displayedIndices.length > 0) {
368 this.updateLocationHash();
371 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
373 indicesToDisplay.unshift(firstIndexToDraw);
376 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
377 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
378 indicesToDisplay.push(lastIndexToDraw+1);
383 for (i=0; i<firstIndexToDraw; i++) {
384 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
387 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
388 var viewWidth = $('#BRcontainer').attr('scrollWidth');
391 for (i=0; i<indicesToDisplay.length; i++) {
392 var index = indicesToDisplay[i];
393 var height = parseInt(this._getPageHeight(index)/this.reduce);
395 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
396 var width = parseInt(this._getPageWidth(index)/this.reduce);
397 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
398 var div = document.createElement("div");
399 div.className = 'BRpagediv1up';
400 div.id = 'pagediv'+index;
401 div.style.position = "absolute";
402 $(div).css('top', leafTop + 'px');
403 var left = (viewWidth-width)>>1;
404 if (left<0) left = 0;
405 $(div).css('left', left+'px');
406 $(div).css('width', width+'px');
407 $(div).css('height', height+'px');
408 //$(div).text('loading...');
410 $('#BRpageview').append(div);
412 var img = document.createElement("img");
413 img.src = this._getPageURI(index, this.reduce, 0);
414 $(img).css('width', width+'px');
415 $(img).css('height', height+'px');
419 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
422 leafTop += height +10;
426 for (i=0; i<this.displayedIndices.length; i++) {
427 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
428 var index = this.displayedIndices[i];
429 //console.log('Removing leaf ' + index);
430 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
431 $('#pagediv'+index).remove();
433 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
437 this.displayedIndices = indicesToDisplay.slice();
438 this.updateSearchHilites();
440 if (null != this.getPageNum(firstIndexToDraw)) {
441 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
443 $("#BRpagenum").val('');
446 this.updateToolbarZoom(this.reduce);
450 // drawLeafsThumbnail()
451 //______________________________________________________________________________
452 // If seekIndex is defined, the view will be drawn with that page visible (without any
453 // animated scrolling)
454 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
455 //alert('drawing leafs!');
458 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
460 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
474 // Will be set to top of requested seek index, if set
477 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
478 for (i=0; i<this.numLeafs; i++) {
479 leafWidth = this.thumbWidth;
480 if (rightPos + (leafWidth + this.padding) > viewWidth){
486 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
487 if (leafMap[currentRow].leafs===undefined) {
488 leafMap[currentRow].leafs = [];
489 leafMap[currentRow].height = 0;
490 leafMap[currentRow].top = 0;
492 leafMap[currentRow].leafs[leafIndex] = {};
493 leafMap[currentRow].leafs[leafIndex].num = i;
494 leafMap[currentRow].leafs[leafIndex].left = rightPos;
496 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
497 if (leafHeight > leafMap[currentRow].height) {
498 leafMap[currentRow].height = leafHeight;
500 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
501 rightPos += leafWidth + this.padding;
502 if (rightPos > maxRight) { maxRight = rightPos; }
505 if (i == seekIndex) {
506 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
510 // reset the bottom position based on thumbnails
511 $('#BRpageview').height(bottomPos);
513 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
515 // If seekTop is defined, seeking was requested and target found
516 if (typeof(seekTop) != 'undefined') {
517 $('#BRcontainer').scrollTop( seekTop );
520 var scrollTop = $('#BRcontainer').attr('scrollTop');
521 var scrollBottom = scrollTop + $('#BRcontainer').height();
525 var rowsToDisplay = [];
527 // Visible leafs with least/greatest index
528 var leastVisible = this.numLeafs - 1;
531 // Determine the thumbnails in view
532 for (i=0; i<leafMap.length; i++) {
533 leafBottom += this.padding + leafMap[i].height;
534 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
535 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
536 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
537 if (topInView | bottomInView | middleInView) {
538 //console.log('row to display: ' + j);
539 rowsToDisplay.push(i);
540 if (leafMap[i].leafs[0].num < leastVisible) {
541 leastVisible = leafMap[i].leafs[0].num;
543 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
544 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
547 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
548 leafTop = leafBottom;
551 // create a buffer of preloaded rows before and after the visible rows
552 var firstRow = rowsToDisplay[0];
553 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
554 for (i=1; i<this.thumbRowBuffer+1; i++) {
555 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
557 for (i=1; i<this.thumbRowBuffer+1; i++) {
558 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
561 // Create the thumbnail divs and images (lazy loaded)
570 for (i=0; i<rowsToDisplay.length; i++) {
571 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
572 row = rowsToDisplay[i];
574 for (j=0; j<leafMap[row].leafs.length; j++) {
576 leaf = leafMap[row].leafs[j].num;
578 leafWidth = this.thumbWidth;
579 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
580 leafTop = leafMap[row].top;
581 left = leafMap[row].leafs[index].left + pageViewBuffer;
582 if ('rl' == this.pageProgression){
583 left = viewWidth - leafWidth - left;
586 div = document.createElement("div");
587 div.id = 'pagediv'+leaf;
588 div.style.position = "absolute";
589 div.className = "BRpagedivthumb";
591 left += this.padding;
592 $(div).css('top', leafTop + 'px');
593 $(div).css('left', left+'px');
594 $(div).css('width', leafWidth+'px');
595 $(div).css('height', leafHeight+'px');
596 //$(div).text('loading...');
598 // link to page in single page mode
599 link = document.createElement("a");
600 $(link).data('leaf', leaf);
601 $(link).bind('tap', function(event) {
602 self.firstIndex = $(this).data('leaf');
603 self.switchMode(self.constMode1up);
604 event.preventDefault();
607 // $$$ we don't actually go to this URL (click is handled in handler above)
608 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
611 $('#BRpageview').append(div);
613 img = document.createElement("img");
614 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
616 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
617 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
618 .addClass('BRlazyload')
619 // Store the URL of the image that will replace this one
620 .data('srcURL', this._getPageURI(leaf, thumbReduce));
622 //console.log('displaying thumbnail: ' + leaf);
627 // Remove thumbnails that are not to be displayed
629 for (i=0; i<this.displayedRows.length; i++) {
630 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
631 row = this.displayedRows[i];
633 // $$$ Safari doesn't like the comprehension
634 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
635 //console.log('Removing row ' + row + ' ' + rowLeafs);
637 for (k=0; k<leafMap[row].leafs.length; k++) {
638 index = leafMap[row].leafs[k].num;
639 //console.log('Removing leaf ' + index);
640 $('#pagediv'+index).remove();
644 var mRow = this.displayedRows[i];
645 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
646 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
651 // Update which page is considered current to make sure a visible page is the current one
652 var currentIndex = this.currentIndex();
653 // console.log('current ' + currentIndex);
654 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
655 if (currentIndex < leastVisible) {
656 this.setCurrentIndex(leastVisible);
657 } else if (currentIndex > mostVisible) {
658 this.setCurrentIndex(mostVisible);
661 this.displayedRows = rowsToDisplay.slice();
663 // Update hash, but only if we're currently displaying a leaf
664 // Hack that fixes #365790
665 if (this.displayedRows.length > 0) {
666 this.updateLocationHash();
669 // remove previous highlights
670 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
672 // highlight current page
673 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
675 this.lazyLoadThumbnails();
677 // Update page number box. $$$ refactor to function
678 if (null !== this.getPageNum(this.currentIndex())) {
679 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
681 $("#BRpagenum").val('');
684 this.updateToolbarZoom(this.reduce);
687 BookReader.prototype.lazyLoadThumbnails = function() {
689 // console.log('lazy load');
691 // We check the complete property since load may not be fired if loading from the cache
692 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
694 var loading = $('.BRlazyloading').length;
695 var toLoad = this.thumbMaxLoading - loading;
697 // console.log(' ' + loading + ' thumbnails loading');
698 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
703 // $$$ TODO load those near top (but not beyond) page view first
704 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
705 self.lazyLoadImage(this);
710 BookReader.prototype.lazyLoadImage = function (dummyImage) {
711 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
713 var img = new Image();
717 .addClass('BRlazyloading')
718 .one('load', function() {
719 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
721 $(this).removeClass('BRlazyloading');
723 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
724 // we call the function after a slight delay. Also the img.complete property
725 // is not yet set in IE8 inside this onload handler
726 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
728 .one('error', function() {
729 // Remove class so we no longer count as loading
730 $(this).removeClass('BRlazyloading');
732 .attr( { width: $(dummyImage).width(),
733 height: $(dummyImage).height(),
734 src: $(dummyImage).data('srcURL')
737 // replace with the new img
738 $(dummyImage).before(img).remove();
740 img = null; // tidy up closure
744 // drawLeafsTwoPage()
745 //______________________________________________________________________________
746 BookReader.prototype.drawLeafsTwoPage = function() {
747 var scrollTop = $('#BRtwopageview').attr('scrollTop');
748 var scrollBottom = scrollTop + $('#BRtwopageview').height();
750 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
752 var indexL = this.twoPage.currentIndexL;
754 var heightL = this._getPageHeight(indexL);
755 var widthL = this._getPageWidth(indexL);
757 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
758 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
759 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
760 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
761 //console.log(leafEdgeWidthL);
763 var middle = this.twoPage.middle; // $$$ getter instead?
764 var top = this.twoPageTop();
765 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
767 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
768 this.twoPage.gutter = this.twoPageGutter();
770 this.prefetchImg(indexL);
771 $(this.prefetchedImgs[indexL]).css({
772 position: 'absolute',
773 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
776 backgroundColor: this.getPageBackgroundColor(indexL),
777 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
778 width: this.twoPage.scaledWL + 'px',
779 borderRight: '1px solid black',
781 }).appendTo('#BRtwopageview');
783 var indexR = this.twoPage.currentIndexR;
784 var heightR = this._getPageHeight(indexR);
785 var widthR = this._getPageWidth(indexR);
787 // $$$ should use getwidth2up?
788 //var scaledWR = this.twoPage.height*widthR/heightR;
789 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
790 this.prefetchImg(indexR);
791 $(this.prefetchedImgs[indexR]).css({
792 position: 'absolute',
793 left: this.twoPage.gutter+'px',
796 backgroundColor: this.getPageBackgroundColor(indexR),
797 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
798 width: this.twoPage.scaledWR + 'px',
799 borderLeft: '1px solid black',
801 }).appendTo('#BRtwopageview');
804 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
805 this.setMouseHandlers2UP();
806 this.twoPageSetCursor();
808 this.updatePageNumBox2UP();
809 this.updateToolbarZoom(this.reduce);
811 // this.twoPagePlaceFlipAreas(); // No longer used
815 // updatePageNumBox2UP
816 //______________________________________________________________________________
817 BookReader.prototype.updatePageNumBox2UP = function() {
818 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
819 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
821 $("#BRpagenum").val('');
823 this.updateLocationHash();
827 //______________________________________________________________________________
828 BookReader.prototype.loadLeafs = function() {
832 if (null == this.timer) {
833 this.timer=setTimeout(function(){self.drawLeafs()},250);
835 clearTimeout(this.timer);
836 this.timer=setTimeout(function(){self.drawLeafs()},250);
842 // Pass 1 to zoom in, anything else to zoom out
843 //______________________________________________________________________________
844 BookReader.prototype.zoom = function(direction) {
846 case this.constMode1up:
847 if (direction == 1) {
849 return this.zoom1up('bigger');
851 return this.zoom1up('smaller');
854 case this.constMode2up:
855 return this.zoom2up(direction);
857 case this.constModeThumb:
858 return this.zoomThumb(direction);
864 //______________________________________________________________________________
865 BookReader.prototype.zoom1up = function(direction) {
867 if (2 == this.mode) { //can only zoom in 1-page mode
872 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
873 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
874 this.autofit = reduceFactor.autofit;
876 this.pageScale = this.reduce; // preserve current reduce
877 this.resizePageView();
879 $('#BRpageview').empty()
880 this.displayedIndices = [];
883 this.updateToolbarZoom(this.reduce);
885 // Recalculate search hilites
886 this.removeSearchHilites();
887 this.updateSearchHilites();
892 //______________________________________________________________________________
893 BookReader.prototype.resizePageView = function() {
895 // $$$ This code assumes 1up mode
896 // e.g. does not preserve position in thumbnail mode
897 // See http://bugs.launchpad.net/bookreader/+bug/552972
900 case this.constMode1up:
901 case this.constMode2up:
902 this.resizePageView1up();
904 case this.constModeThumb:
905 this.prepareThumbnailView( this.currentIndex() );
908 alert('Resize not implemented for this mode');
912 BookReader.prototype.resizePageView1up = function() {
915 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
916 var viewWidth = $('#BRcontainer').attr('clientWidth');
918 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
919 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
920 var oldPageViewHeight = $('#BRpageview').height();
921 var oldPageViewWidth = $('#BRpageview').width();
923 var oldCenterY = this.centerY1up();
924 var oldCenterX = this.centerX1up();
926 if (0 != oldPageViewHeight) {
927 var scrollRatio = oldCenterY / oldPageViewHeight;
932 // Recalculate 1up reduction factors
933 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
934 $('#BRcontainer').attr('clientHeight') );
935 // Update current reduce (if in autofit)
936 // this.onePageUpdateReduce(); // XXX
938 for (i=0; i<this.numLeafs; i++) {
939 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
940 var width = parseInt(this._getPageWidth(i)/this.reduce);
941 if (width>viewWidth) viewWidth=width;
943 $('#BRpageview').height(viewHeight);
944 $('#BRpageview').width(viewWidth);
946 var newCenterY = scrollRatio*viewHeight;
947 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
948 $('#BRcontainer').attr('scrollTop', newTop);
950 // We use clientWidth here to avoid miscalculating due to scroll bar
951 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
952 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
953 newLeft = Math.max(newLeft, 0);
954 $('#BRcontainer').attr('scrollLeft', newLeft);
955 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
957 //this.centerPageView();
960 this.removeSearchHilites();
961 this.updateSearchHilites();
966 //______________________________________________________________________________
967 // Returns the current offset of the viewport center in scaled document coordinates.
968 BookReader.prototype.centerX1up = function() {
970 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
971 centerX = $('#BRpageview').width();
973 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
975 centerX = Math.floor(centerX);
980 //______________________________________________________________________________
981 // Returns the current offset of the viewport center in scaled document coordinates.
982 BookReader.prototype.centerY1up = function() {
983 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
984 return Math.floor(centerY);
988 //______________________________________________________________________________
989 BookReader.prototype.centerPageView = function() {
991 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
992 var clientWidth = $('#BRcontainer').attr('clientWidth');
993 //console.log('sW='+scrollWidth+' cW='+clientWidth);
994 if (scrollWidth > clientWidth) {
995 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1000 // zoom2up(direction)
1001 //______________________________________________________________________________
1002 BookReader.prototype.zoom2up = function(direction) {
1004 // Hard stop autoplay
1005 this.stopFlipAnimations();
1007 // Get new zoom state
1008 var newZoom = this.twoPageNextReduce(this.reduce, direction);
1009 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
1012 this.twoPage.autofit = newZoom.autofit;
1013 this.reduce = newZoom.reduce;
1014 this.pageScale = this.reduce; // preserve current reduce
1016 // Preserve view center position
1017 var oldCenter = this.twoPageGetViewCenter();
1019 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1020 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1021 if (1 == direction) {
1022 for (var img in this.prefetchedImgs) {
1023 delete this.prefetchedImgs[img];
1027 // Prepare view with new center to minimize visual glitches
1028 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1031 BookReader.prototype.zoomThumb = function(direction) {
1032 var oldColumns = this.thumbColumns;
1033 switch (direction) {
1035 this.thumbColumns += 1;
1038 this.thumbColumns -= 1;
1043 if (this.thumbColumns < 2) {
1044 this.thumbColumns = 2;
1045 } else if (this.thumbColumns > 8) {
1046 this.thumbColumns = 8;
1049 if (this.thumbColumns != oldColumns) {
1050 this.prepareThumbnailView();
1054 // Returns the width per thumbnail to display the requested number of columns
1055 // Note: #BRpageview must already exist since its width is used to calculate the
1057 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1058 var padding = (thumbnailColumns + 1) * this.padding;
1059 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1060 return parseInt(width);
1063 // quantizeReduce(reduce)
1064 //______________________________________________________________________________
1065 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1066 BookReader.prototype.quantizeReduce = function(reduce) {
1067 var quantized = this.reductionFactors[0].reduce;
1068 var distance = Math.abs(reduce - quantized);
1069 for (var i = 1; i < this.reductionFactors.length; i++) {
1070 newDistance = Math.abs(reduce - this.reductionFactors[i].reduce);
1071 if (newDistance < distance) {
1072 distance = newDistance;
1073 quantized = this.reductionFactors[i].reduce;
1080 // reductionFactors should be array of sorted reduction factors
1081 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1082 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1084 // XXX add 'closest', to replace quantize function
1086 if (direction == 'bigger') {
1087 var newReduceIndex = 0;
1089 for (var i = 1; i < reductionFactors.length; i++) {
1090 if (reductionFactors[i].reduce < currentReduce) {
1094 return reductionFactors[newReduceIndex];
1096 } else if (direction == 'smaller') { // zoom out
1097 var lastIndex = reductionFactors.length - 1;
1098 var newReduceIndex = lastIndex;
1100 for (var i = lastIndex; i >= 0; i--) {
1101 if (reductionFactors[i].reduce > currentReduce) {
1105 return reductionFactors[newReduceIndex];
1108 // Asked for specific autofit mode
1109 for (var i = 0; i < reductionFactors.length; i++) {
1110 if (reductionFactors[i].autofit == direction) {
1111 return reductionFactors[i];
1115 alert('Could not find reduction factor for direction ' + direction);
1116 return reductionFactors[0];
1120 BookReader.prototype._reduceSort = function(a, b) {
1121 return a.reduce - b.reduce;
1124 // twoPageNextReduce()
1125 //______________________________________________________________________________
1126 // Returns the next reduction level
1127 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1129 var autofitReduce = this.twoPageGetAutofitReduce();
1131 if (0 == direction) { // autofit
1132 result.autofit = true;
1133 result.reduce = autofitReduce;
1135 } else if (1 == direction) { // zoom in
1136 var newReduce = this.reductionFactors[0];
1138 for (var i = 1; i < this.reductionFactors.length; i++) {
1139 if (this.reductionFactors[i] < reduce) {
1140 newReduce = this.reductionFactors[i];
1144 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1146 result.autofit = true;
1147 result.reduce = autofitReduce;
1149 result.autofit = false;
1150 result.reduce = newReduce;
1153 } else { // zoom out
1154 var lastIndex = this.reductionFactors.length - 1;
1155 var newReduce = this.reductionFactors[lastIndex];
1157 for (var i = lastIndex; i >= 0; i--) {
1158 if (this.reductionFactors[i] > reduce) {
1159 newReduce = this.reductionFactors[i];
1163 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1165 result.autofit = true;
1166 result.reduce = autofitReduce;
1168 result.autofit = false;
1169 result.reduce = newReduce;
1177 //______________________________________________________________________________
1178 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1179 BookReader.prototype.jumpToPage = function(pageNum) {
1181 var pageIndex = this.getPageIndex(pageNum);
1183 if ('undefined' != typeof(pageIndex)) {
1186 this.jumpToIndex(pageIndex);
1187 $('#BRcontainer').attr('scrollTop', leafTop);
1196 //______________________________________________________________________________
1197 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1199 if (2 == this.mode) {
1202 // By checking against min/max we do nothing if requested index
1204 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1205 this.flipBackToIndex(index);
1206 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1207 this.flipFwdToIndex(index);
1210 } else if (3 == this.mode) {
1211 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1221 for (i=0; i<(index+1); i++) {
1222 leafWidth = this.thumbWidth;
1223 if (rightPos + (leafWidth + this.padding) > viewWidth){
1229 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1230 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1231 if (leafIndex==0) { leafTop = bottomPos; }
1232 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1233 rightPos += leafWidth + this.padding;
1236 this.firstIndex=index;
1237 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1240 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1247 for (i=0; i<index; i++) {
1248 h = parseInt(this._getPageHeight(i)/this.reduce);
1249 leafTop += h + this.padding;
1253 //console.log('pageY ' + pageY);
1254 var offset = parseInt( (pageY) / this.reduce);
1255 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1256 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1261 var offset = parseInt( (pageX) / this.reduce);
1262 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1266 //$('#BRcontainer').attr('scrollTop', leafTop);
1267 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1273 //______________________________________________________________________________
1274 BookReader.prototype.switchMode = function(mode) {
1276 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1278 if (mode == this.mode) {
1282 if (!this.canSwitchToMode(mode)) {
1287 this.removeSearchHilites();
1290 this.switchToolbarMode(mode);
1292 // reinstate scale if moving from thumbnail view
1293 if (this.pageScale != this.reduce) {
1294 this.reduce = this.pageScale;
1297 // $$$ TODO preserve center of view when switching between mode
1298 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1301 this.reduce = this.quantizeReduce(this.reduce);
1302 this.prepareOnePageView();
1303 } else if (3 == mode) {
1304 this.reduce = this.quantizeReduce(this.reduce);
1305 this.prepareThumbnailView();
1307 // $$$ why don't we save autofit?
1308 this.twoPage.autofit = false; // Take zoom level from other mode
1309 this.reduce = this.quantizeReduce(this.reduce);
1310 this.prepareTwoPageView();
1311 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1316 //prepareOnePageView()
1317 //______________________________________________________________________________
1318 BookReader.prototype.prepareOnePageView = function() {
1320 // var startLeaf = this.displayedIndices[0];
1321 var startLeaf = this.currentIndex();
1323 $('#BRcontainer').empty();
1324 $('#BRcontainer').css({
1325 overflowY: 'scroll',
1329 $("#BRcontainer").append("<div id='BRpageview'></div>");
1331 // Attaches to first child - child must be present
1332 $('#BRcontainer').dragscrollable();
1333 this.bindGestures($('#BRcontainer'));
1335 // $$$ keep select enabled for now since disabling it breaks keyboard
1336 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1337 // BookReader.util.disableSelect($('#BRpageview'));
1339 this.resizePageView();
1341 this.jumpToIndex(startLeaf);
1342 this.displayedIndices = [];
1344 this.drawLeafsOnePage();
1347 //prepareThumbnailView()
1348 //______________________________________________________________________________
1349 BookReader.prototype.prepareThumbnailView = function() {
1351 $('#BRcontainer').empty();
1352 $('#BRcontainer').css({
1353 overflowY: 'scroll',
1357 $("#BRcontainer").append("<div id='BRpageview'></div>");
1359 $('#BRcontainer').dragscrollable();
1360 this.bindGestures($('#BRcontainer'));
1362 // $$$ keep select enabled for now since disabling it breaks keyboard
1363 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1364 // BookReader.util.disableSelect($('#BRpageview'));
1366 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1367 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1369 this.displayedRows = [];
1371 // Draw leafs with current index directly in view (no animating to the index)
1372 this.drawLeafsThumbnail( this.currentIndex() );
1376 // prepareTwoPageView()
1377 //______________________________________________________________________________
1378 // Some decisions about two page view:
1380 // Both pages will be displayed at the same height, even if they were different physical/scanned
1381 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1382 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1383 // aspect ratio to determine the height.
1385 // The two page view div is resized to keep the middle of the book in the middle of the div
1386 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1387 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1388 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1389 $('#BRcontainer').empty();
1390 $('#BRcontainer').css('overflow', 'auto');
1392 // We want to display two facing pages. We may be missing
1393 // one side of the spread because it is the first/last leaf,
1394 // foldouts, missing pages, etc
1396 //var targetLeaf = this.displayedIndices[0];
1397 var targetLeaf = this.firstIndex;
1399 if (targetLeaf < this.firstDisplayableIndex()) {
1400 targetLeaf = this.firstDisplayableIndex();
1403 if (targetLeaf > this.lastDisplayableIndex()) {
1404 targetLeaf = this.lastDisplayableIndex();
1407 //this.twoPage.currentIndexL = null;
1408 //this.twoPage.currentIndexR = null;
1409 //this.pruneUnusedImgs();
1411 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1412 this.twoPage.currentIndexL = currentSpreadIndices[0];
1413 this.twoPage.currentIndexR = currentSpreadIndices[1];
1414 this.firstIndex = this.twoPage.currentIndexL;
1416 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1418 this.pruneUnusedImgs();
1419 this.prefetch(); // Preload images or reload if scaling has changed
1421 //console.dir(this.twoPage);
1423 // Add the two page view
1424 // $$$ Can we get everything set up and then append?
1425 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1427 // Attaches to first child, so must come after we add the page view
1428 $('#BRcontainer').dragscrollable();
1429 this.bindGestures($('#BRcontainer'));
1431 // $$$ calculate first then set
1432 $('#BRtwopageview').css( {
1433 height: this.twoPage.totalHeight + 'px',
1434 width: this.twoPage.totalWidth + 'px',
1435 position: 'absolute'
1438 // If there will not be scrollbars (e.g. when zooming out) we center the book
1439 // since otherwise the book will be stuck off-center
1440 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1441 centerPercentageX = 0.5;
1443 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1444 centerPercentageY = 0.5;
1447 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1449 this.twoPage.coverDiv = document.createElement('div');
1450 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1451 width: this.twoPage.bookCoverDivWidth + 'px',
1452 height: this.twoPage.bookCoverDivHeight+'px',
1453 visibility: 'visible',
1454 position: 'absolute',
1455 left: this.twoPage.bookCoverDivLeft + 'px',
1456 top: this.twoPage.bookCoverDivTop+'px',
1457 }).appendTo('#BRtwopageview');
1459 this.leafEdgeR = document.createElement('div');
1460 this.leafEdgeR.className = 'BRleafEdgeR';
1461 $(this.leafEdgeR).css({
1462 width: this.twoPage.leafEdgeWidthR + 'px',
1463 height: this.twoPage.height-1 + 'px',
1464 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1465 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1466 }).appendTo('#BRtwopageview');
1468 this.leafEdgeL = document.createElement('div');
1469 this.leafEdgeL.className = 'BRleafEdgeL';
1470 $(this.leafEdgeL).css({
1471 width: this.twoPage.leafEdgeWidthL + 'px',
1472 height: this.twoPage.height-1 + 'px',
1473 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1474 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1475 }).appendTo('#BRtwopageview');
1477 div = document.createElement('div');
1478 $(div).attr('id', 'BRbookspine').css({
1479 width: this.twoPage.bookSpineDivWidth+'px',
1480 height: this.twoPage.bookSpineDivHeight+'px',
1481 left: this.twoPage.bookSpineDivLeft+'px',
1482 top: this.twoPage.bookSpineDivTop+'px'
1483 }).appendTo('#BRtwopageview');
1485 var self = this; // for closure
1487 /* Flip areas no longer used
1488 this.twoPage.leftFlipArea = document.createElement('div');
1489 this.twoPage.leftFlipArea.className = 'BRfliparea';
1490 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1492 width: this.twoPageFlipAreaWidth() + 'px',
1493 height: this.twoPageFlipAreaHeight() + 'px',
1494 position: 'absolute',
1495 left: this.twoPageLeftFlipAreaLeft() + 'px',
1496 top: this.twoPageFlipAreaTop() + 'px',
1499 }).bind('click', function(e) {
1501 }).bind('mousedown', function(e) {
1503 }).appendTo('#BRtwopageview');
1505 this.twoPage.rightFlipArea = document.createElement('div');
1506 this.twoPage.rightFlipArea.className = 'BRfliparea';
1507 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1509 width: this.twoPageFlipAreaWidth() + 'px',
1510 height: this.twoPageFlipAreaHeight() + 'px',
1511 position: 'absolute',
1512 left: this.twoPageRightFlipAreaLeft() + 'px',
1513 top: this.twoPageFlipAreaTop() + 'px',
1516 }).bind('click', function(e) {
1518 }).bind('mousedown', function(e) {
1520 }).appendTo('#BRtwopageview');
1523 this.prepareTwoPagePopUp();
1525 this.displayedIndices = [];
1527 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1528 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1530 this.drawLeafsTwoPage();
1531 this.updateToolbarZoom(this.reduce);
1535 this.removeSearchHilites();
1536 this.updateSearchHilites();
1540 // prepareTwoPagePopUp()
1542 // This function prepares the "View Page n" popup that shows while the mouse is
1543 // over the left/right "stack of sheets" edges. It also binds the mouse
1544 // events for these divs.
1545 //______________________________________________________________________________
1546 BookReader.prototype.prepareTwoPagePopUp = function() {
1548 this.twoPagePopUp = document.createElement('div');
1549 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1550 $(this.twoPagePopUp).css({
1552 }).appendTo('#BRcontainer');
1553 $(this.twoPagePopUp).hide();
1555 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1556 $(e.data.twoPagePopUp).show();
1559 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1560 $(e.data.twoPagePopUp).hide();
1563 $(this.leafEdgeL).bind('click', this, function(e) {
1565 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1566 e.data.jumpToIndex(jumpIndex);
1569 $(this.leafEdgeR).bind('click', this, function(e) {
1571 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1572 e.data.jumpToIndex(jumpIndex);
1575 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1577 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1578 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1580 // $$$ TODO: Make sure popup is positioned so that it is in view
1581 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1582 $(e.data.twoPagePopUp).css({
1583 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1584 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1588 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1590 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1591 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1593 // $$$ TODO: Make sure popup is positioned so that it is in view
1594 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1595 $(e.data.twoPagePopUp).css({
1596 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1597 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1602 // calculateSpreadSize()
1603 //______________________________________________________________________________
1604 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1605 // this.twoPage.currentIndexR
1606 // This function sets this.twoPage.height, twoPage.width
1608 BookReader.prototype.calculateSpreadSize = function() {
1610 var firstIndex = this.twoPage.currentIndexL;
1611 var secondIndex = this.twoPage.currentIndexR;
1612 //console.log('first page is ' + firstIndex);
1614 // Calculate page sizes and total leaf width
1616 if ( this.twoPage.autofit) {
1617 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1619 // set based on reduction factor
1620 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1623 // Both pages together
1624 this.twoPage.height = spreadSize.height;
1625 this.twoPage.width = spreadSize.width;
1628 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1629 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1632 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1633 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1634 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1638 // The width of the book cover div. The combined width of both pages, twice the width
1639 // of the book cover internal padding (2*10) and the page edges
1640 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1641 // The height of the book cover div
1642 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1645 // We calculate the total width and height for the div so that we can make the book
1647 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1648 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1649 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1650 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1651 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1652 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1654 // We want to minimize the unused space in two-up mode (maximize the amount of page
1655 // shown). We give width to the leaf edges and these widths change (though the sum
1656 // of the two remains constant) as we flip through the book. With the book
1657 // cover centered and fixed in the BRcontainer div the page images will meet
1658 // at the "gutter" which is generally offset from the center.
1659 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1660 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1662 // The left edge of the book cover moves depending on the width of the pages
1663 // $$$ change to getter
1664 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1665 // The top edge of the book cover stays a fixed distance from the top
1666 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1669 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1670 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1671 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1674 this.reduce = spreadSize.reduce; // $$$ really set this here?
1677 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1680 // We check which page is closest to a "normal" page and use that to set the height
1681 // for both pages. This means that foldouts and other odd size pages will be displayed
1682 // smaller than the nominal zoom amount.
1683 var canon5Dratio = 1.5;
1686 height: this._getPageHeight(firstIndex),
1687 width: this._getPageWidth(firstIndex)
1691 height: this._getPageHeight(secondIndex),
1692 width: this._getPageWidth(secondIndex)
1695 var firstIndexRatio = first.height / first.width;
1696 var secondIndexRatio = second.height / second.width;
1697 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1700 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1701 ratio = firstIndexRatio;
1702 //console.log('using firstIndexRatio ' + ratio);
1704 ratio = secondIndexRatio;
1705 //console.log('using secondIndexRatio ' + ratio);
1708 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1709 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1710 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1712 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1713 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1715 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1716 ideal.width -= 10; // $$$ fudge factor
1717 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1718 ideal.height -= 20; // fudge factor
1719 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1721 if (ideal.height/ratio <= ideal.width) {
1723 ideal.width = parseInt(ideal.height/ratio);
1726 ideal.height = parseInt(ideal.width*ratio);
1729 // $$$ check this logic with large spreads
1730 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1735 // getSpreadSizeFromReduce()
1736 //______________________________________________________________________________
1737 // Returns the spread size calculated from the reduction factor for the given pages
1738 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1739 var spreadSize = {};
1740 // $$$ Scale this based on reduce?
1741 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1742 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1743 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1745 // $$$ Possibly incorrect -- we should make height "dominant"
1746 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1747 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1748 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1749 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1750 spreadSize.reduce = reduce;
1755 // twoPageGetAutofitReduce()
1756 //______________________________________________________________________________
1757 // Returns the current ideal reduction factor
1758 BookReader.prototype.twoPageGetAutofitReduce = function() {
1759 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1760 return spreadSize.reduce;
1763 BookReader.prototype.onePageGetAutofitWidth = function() {
1764 var widthPadding = 50;
1765 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1768 BookReader.prototype.onePageGetAutofitHeight = function() {
1769 var heightPadding = 10;
1770 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - heightPadding * 2);
1773 BookReader.prototype.getMedianPageSize = function() {
1774 if (this._medianPageSize) {
1775 return this._medianPageSize;
1778 // A little expensive but we just do it once
1781 for (var i = 0; i < this.numLeafs; i++) {
1782 widths.push(this.getPageWidth(i));
1783 heights.push(this.getPageHeight(i));
1789 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1790 return this._medianPageSize;
1793 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1794 // the autofit reduction factors.
1795 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1796 this.onePage.reductionFactors = this.reductionFactors.concat(
1798 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1799 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1801 this.onePage.reductionFactors.sort(this._reduceSort);
1804 // twoPageSetCursor()
1805 //______________________________________________________________________________
1806 // Set the cursor for two page view
1807 BookReader.prototype.twoPageSetCursor = function() {
1808 // console.log('setting cursor');
1809 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1810 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1811 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1812 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1814 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1815 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1820 //______________________________________________________________________________
1821 // Returns the currently active index.
1822 BookReader.prototype.currentIndex = function() {
1823 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1824 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1825 return this.firstIndex; // $$$ TODO page in center of view would be better
1826 } else if (this.mode == this.constMode2up) {
1827 // Only allow indices that are actually present in book
1828 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1830 throw 'currentIndex called for unimplemented mode ' + this.mode;
1834 // setCurrentIndex(index)
1835 //______________________________________________________________________________
1836 // Sets the idea of current index without triggering other actions such as animation.
1837 // Compare to jumpToIndex which animates to that index
1838 BookReader.prototype.setCurrentIndex = function(index) {
1839 this.firstIndex = index;
1844 //______________________________________________________________________________
1845 // Flip the right page over onto the left
1846 BookReader.prototype.right = function() {
1847 if ('rl' != this.pageProgression) {
1857 //______________________________________________________________________________
1858 // Flip to the rightmost page
1859 BookReader.prototype.rightmost = function() {
1860 if ('rl' != this.pageProgression) {
1868 //______________________________________________________________________________
1869 // Flip the left page over onto the right.
1870 BookReader.prototype.left = function() {
1871 if ('rl' != this.pageProgression) {
1881 //______________________________________________________________________________
1882 // Flip to the leftmost page
1883 BookReader.prototype.leftmost = function() {
1884 if ('rl' != this.pageProgression) {
1892 //______________________________________________________________________________
1893 BookReader.prototype.next = function() {
1894 if (2 == this.mode) {
1896 this.flipFwdToIndex(null);
1898 if (this.firstIndex < this.lastDisplayableIndex()) {
1899 this.jumpToIndex(this.firstIndex+1);
1905 //______________________________________________________________________________
1906 BookReader.prototype.prev = function() {
1907 if (2 == this.mode) {
1909 this.flipBackToIndex(null);
1911 if (this.firstIndex >= 1) {
1912 this.jumpToIndex(this.firstIndex-1);
1917 BookReader.prototype.first = function() {
1918 this.jumpToIndex(this.firstDisplayableIndex());
1921 BookReader.prototype.last = function() {
1922 this.jumpToIndex(this.lastDisplayableIndex());
1926 //______________________________________________________________________________
1927 // Scrolls down one screen view
1928 BookReader.prototype.scrollDown = function() {
1929 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1930 $('#BRcontainer').animate(
1931 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1932 450, 'easeInOutQuint'
1941 //______________________________________________________________________________
1942 // Scrolls up one screen view
1943 BookReader.prototype.scrollUp = function() {
1944 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1945 $('#BRcontainer').animate(
1946 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1947 450, 'easeInOutQuint'
1956 // flipBackToIndex()
1957 //______________________________________________________________________________
1958 // to flip back one spread, pass index=null
1959 BookReader.prototype.flipBackToIndex = function(index) {
1961 if (1 == this.mode) return;
1963 var leftIndex = this.twoPage.currentIndexL;
1965 if (this.animating) return;
1967 if (null != this.leafEdgeTmp) {
1968 alert('error: leafEdgeTmp should be null!');
1972 if (null == index) {
1973 index = leftIndex-2;
1975 //if (index<0) return;
1977 var previousIndices = this.getSpreadIndices(index);
1979 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1983 this.animating = true;
1985 if ('rl' != this.pageProgression) {
1986 // Assume LTR and we are going backward
1987 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1988 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1990 // RTL and going backward
1991 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1992 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1996 // flipLeftToRight()
1997 //______________________________________________________________________________
1998 // Flips the page on the left towards the page on the right
1999 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2001 var leftLeaf = this.twoPage.currentIndexL;
2003 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2004 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2005 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2007 var currWidthL = this.getPageWidth2UP(leftLeaf);
2008 var newWidthL = this.getPageWidth2UP(newIndexL);
2009 var newWidthR = this.getPageWidth2UP(newIndexR);
2011 var top = this.twoPageTop();
2012 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2014 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2015 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2017 //animation strategy:
2018 // 0. remove search highlight, if any.
2019 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2020 // of the left leaf and where the user clicked in the leaf edge.
2021 // Note that if this function was triggered by left() and not a
2022 // mouse click, the width of leafEdgeTmp is very small (zero px).
2023 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2024 // leftLeaf to width=0.
2025 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2026 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2027 // its new full width.
2028 // 4. After step 3 is finished, do the following:
2029 // - remove leafEdgeTmp from the dom.
2030 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2031 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2032 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2033 // and width=newLeafEdgeWidthL.
2034 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2035 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2036 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2037 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2038 // - prefetch new adjacent leafs.
2039 // - set up click handlers for both new left and right leafs.
2040 // - redraw the search highlight.
2041 // - update the pagenum box and the url.
2044 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2046 this.leafEdgeTmp = document.createElement('div');
2047 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2048 $(this.leafEdgeTmp).css({
2049 width: leafEdgeTmpW + 'px',
2050 height: this.twoPage.height-1 + 'px',
2051 left: leftEdgeTmpLeft + 'px',
2054 }).appendTo('#BRtwopageview');
2056 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2057 $(this.leafEdgeL).css({
2058 width: newLeafEdgeWidthL+'px',
2059 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2062 // Left gets the offset of the current left leaf from the document
2063 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2064 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2065 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2067 // We change the left leaf to right positioning
2068 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2069 $(this.prefetchedImgs[leftLeaf]).css({
2074 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2075 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2079 this.removeSearchHilites();
2081 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2082 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2084 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2085 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2087 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2088 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2089 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2091 $(self.leafEdgeR).css({
2092 // Moves the right leaf edge
2093 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2094 left: gutter+newWidthR+'px'
2097 $(self.leafEdgeL).css({
2098 // Moves and resizes the left leaf edge
2099 width: newLeafEdgeWidthL+'px',
2100 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2103 // Resizes the brown border div
2104 $(self.twoPage.coverDiv).css({
2105 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2106 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2109 $(self.leafEdgeTmp).remove();
2110 self.leafEdgeTmp = null;
2112 // $$$ TODO refactor with opposite direction flip
2114 self.twoPage.currentIndexL = newIndexL;
2115 self.twoPage.currentIndexR = newIndexR;
2116 self.twoPage.scaledWL = newWidthL;
2117 self.twoPage.scaledWR = newWidthR;
2118 self.twoPage.gutter = gutter;
2120 self.firstIndex = self.twoPage.currentIndexL;
2121 self.displayedIndices = [newIndexL, newIndexR];
2122 self.pruneUnusedImgs();
2124 self.animating = false;
2126 self.updateSearchHilites2UP();
2127 self.updatePageNumBox2UP();
2129 // self.twoPagePlaceFlipAreas(); // No longer used
2130 self.setMouseHandlers2UP();
2131 self.twoPageSetCursor();
2133 if (self.animationFinishedCallback) {
2134 self.animationFinishedCallback();
2135 self.animationFinishedCallback = null;
2143 //______________________________________________________________________________
2144 // Whether we flip left or right is dependent on the page progression
2145 // to flip forward one spread, pass index=null
2146 BookReader.prototype.flipFwdToIndex = function(index) {
2148 if (this.animating) return;
2150 if (null != this.leafEdgeTmp) {
2151 alert('error: leafEdgeTmp should be null!');
2155 if (null == index) {
2156 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2158 if (index > this.lastDisplayableIndex()) return;
2160 this.animating = true;
2162 var nextIndices = this.getSpreadIndices(index);
2164 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2166 if ('rl' != this.pageProgression) {
2167 // We did not specify RTL
2168 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2169 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2172 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2173 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2177 // flipRightToLeft(nextL, nextR, gutter)
2178 // $$$ better not to have to pass gutter in
2179 //______________________________________________________________________________
2180 // Flip from left to right and show the nextL and nextR indices on those sides
2181 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2182 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2183 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2184 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2185 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2187 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2189 var top = this.twoPageTop();
2190 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2192 var middle = this.twoPage.middle;
2193 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2195 this.leafEdgeTmp = document.createElement('div');
2196 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2197 $(this.leafEdgeTmp).css({
2198 width: leafEdgeTmpW + 'px',
2199 height: this.twoPage.height-1 + 'px',
2200 left: gutter+scaledW+'px',
2203 }).appendTo('#BRtwopageview');
2205 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2206 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2208 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2209 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2210 var newWidthL = this.getPageWidth2UP(newIndexL);
2211 var newWidthR = this.getPageWidth2UP(newIndexR);
2213 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2215 var self = this; // closure-tastic!
2217 var speed = this.flipSpeed;
2219 this.removeSearchHilites();
2221 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2222 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2223 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2224 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2225 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2227 $(self.leafEdgeL).css({
2228 width: newLeafEdgeWidthL+'px',
2229 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2232 // Resizes the book cover
2233 $(self.twoPage.coverDiv).css({
2234 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2235 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2238 $(self.leafEdgeTmp).remove();
2239 self.leafEdgeTmp = null;
2241 self.twoPage.currentIndexL = newIndexL;
2242 self.twoPage.currentIndexR = newIndexR;
2243 self.twoPage.scaledWL = newWidthL;
2244 self.twoPage.scaledWR = newWidthR;
2245 self.twoPage.gutter = gutter;
2247 self.firstIndex = self.twoPage.currentIndexL;
2248 self.displayedIndices = [newIndexL, newIndexR];
2249 self.pruneUnusedImgs();
2251 self.animating = false;
2254 self.updateSearchHilites2UP();
2255 self.updatePageNumBox2UP();
2257 // self.twoPagePlaceFlipAreas(); // No longer used
2258 self.setMouseHandlers2UP();
2259 self.twoPageSetCursor();
2261 if (self.animationFinishedCallback) {
2262 self.animationFinishedCallback();
2263 self.animationFinishedCallback = null;
2269 // setMouseHandlers2UP
2270 //______________________________________________________________________________
2271 BookReader.prototype.setMouseHandlers2UP = function() {
2272 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2280 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2283 e.data.self.right();
2290 //______________________________________________________________________________
2291 BookReader.prototype.prefetchImg = function(index) {
2292 var pageURI = this._getPageURI(index);
2294 // Load image if not loaded or URI has changed (e.g. due to scaling)
2295 var loadImage = false;
2296 if (undefined == this.prefetchedImgs[index]) {
2297 //console.log('no image for ' + index);
2299 } else if (pageURI != this.prefetchedImgs[index].uri) {
2300 //console.log('uri changed for ' + index);
2305 //console.log('prefetching ' + index);
2306 var img = document.createElement("img");
2308 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2309 this.prefetchedImgs[index] = img;
2314 // prepareFlipLeftToRight()
2316 //______________________________________________________________________________
2318 // Prepare to flip the left page towards the right. This corresponds to moving
2319 // backward when the page progression is left to right.
2320 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2322 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2324 this.prefetchImg(prevL);
2325 this.prefetchImg(prevR);
2327 var height = this._getPageHeight(prevL);
2328 var width = this._getPageWidth(prevL);
2329 var middle = this.twoPage.middle;
2330 var top = this.twoPageTop();
2331 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2333 // The gutter is the dividing line between the left and right pages.
2334 // It is offset from the middle to create the illusion of thickness to the pages
2335 var gutter = middle + this.gutterOffsetForIndex(prevL);
2337 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2338 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2339 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2342 position: 'absolute',
2343 left: gutter-scaledW+'px',
2344 right: '', // clear right property
2346 height: this.twoPage.height,
2347 width: scaledW+'px',
2348 backgroundColor: this.getPageBackgroundColor(prevL),
2349 borderRight: '1px solid black',
2353 $(this.prefetchedImgs[prevL]).css(leftCSS);
2355 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2357 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2360 position: 'absolute',
2364 height: this.twoPage.height,
2366 backgroundColor: this.getPageBackgroundColor(prevR),
2367 borderLeft: '1px solid black',
2371 $(this.prefetchedImgs[prevR]).css(rightCSS);
2373 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2377 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2378 // prepareFlipRightToLeft()
2379 //______________________________________________________________________________
2380 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2382 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2385 this.prefetchImg(nextL);
2386 this.prefetchImg(nextR);
2388 var height = this._getPageHeight(nextR);
2389 var width = this._getPageWidth(nextR);
2390 var middle = this.twoPage.middle;
2391 var top = this.twoPageTop();
2392 var scaledW = this.twoPage.height*width/height;
2394 var gutter = middle + this.gutterOffsetForIndex(nextL);
2396 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2397 $(this.prefetchedImgs[nextR]).css({
2398 position: 'absolute',
2401 backgroundColor: this.getPageBackgroundColor(nextR),
2402 height: this.twoPage.height,
2403 width: scaledW+'px',
2404 borderLeft: '1px solid black',
2408 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2410 height = this._getPageHeight(nextL);
2411 width = this._getPageWidth(nextL);
2412 scaledW = this.twoPage.height*width/height;
2414 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2415 $(this.prefetchedImgs[nextL]).css({
2416 position: 'absolute',
2417 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2419 backgroundColor: this.getPageBackgroundColor(nextL),
2420 height: this.twoPage.height,
2421 width: 0+'px', // Start at 0 width, then grow to the left
2422 borderRight: '1px solid black',
2426 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2430 // getNextLeafs() -- NOT RTL AWARE
2431 //______________________________________________________________________________
2432 // BookReader.prototype.getNextLeafs = function(o) {
2433 // //TODO: we might have two left or two right leafs in a row (damaged book)
2434 // //For now, assume that leafs are contiguous.
2436 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2437 // o.L = this.twoPage.currentIndexL+2;
2438 // o.R = this.twoPage.currentIndexL+3;
2441 // getprevLeafs() -- NOT RTL AWARE
2442 //______________________________________________________________________________
2443 // BookReader.prototype.getPrevLeafs = function(o) {
2444 // //TODO: we might have two left or two right leafs in a row (damaged book)
2445 // //For now, assume that leafs are contiguous.
2447 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2448 // o.L = this.twoPage.currentIndexL-2;
2449 // o.R = this.twoPage.currentIndexL-1;
2452 // pruneUnusedImgs()
2453 //______________________________________________________________________________
2454 BookReader.prototype.pruneUnusedImgs = function() {
2455 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2456 for (var key in this.prefetchedImgs) {
2457 //console.log('key is ' + key);
2458 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2459 //console.log('removing key '+ key);
2460 $(this.prefetchedImgs[key]).remove();
2462 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2463 //console.log('deleting key '+ key);
2464 delete this.prefetchedImgs[key];
2470 //______________________________________________________________________________
2471 BookReader.prototype.prefetch = function() {
2473 // $$$ We should check here if the current indices have finished
2474 // loading (with some timeout) before loading more page images
2475 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2477 // prefetch visible pages first
2478 this.prefetchImg(this.twoPage.currentIndexL);
2479 this.prefetchImg(this.twoPage.currentIndexR);
2481 var adjacentPagesToLoad = 3;
2483 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2484 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2486 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2487 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2489 // Load images spreading out from current
2490 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2491 var goingDown = lowCurrent - i;
2492 if (goingDown >= start) {
2493 this.prefetchImg(goingDown);
2495 var goingUp = highCurrent + i;
2496 if (goingUp <= end) {
2497 this.prefetchImg(goingUp);
2502 var lim = this.twoPage.currentIndexL-4;
2504 lim = Math.max(lim, 0);
2505 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2506 this.prefetchImg(i);
2509 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2510 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2511 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2512 this.prefetchImg(i);
2518 // getPageWidth2UP()
2519 //______________________________________________________________________________
2520 BookReader.prototype.getPageWidth2UP = function(index) {
2521 // We return the width based on the dominant height
2522 var height = this._getPageHeight(index);
2523 var width = this._getPageWidth(index);
2524 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2528 //______________________________________________________________________________
2529 BookReader.prototype.search = function(term) {
2530 term = term.replace(/\//g, ' '); // strip slashes
2531 this.searchTerm = term;
2532 $('#BookReaderSearchScript').remove();
2533 var script = document.createElement("script");
2534 script.setAttribute('id', 'BookReaderSearchScript');
2535 script.setAttribute("type", "text/javascript");
2536 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2537 document.getElementsByTagName('head')[0].appendChild(script);
2538 $('#BookReaderSearchBox').val(term);
2539 $('#BookReaderSearchResults').html('Searching...');
2542 // BRSearchCallback()
2543 //______________________________________________________________________________
2544 BookReader.prototype.BRSearchCallback = function(txt) {
2546 if (jQuery.browser.msie) {
2547 var dom=new ActiveXObject("Microsoft.XMLDOM");
2551 var parser = new DOMParser();
2552 var dom = parser.parseFromString(txt, "text/xml");
2555 $('#BookReaderSearchResults').empty();
2556 $('#BookReaderSearchResults').append('<ul>');
2558 for (var key in this.searchResults) {
2559 if (null != this.searchResults[key].div) {
2560 $(this.searchResults[key].div).remove();
2562 delete this.searchResults[key];
2565 var pages = dom.getElementsByTagName('PAGE');
2567 if (0 == pages.length) {
2568 // $$$ it would be nice to echo the (sanitized) search result here
2569 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2571 for (var i = 0; i < pages.length; i++){
2572 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2575 var re = new RegExp (/_(\d{4})\.djvu/);
2576 var reMatch = re.exec(pages[i].getAttribute('file'));
2577 var index = parseInt(reMatch[1], 10);
2578 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2580 var children = pages[i].childNodes;
2582 for (var j=0; j<children.length; j++) {
2583 //console.log(j + ' - ' + children[j].nodeName);
2584 //console.log(children[j].firstChild.nodeValue);
2585 if ('CONTEXT' == children[j].nodeName) {
2586 context += children[j].firstChild.nodeValue;
2587 } else if ('WORD' == children[j].nodeName) {
2588 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2590 var index = this.leafNumToIndex(index);
2591 if (null != index) {
2592 //coordinates are [left, bottom, right, top, [baseline]]
2593 //we'll skip baseline for now...
2594 var coords = children[j].getAttribute('coords').split(',',4);
2595 if (4 == coords.length) {
2596 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2601 var pageName = this.getPageName(index);
2602 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2603 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2604 //TODO: remove hardcoded instance name
2605 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2608 $('#BookReaderSearchResults').append('</ul>');
2610 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2611 $('#BookReaderSearchBox').val(this.searchTerm);
2613 this.updateSearchHilites();
2616 // updateSearchHilites()
2617 //______________________________________________________________________________
2618 BookReader.prototype.updateSearchHilites = function() {
2619 if (2 == this.mode) {
2620 this.updateSearchHilites2UP();
2622 this.updateSearchHilites1UP();
2626 // showSearchHilites1UP()
2627 //______________________________________________________________________________
2628 BookReader.prototype.updateSearchHilites1UP = function() {
2630 for (var key in this.searchResults) {
2632 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2633 var result = this.searchResults[key];
2634 if (null == result.div) {
2635 result.div = document.createElement('div');
2636 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2637 //console.log('appending ' + key);
2640 width: (result.r-result.l)/this.reduce + 'px',
2641 height: (result.b-result.t)/this.reduce + 'px',
2642 left: (result.l)/this.reduce + 'px',
2643 top: (result.t)/this.reduce +'px'
2647 //console.log(key + ' not displayed');
2648 this.searchResults[key].div=null;
2654 //______________________________________________________________________________
2655 // Returns the position of the gutter (line between the page images)
2656 BookReader.prototype.twoPageGutter = function() {
2657 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2661 //______________________________________________________________________________
2662 // Returns the offset for the top of the page images
2663 BookReader.prototype.twoPageTop = function() {
2664 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2667 // twoPageCoverWidth()
2668 //______________________________________________________________________________
2669 // Returns the width of the cover div given the total page width
2670 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2671 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2674 // twoPageGetViewCenter()
2675 //______________________________________________________________________________
2676 // Returns the percentage offset into twopageview div at the center of container div
2677 // { percentageX: float, percentageY: float }
2678 BookReader.prototype.twoPageGetViewCenter = function() {
2681 var containerOffset = $('#BRcontainer').offset();
2682 var viewOffset = $('#BRtwopageview').offset();
2683 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2684 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2689 // twoPageCenterView(percentageX, percentageY)
2690 //______________________________________________________________________________
2691 // Centers the point given by percentage from left,top of twopageview
2692 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2693 if ('undefined' == typeof(percentageX)) {
2696 if ('undefined' == typeof(percentageY)) {
2700 var viewWidth = $('#BRtwopageview').width();
2701 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2702 var intoViewX = percentageX * viewWidth;
2704 var viewHeight = $('#BRtwopageview').height();
2705 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2706 var intoViewY = percentageY * viewHeight;
2708 if (viewWidth < containerClientWidth) {
2709 // Can fit width without scrollbars - center by adjusting offset
2710 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2712 // Need to scroll to center
2713 $('#BRtwopageview').css('left', 0);
2714 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2717 if (viewHeight < containerClientHeight) {
2718 // Fits with scrollbars - add offset
2719 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2721 $('#BRtwopageview').css('top', 0);
2722 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2726 // twoPageFlipAreaHeight
2727 //______________________________________________________________________________
2728 // Returns the integer height of the click-to-flip areas at the edges of the book
2729 BookReader.prototype.twoPageFlipAreaHeight = function() {
2730 return parseInt(this.twoPage.height);
2733 // twoPageFlipAreaWidth
2734 //______________________________________________________________________________
2735 // Returns the integer width of the flip areas
2736 BookReader.prototype.twoPageFlipAreaWidth = function() {
2737 var max = 100; // $$$ TODO base on view width?
2740 var width = this.twoPage.width * 0.15;
2741 return parseInt(BookReader.util.clamp(width, min, max));
2744 // twoPageFlipAreaTop
2745 //______________________________________________________________________________
2746 // Returns integer top offset for flip areas
2747 BookReader.prototype.twoPageFlipAreaTop = function() {
2748 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2751 // twoPageLeftFlipAreaLeft
2752 //______________________________________________________________________________
2753 // Left offset for left flip area
2754 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2755 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2758 // twoPageRightFlipAreaLeft
2759 //______________________________________________________________________________
2760 // Left offset for right flip area
2761 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2762 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2765 // twoPagePlaceFlipAreas
2766 //______________________________________________________________________________
2767 // Readjusts position of flip areas based on current layout
2768 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2769 // We don't set top since it shouldn't change relative to view
2770 $(this.twoPage.leftFlipArea).css({
2771 left: this.twoPageLeftFlipAreaLeft() + 'px',
2772 width: this.twoPageFlipAreaWidth() + 'px'
2774 $(this.twoPage.rightFlipArea).css({
2775 left: this.twoPageRightFlipAreaLeft() + 'px',
2776 width: this.twoPageFlipAreaWidth() + 'px'
2780 // showSearchHilites2UP()
2781 //______________________________________________________________________________
2782 BookReader.prototype.updateSearchHilites2UP = function() {
2784 for (var key in this.searchResults) {
2785 key = parseInt(key, 10);
2786 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2787 var result = this.searchResults[key];
2788 if (null == result.div) {
2789 result.div = document.createElement('div');
2790 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2791 //console.log('appending ' + key);
2794 // We calculate the reduction factor for the specific page because it can be different
2795 // for each page in the spread
2796 var height = this._getPageHeight(key);
2797 var width = this._getPageWidth(key)
2798 var reduce = this.twoPage.height/height;
2799 var scaledW = parseInt(width*reduce);
2801 var gutter = this.twoPageGutter();
2803 if ('L' == this.getPageSide(key)) {
2804 pageL = gutter-scaledW;
2808 var pageT = this.twoPageTop();
2811 width: (result.r-result.l)*reduce + 'px',
2812 height: (result.b-result.t)*reduce + 'px',
2813 left: pageL+(result.l)*reduce + 'px',
2814 top: pageT+(result.t)*reduce +'px'
2818 //console.log(key + ' not displayed');
2819 if (null != this.searchResults[key].div) {
2820 //console.log('removing ' + key);
2821 $(this.searchResults[key].div).remove();
2823 this.searchResults[key].div=null;
2828 // removeSearchHilites()
2829 //______________________________________________________________________________
2830 BookReader.prototype.removeSearchHilites = function() {
2831 for (var key in this.searchResults) {
2832 if (null != this.searchResults[key].div) {
2833 $(this.searchResults[key].div).remove();
2834 this.searchResults[key].div=null;
2840 //______________________________________________________________________________
2841 BookReader.prototype.printPage = function() {
2842 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2844 /* iframe implementation
2846 if (null != this.printPopup) { // check if already showing
2849 this.printPopup = document.createElement("div");
2850 $(this.printPopup).css({
2851 position: 'absolute',
2853 left: ($('#BRcontainer').width()-400)/2 + 'px',
2856 border: "3px double #999999",
2858 backgroundColor: "#fff"
2859 }).appendTo('#BookReader');
2862 if (this.constMode1up == this.mode) {
2863 indexToPrint = this.firstIndex;
2865 indexToPrint = this.twoPage.currentIndexL;
2868 this.indexToPrint = indexToPrint;
2870 var htmlStr = '<div style="text-align: center;">';
2871 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>';
2872 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2873 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2874 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2875 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2876 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2878 htmlStr += '</div>';
2879 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2880 htmlStr += '</div>';
2882 this.printPopup.innerHTML = htmlStr;
2884 var iframe = document.createElement('iframe');
2885 iframe.id = 'printFrame';
2886 iframe.name = 'printFrame';
2887 iframe.width = '233px'; // 8.5 x 11 aspect
2888 iframe.height = '300px';
2890 var self = this; // closure
2892 $(iframe).load(function() {
2893 var doc = BookReader.util.getIFrameDocument(this);
2894 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2897 $('#printDiv').prepend(iframe);
2901 // Get print URI from current indices and mode
2902 BookReader.prototype.getPrintURI = function() {
2904 if (this.constMode2up == this.mode) {
2905 indexToPrint = this.twoPage.currentIndexL;
2907 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2910 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2911 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2912 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2914 if (this.constMode2up == this.mode) {
2915 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2916 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2917 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2919 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2922 return '/bookreader/print.php?' + options;
2925 /* iframe implementation
2926 BookReader.prototype.getPrintFrameContent = function(index) {
2927 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2928 // 8.5x11 so we should end up not overflowing on either paper size.
2929 var paperAspect = 8.5 / 11;
2930 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2934 // Rotate if possible and appropriate, to get larger image size on printed page
2935 if (this.canRotatePage(index)) {
2936 if (imageAspect > 1 && imageAspect > paperAspect) {
2937 // more wide than square, and more wide than paper
2939 imageAspect = 1/imageAspect;
2944 if (imageAspect > paperAspect) {
2945 // wider than paper, fit width
2946 fitAttrs = 'width="95%"';
2948 // taller than paper, fit height
2949 fitAttrs = 'height="95%"';
2952 var imageURL = this._getPageURI(index, 1, rotate);
2953 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2954 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2955 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2956 iframeStr += '</div>';
2957 iframeStr += '</body></html>';
2962 BookReader.prototype.updatePrintFrame = function(delta) {
2963 var newIndex = this.indexToPrint + delta;
2964 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2965 if (newIndex == this.indexToPrint) {
2968 this.indexToPrint = newIndex;
2969 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2970 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2975 //______________________________________________________________________________
2976 BookReader.prototype.showEmbedCode = function() {
2977 if (null != this.embedPopup) { // check if already showing
2981 this.embedPopup = document.createElement("div");
2982 $(this.embedPopup).css({
2983 position: 'absolute',
2985 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2988 border: "3px double #999999",
2990 backgroundColor: "#fff"
2991 }).appendTo('#BookReader');
2993 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2994 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>';
2995 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2996 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2998 this.embedPopup.innerHTML = htmlStr;
2999 $(this.embedPopup).find('input').bind('click', function() {
3005 //______________________________________________________________________________
3006 BookReader.prototype.autoToggle = function() {
3008 var bComingFrom1up = false;
3009 if (2 != this.mode) {
3010 bComingFrom1up = true;
3014 // Change to autofit if book is too large
3015 if (this.reduce < this.twoPageGetAutofitReduce()) {
3020 if (null == this.autoTimer) {
3021 this.flipSpeed = 2000;
3023 // $$$ Draw events currently cause layout problems when they occur during animation.
3024 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3025 // we workaround for now by not triggering immediate animation in that case.
3026 // See https://bugs.launchpad.net/gnubook/+bug/328327
3027 if (('rl' == this.pageProgression) && bComingFrom1up) {
3028 // don't flip immediately -- wait until timer fires
3031 this.flipFwdToIndex();
3034 $('#BRtoolbar .play').hide();
3035 $('#BRtoolbar .pause').show();
3036 this.autoTimer=setInterval(function(){
3037 if (self.animating) {return;}
3039 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3040 self.flipBackToIndex(1); // $$$ really what we want?
3042 self.flipFwdToIndex();
3051 //______________________________________________________________________________
3052 // Stop autoplay mode, allowing animations to finish
3053 BookReader.prototype.autoStop = function() {
3054 if (null != this.autoTimer) {
3055 clearInterval(this.autoTimer);
3056 this.flipSpeed = 'fast';
3057 $('#BRtoolbar .pause').hide();
3058 $('#BRtoolbar .play').show();
3059 this.autoTimer = null;
3063 // stopFlipAnimations
3064 //______________________________________________________________________________
3065 // Immediately stop flip animations. Callbacks are triggered.
3066 BookReader.prototype.stopFlipAnimations = function() {
3068 this.autoStop(); // Clear timers
3070 // Stop animation, clear queue, trigger callbacks
3071 if (this.leafEdgeTmp) {
3072 $(this.leafEdgeTmp).stop(false, true);
3074 jQuery.each(this.prefetchedImgs, function() {
3075 $(this).stop(false, true);
3078 // And again since animations also queued in callbacks
3079 if (this.leafEdgeTmp) {
3080 $(this.leafEdgeTmp).stop(false, true);
3082 jQuery.each(this.prefetchedImgs, function() {
3083 $(this).stop(false, true);
3088 // keyboardNavigationIsDisabled(event)
3089 // - returns true if keyboard navigation should be disabled for the event
3090 //______________________________________________________________________________
3091 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3092 if (event.target.tagName == "INPUT") {
3098 // gutterOffsetForIndex
3099 //______________________________________________________________________________
3101 // Returns the gutter offset for the spread containing the given index.
3102 // This function supports RTL
3103 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3105 // To find the offset of the gutter from the middle we calculate our percentage distance
3106 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3107 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3109 // But then again for RTL it's the opposite
3110 if ('rl' == this.pageProgression) {
3118 //______________________________________________________________________________
3119 // Returns the width of the leaf edge div for the page with index given
3120 BookReader.prototype.leafEdgeWidth = function(pindex) {
3121 // $$$ could there be single pixel rounding errors for L vs R?
3122 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3123 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3125 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3129 // jumpIndexForLeftEdgePageX
3130 //______________________________________________________________________________
3131 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3132 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3133 if ('rl' != this.pageProgression) {
3134 // LTR - flipping backward
3135 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3137 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3138 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3142 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3143 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3148 // jumpIndexForRightEdgePageX
3149 //______________________________________________________________________________
3150 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3151 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3152 if ('rl' != this.pageProgression) {
3154 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3155 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3158 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3159 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3164 BookReader.prototype.initToolbar = function(mode, ui) {
3166 $("#BookReader").append("<div id='BRtoolbar'>"
3167 + "<span id='BRtoolbarbuttons' style='float: right'>"
3168 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3169 + "<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>"
3170 + "<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>"
3171 + "<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>"
3172 + "<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>"
3173 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3177 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3178 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3179 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3180 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3181 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3182 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3183 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3186 + "<span id='#BRbooktitle'>"
3187 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3191 this.updateToolbarZoom(this.reduce); // Pretty format
3193 if (ui == "embed" || ui == "touch") {
3194 $("#BookReader a.logo").attr("target","_blank");
3197 // $$$ turn this into a member variable
3198 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3200 // We build in mode 2
3203 this.bindToolbarNavHandlers(jToolbar);
3205 // Setup tooltips -- later we could load these from a file for i18n
3206 var titles = { '.logo': 'Go to Archive.org',
3207 '.zoom_in': 'Zoom in',
3208 '.zoom_out': 'Zoom out',
3209 '.one_page_mode': 'One-page view',
3210 '.two_page_mode': 'Two-page view',
3211 '.thumbnail_mode': 'Thumbnail view',
3212 '.print': 'Print this page',
3213 '.embed': 'Embed bookreader',
3214 '.book_left': 'Flip left',
3215 '.book_right': 'Flip right',
3216 '.book_up': 'Page up',
3217 '.book_down': 'Page down',
3220 '.book_top': 'First page',
3221 '.book_bottom': 'Last page'
3223 if ('rl' == this.pageProgression) {
3224 titles['.book_leftmost'] = 'Last page';
3225 titles['.book_rightmost'] = 'First page';
3227 titles['.book_leftmost'] = 'First page';
3228 titles['.book_rightmost'] = 'Last page';
3231 for (var icon in titles) {
3232 jToolbar.find(icon).attr('title', titles[icon]);
3235 // Hide mode buttons and autoplay if 2up is not available
3236 // $$$ if we end up with more than two modes we should show the applicable buttons
3237 if ( !this.canSwitchToMode(this.constMode2up) ) {
3238 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3241 // Switch to requested mode -- binds other click handlers
3242 this.switchToolbarMode(mode);
3247 // switchToolbarMode
3248 //______________________________________________________________________________
3249 // Update the toolbar for the given mode (changes navigation buttons)
3250 // $$$ we should soon split the toolbar out into its own module
3251 BookReader.prototype.switchToolbarMode = function(mode) {
3254 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3255 $('#BRtoolbar .BRtoolbarmode2').hide();
3256 $('#BRtoolbar .BRtoolbarmode3').hide();
3257 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3258 } else if (2 == mode) {
3260 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3261 $('#BRtoolbar .BRtoolbarmode1').hide();
3262 $('#BRtoolbar .BRtoolbarmode3').hide();
3263 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3266 $('#BRtoolbar .BRtoolbarzoom').hide();
3267 $('#BRtoolbar .BRtoolbarmode2').hide();
3268 $('#BRtoolbar .BRtoolbarmode1').hide();
3269 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3273 // bindToolbarNavHandlers
3274 //______________________________________________________________________________
3275 // Binds the toolbar handlers
3276 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3278 var self = this; // closure
3280 jToolbar.find('.book_left').bind('click', function(e) {
3285 jToolbar.find('.book_right').bind('click', function(e) {
3290 jToolbar.find('.book_up').bind('click', function(e) {
3291 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3299 jToolbar.find('.book_down').bind('click', function(e) {
3300 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3308 jToolbar.find('.print').bind('click', function(e) {
3313 jToolbar.find('.embed').bind('click', function(e) {
3314 self.showEmbedCode();
3318 jToolbar.find('.play').bind('click', function(e) {
3323 jToolbar.find('.pause').bind('click', function(e) {
3328 jToolbar.find('.book_top').bind('click', function(e) {
3333 jToolbar.find('.book_bottom').bind('click', function(e) {
3338 jToolbar.find('.book_leftmost').bind('click', function(e) {
3343 jToolbar.find('.book_rightmost').bind('click', function(e) {
3349 // updateToolbarZoom(reduce)
3350 //______________________________________________________________________________
3351 // Update the displayed zoom factor based on reduction factor
3352 BookReader.prototype.updateToolbarZoom = function(reduce) {
3354 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3357 value = (100 / reduce).toFixed(2);
3358 // Strip trailing zeroes and decimal if all zeroes
3359 value = value.replace(/0+$/,'');
3360 value = value.replace(/\.$/,'');
3363 $('#BRzoom').text(value);
3366 // firstDisplayableIndex
3367 //______________________________________________________________________________
3368 // Returns the index of the first visible page, dependent on the mode.
3369 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3370 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3371 BookReader.prototype.firstDisplayableIndex = function() {
3372 if (this.mode != this.constMode2up) {
3376 if ('rl' != this.pageProgression) {
3378 if (this.getPageSide(0) == 'L') {
3385 if (this.getPageSide(0) == 'R') {
3393 // lastDisplayableIndex
3394 //______________________________________________________________________________
3395 // Returns the index of the last visible page, dependent on the mode.
3396 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3397 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3398 BookReader.prototype.lastDisplayableIndex = function() {
3400 var lastIndex = this.numLeafs - 1;
3402 if (this.mode != this.constMode2up) {
3406 if ('rl' != this.pageProgression) {
3408 if (this.getPageSide(lastIndex) == 'R') {
3411 return lastIndex + 1;
3415 if (this.getPageSide(lastIndex) == 'L') {
3418 return lastIndex + 1;
3423 // shortTitle(maximumCharacters)
3425 // Returns a shortened version of the title with the maximum number of characters
3426 BookReader.prototype.shortTitle = function(maximumCharacters) {
3427 if (this.bookTitle.length < maximumCharacters) {
3428 return this.bookTitle;
3431 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3436 // Parameter related functions
3438 // updateFromParams(params)
3440 // Update ourselves from the params object.
3442 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3443 BookReader.prototype.updateFromParams = function(params) {
3444 if ('undefined' != typeof(params.mode)) {
3445 this.switchMode(params.mode);
3449 if ('undefined' != typeof(params.searchTerm)) {
3450 if (this.searchTerm != params.searchTerm) {
3451 this.search(params.searchTerm);
3455 // $$$ process /zoom
3457 // We only respect page if index is not set
3458 if ('undefined' != typeof(params.index)) {
3459 if (params.index != this.currentIndex()) {
3460 this.jumpToIndex(params.index);
3462 } else if ('undefined' != typeof(params.page)) {
3463 // $$$ this assumes page numbers are unique
3464 if (params.page != this.getPageNum(this.currentIndex())) {
3465 this.jumpToPage(params.page);
3469 // $$$ process /region
3470 // $$$ process /highlight
3473 // paramsFromFragment(urlFragment)
3475 // Returns a object with configuration parametes from a URL fragment.
3477 // E.g paramsFromFragment(window.location.hash)
3478 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3479 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3483 // For convenience we allow an initial # character (as from window.location.hash)
3484 // but don't require it
3485 if (urlFragment.substr(0,1) == '#') {
3486 urlFragment = urlFragment.substr(1);
3489 // Simple #nn syntax
3490 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3491 if ( !isNaN(oldStyleLeafNum) ) {
3492 params.index = oldStyleLeafNum;
3494 // Done processing if using old-style syntax
3498 // Split into key-value pairs
3499 var urlArray = urlFragment.split('/');
3501 for (var i = 0; i < urlArray.length; i += 2) {
3502 urlHash[urlArray[i]] = urlArray[i+1];
3506 if ('1up' == urlHash['mode']) {
3507 params.mode = this.constMode1up;
3508 } else if ('2up' == urlHash['mode']) {
3509 params.mode = this.constMode2up;
3510 } else if ('thumb' == urlHash['mode']) {
3511 params.mode = this.constModeThumb;
3515 if ('undefined' != typeof(urlHash['page'])) {
3516 // page was set -- may not be int
3517 params.page = urlHash['page'];
3520 // $$$ process /region
3521 // $$$ process /search
3523 if (urlHash['search'] != undefined) {
3524 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3527 // $$$ process /highlight
3532 // paramsFromCurrent()
3534 // Create a params object from the current parameters.
3535 BookReader.prototype.paramsFromCurrent = function() {
3539 var index = this.currentIndex();
3540 var pageNum = this.getPageNum(index);
3541 if ((pageNum === 0) || pageNum) {
3542 params.page = pageNum;
3545 params.index = index;
3546 params.mode = this.mode;
3552 if (this.searchHighlightVisible()) {
3553 params.searchTerm = this.searchTerm;
3559 // fragmentFromParams(params)
3561 // Create a fragment string from the params object.
3562 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3563 BookReader.prototype.fragmentFromParams = function(params) {
3564 var separator = '/';
3568 if ('undefined' != typeof(params.page)) {
3569 fragments.push('page', params.page);
3571 // Don't have page numbering -- use index instead
3572 fragments.push('page', 'n' + params.index);
3579 if ('undefined' != typeof(params.mode)) {
3580 if (params.mode == this.constMode1up) {
3581 fragments.push('mode', '1up');
3582 } else if (params.mode == this.constMode2up) {
3583 fragments.push('mode', '2up');
3584 } else if (params.mode == this.constModeThumb) {
3585 fragments.push('mode', 'thumb');
3587 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3592 if (params.searchTerm) {
3593 fragments.push('search', params.searchTerm);
3596 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3599 // getPageIndex(pageNum)
3601 // Returns the *highest* index the given page number, or undefined
3602 BookReader.prototype.getPageIndex = function(pageNum) {
3603 var pageIndices = this.getPageIndices(pageNum);
3605 if (pageIndices.length > 0) {
3606 return pageIndices[pageIndices.length - 1];
3612 // getPageIndices(pageNum)
3614 // Returns an array (possibly empty) of the indices with the given page number
3615 BookReader.prototype.getPageIndices = function(pageNum) {
3618 // Check for special "nXX" page number
3619 if (pageNum.slice(0,1) == 'n') {
3621 var pageIntStr = pageNum.slice(1, pageNum.length);
3622 var pageIndex = parseInt(pageIntStr);
3623 indices.push(pageIndex);
3626 // Do nothing... will run through page names and see if one matches
3631 for (i=0; i<this.numLeafs; i++) {
3632 if (this.getPageNum(i) == pageNum) {
3640 // getPageName(index)
3642 // Returns the name of the page as it should be displayed in the user interface
3643 BookReader.prototype.getPageName = function(index) {
3644 return 'Page ' + this.getPageNum(index);
3647 // updateLocationHash
3649 // Update the location hash from the current parameters. Call this instead of manually
3650 // using window.location.replace
3651 BookReader.prototype.updateLocationHash = function() {
3652 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3653 window.location.replace(newHash);
3655 // This is the variable checked in the timer. Only user-generated changes
3656 // to the URL will trigger the event.
3657 this.oldLocationHash = newHash;
3660 // startLocationPolling
3662 // Starts polling of window.location to see hash fragment changes
3663 BookReader.prototype.startLocationPolling = function() {
3664 var self = this; // remember who I am
3665 self.oldLocationHash = window.location.hash;
3667 if (this.locationPollId) {
3668 clearInterval(this.locationPollID);
3669 this.locationPollId = null;
3672 this.locationPollId = setInterval(function() {
3673 var newHash = window.location.hash;
3674 if (newHash != self.oldLocationHash) {
3675 if (newHash != self.oldUserHash) { // Only process new user hash once
3676 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3678 // Queue change if animating
3679 if (self.animating) {
3681 self.animationFinishedCallback = function() {
3682 self.updateFromParams(self.paramsFromFragment(newHash));
3684 } else { // update immediately
3685 self.updateFromParams(self.paramsFromFragment(newHash));
3687 self.oldUserHash = newHash;
3695 // Returns true if we can switch to the requested mode
3696 BookReader.prototype.canSwitchToMode = function(mode) {
3697 if (mode == this.constMode2up) {
3698 // check there are enough pages to display
3699 // $$$ this is a workaround for the mis-feature that we can't display
3700 // short books in 2up mode
3701 if (this.numLeafs < 6) {
3709 // searchHighlightVisible
3711 // Returns true if a search highlight is currently being displayed
3712 BookReader.prototype.searchHighlightVisible = function() {
3713 if (this.constMode2up == this.mode) {
3714 if (this.searchResults[this.twoPage.currentIndexL]
3715 || this.searchResults[this.twoPage.currentIndexR]) {
3719 if (this.searchResults[this.currentIndex()]) {
3726 // getPageBackgroundColor
3728 // Returns a CSS property string for the background color for the given page
3729 // $$$ turn into regular CSS?
3730 BookReader.prototype.getPageBackgroundColor = function(index) {
3731 if (index >= 0 && index < this.numLeafs) {
3733 return this.pageDefaultBackgroundColor;
3741 // Returns the page width for the given index, or first or last page if out of range
3742 BookReader.prototype._getPageWidth = function(index) {
3743 // Synthesize a page width for pages not actually present in book.
3744 // May or may not be the best approach.
3745 // If index is out of range we return the width of first or last page
3746 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3747 return this.getPageWidth(index);
3752 // Returns the page height for the given index, or first or last page if out of range
3753 BookReader.prototype._getPageHeight= function(index) {
3754 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3755 return this.getPageHeight(index);
3760 // Returns the page URI or transparent image if out of range
3761 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3762 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3763 return this.imagesBaseURL + "/transparent.png";
3766 if ('undefined' == typeof(reduce)) {
3767 // reduce not passed in
3768 // $$$ this probably won't work for thumbnail mode
3769 var ratio = this.getPageHeight(index) / this.twoPage.height;
3771 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3774 } else if (ratio < 4) {
3776 } else if (ratio < 8) {
3778 } else if (ratio < 16) {
3780 } else if (ratio < 32) {
3788 return this.getPageURI(index, reduce, rotate);
3791 // Library functions
3793 disableSelect: function(jObject) {
3794 // Bind mouse handlers
3795 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3796 jObject.bind('mousedown', function(e) {
3797 // $$$ check here for right-click and don't disable. Also use jQuery style
3798 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3801 // Special hack for IE7
3802 jObject[0].onselectstart = function(e) { return false; };
3805 clamp: function(value, min, max) {
3806 return Math.min(Math.max(value, min), max);
3809 notInArray: function(value, array) {
3810 // inArray returns -1 or undefined if value not in array
3811 return ! (jQuery.inArray(value, array) >= 0);
3814 getIFrameDocument: function(iframe) {
3815 // Adapted from http://xkr.us/articles/dom/iframe-document/
3816 var outer = (iframe.contentWindow || iframe.contentDocument);
3817 return (outer.document || outer);
3820 decodeURIComponentPlus: function(value) {
3821 // Decodes a URI component and converts '+' to ' '
3822 return decodeURIComponent(value).replace(/\+/g, ' ');
3825 encodeURIComponentPlus: function(value) {
3826 // Encodes a URI component and converts ' ' to '+'
3827 return encodeURIComponent(value).replace(/%20/g, '+');
3829 // The final property here must NOT have a comma after it - IE7