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 // Should be overriden (before init) by custom implmentations.
76 this.logoURL = 'http://www.archive.org/index.php';
78 // Base URL for UI images - should be overriden (before init) by
79 // custom implementations.
80 // $$$ This is the same directory as the images referenced by relative
81 // path in the CSS. Would be better to automagically find that path.
82 this.imagesBaseURL = '/bookreader/images/';
85 this.constMode1up = 1;
86 this.constMode2up = 2;
87 this.constModeThumb = 3;
90 // $$$ provide finer grained zooming
91 this.reductionFactors = [ {reduce: 0.5, autofit: null},
92 {reduce: 1, autofit: null},
93 {reduce: 2, autofit: null},
94 {reduce: 4, autofit: null},
95 {reduce: 8, autofit: null},
96 {reduce: 16, autofit: null} ];
98 // Object to hold parameters related to 1up mode
100 autofit: 'height' // valid values are height, width, none
103 // Object to hold parameters related to 2up mode
105 coverInternalPadding: 0, // Width of cover
106 coverExternalPadding: 0, // Padding outside of cover
107 bookSpineDivWidth: 0, // Width of book spine $$$ consider sizing based on book length
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 // Sanitize/process parameters
126 if ( !this.canSwitchToMode( this.mode ) ) {
127 this.mode = this.constMode1up;
130 if ('undefined' != typeof(params.index)) {
131 startIndex = params.index;
132 } else if ('undefined' != typeof(params.page)) {
133 startIndex = this.getPageIndex(params.page);
136 if ('undefined' == typeof(startIndex)) {
137 if ('undefined' != typeof(this.titleLeaf)) {
138 // title leaf is known - but only use as default if book has a few pages
139 if (this.numLeafs > 2) {
140 startIndex = this.leafNumToIndex(this.titleLeaf);
145 if ('undefined' == typeof(startIndex)) {
149 if ('undefined' != typeof(params.mode)) {
150 this.mode = params.mode;
153 // Set document title -- may have already been set in enclosing html for
154 // search engine visibility
155 document.title = this.shortTitle(50);
157 $("#BookReader").empty();
159 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
160 $("#BookReader").append("<div id='BRcontainer'></div>");
161 $("#BRcontainer").append("<div id='BRpageview'></div>");
163 $("#BRcontainer").bind('scroll', this, function(e) {
167 this.setupKeyListeners();
168 this.startLocationPolling();
170 $(window).bind('resize', this, function(e) {
171 //console.log('resize!');
172 if (1 == e.data.mode) {
173 //console.log('centering 1page view');
174 if (e.data.autofit) {
175 e.data.resizePageView();
177 e.data.centerPageView();
178 $('#BRpageview').empty()
179 e.data.displayedIndices = [];
180 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
182 } else if (3 == e.data.mode){
183 e.data.prepareThumbnailView();
185 //console.log('drawing 2 page view');
187 // We only need to prepare again in autofit (size of spread changes)
188 if (e.data.twoPage.autofit) {
189 e.data.prepareTwoPageView();
191 // Re-center if the scrollbars have disappeared
192 var center = e.data.twoPageGetViewCenter();
193 var doRecenter = false;
194 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
195 center.percentageX = 0.5;
198 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
199 center.percentageY = 0.5;
203 e.data.twoPageCenterView(center.percentageX, center.percentageY);
209 $('.BRpagediv1up').bind('mousedown', this, function(e) {
210 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
211 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
215 // $$$ refactor this so it's enough to set the first index and call preparePageView
216 // (get rid of mode-specific logic at this point)
217 if (1 == this.mode) {
218 this.firstIndex = startIndex;
219 this.prepareOnePageView();
220 this.jumpToIndex(startIndex);
221 } else if (3 == this.mode) {
222 this.firstIndex = startIndex;
223 this.prepareThumbnailView();
224 this.jumpToIndex(startIndex);
226 //this.resizePageView();
228 this.displayedIndices=[0];
229 this.firstIndex = startIndex;
230 this.displayedIndices = [this.firstIndex];
231 //console.log('titleLeaf: %d', this.titleLeaf);
232 //console.log('displayedIndices: %s', this.displayedIndices);
233 this.prepareTwoPageView();
236 // Enact other parts of initial params
237 this.updateFromParams(params);
240 BookReader.prototype.setupKeyListeners = function() {
253 // We use document here instead of window to avoid a bug in jQuery on IE7
254 $(document).keydown(function(e) {
256 // Keyboard navigation
257 if (!self.keyboardNavigationIsDisabled(e)) {
261 // In 1up mode page scrolling is handled by browser
262 if (2 == self.mode) {
269 if (2 == self.mode) {
283 if (2 == self.mode) {
289 if (2 == self.mode) {
300 //______________________________________________________________________________
301 BookReader.prototype.drawLeafs = function() {
302 if (1 == this.mode) {
303 this.drawLeafsOnePage();
304 } else if (3 == this.mode) {
305 this.drawLeafsThumbnail();
307 this.drawLeafsTwoPage();
312 // bindGestures(jElement)
313 //______________________________________________________________________________
314 BookReader.prototype.bindGestures = function(jElement) {
316 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
318 if (e.originalEvent.scale > 1.5) {
320 } else if (e.originalEvent.scale < 0.6) {
327 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
328 //console.log('setting handler');
329 //console.log(element.tagName);
331 $(element).unbind('tap').bind('tap', data, function(e) {
336 // drawLeafsOnePage()
337 //______________________________________________________________________________
338 BookReader.prototype.drawLeafsOnePage = function() {
339 //alert('drawing leafs!');
343 var scrollTop = $('#BRcontainer').attr('scrollTop');
344 var scrollBottom = scrollTop + $('#BRcontainer').height();
345 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
347 var indicesToDisplay = [];
352 for (i=0; i<this.numLeafs; i++) {
353 var height = parseInt(this._getPageHeight(i)/this.reduce);
355 leafBottom += height;
356 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
357 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
358 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
359 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
360 if (topInView | bottomInView | middleInView) {
361 //console.log('displayed: ' + this.displayedIndices);
362 //console.log('to display: ' + i);
363 indicesToDisplay.push(i);
365 leafTop += height +10;
369 var firstIndexToDraw = indicesToDisplay[0];
370 this.firstIndex = firstIndexToDraw;
372 // Update hash, but only if we're currently displaying a leaf
373 // Hack that fixes #365790
374 if (this.displayedIndices.length > 0) {
375 this.updateLocationHash();
378 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
380 indicesToDisplay.unshift(firstIndexToDraw);
383 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
384 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
385 indicesToDisplay.push(lastIndexToDraw+1);
390 for (i=0; i<firstIndexToDraw; i++) {
391 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
394 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
395 var viewWidth = $('#BRcontainer').attr('scrollWidth');
398 for (i=0; i<indicesToDisplay.length; i++) {
399 var index = indicesToDisplay[i];
400 var height = parseInt(this._getPageHeight(index)/this.reduce);
402 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
403 var width = parseInt(this._getPageWidth(index)/this.reduce);
404 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
405 var div = document.createElement("div");
406 div.className = 'BRpagediv1up';
407 div.id = 'pagediv'+index;
408 div.style.position = "absolute";
409 $(div).css('top', leafTop + 'px');
410 var left = (viewWidth-width)>>1;
411 if (left<0) left = 0;
412 $(div).css('left', left+'px');
413 $(div).css('width', width+'px');
414 $(div).css('height', height+'px');
415 //$(div).text('loading...');
417 $('#BRpageview').append(div);
419 var img = document.createElement("img");
420 img.src = this._getPageURI(index, this.reduce, 0);
421 $(img).css('width', width+'px');
422 $(img).css('height', height+'px');
426 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
429 leafTop += height +10;
433 for (i=0; i<this.displayedIndices.length; i++) {
434 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
435 var index = this.displayedIndices[i];
436 //console.log('Removing leaf ' + index);
437 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
438 $('#pagediv'+index).remove();
440 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
444 this.displayedIndices = indicesToDisplay.slice();
445 this.updateSearchHilites();
447 if (null != this.getPageNum(firstIndexToDraw)) {
448 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
450 $("#BRpagenum").val('');
453 this.updateToolbarZoom(this.reduce);
457 // drawLeafsThumbnail()
458 //______________________________________________________________________________
459 // If seekIndex is defined, the view will be drawn with that page visible (without any
460 // animated scrolling)
461 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
462 //alert('drawing leafs!');
465 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
467 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
481 // Will be set to top of requested seek index, if set
484 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
485 for (i=0; i<this.numLeafs; i++) {
486 leafWidth = this.thumbWidth;
487 if (rightPos + (leafWidth + this.padding) > viewWidth){
493 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
494 if (leafMap[currentRow].leafs===undefined) {
495 leafMap[currentRow].leafs = [];
496 leafMap[currentRow].height = 0;
497 leafMap[currentRow].top = 0;
499 leafMap[currentRow].leafs[leafIndex] = {};
500 leafMap[currentRow].leafs[leafIndex].num = i;
501 leafMap[currentRow].leafs[leafIndex].left = rightPos;
503 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
504 if (leafHeight > leafMap[currentRow].height) {
505 leafMap[currentRow].height = leafHeight;
507 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
508 rightPos += leafWidth + this.padding;
509 if (rightPos > maxRight) { maxRight = rightPos; }
512 if (i == seekIndex) {
513 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
517 // reset the bottom position based on thumbnails
518 $('#BRpageview').height(bottomPos);
520 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
522 // If seekTop is defined, seeking was requested and target found
523 if (typeof(seekTop) != 'undefined') {
524 $('#BRcontainer').scrollTop( seekTop );
527 var scrollTop = $('#BRcontainer').attr('scrollTop');
528 var scrollBottom = scrollTop + $('#BRcontainer').height();
532 var rowsToDisplay = [];
534 // Visible leafs with least/greatest index
535 var leastVisible = this.numLeafs - 1;
538 // Determine the thumbnails in view
539 for (i=0; i<leafMap.length; i++) {
540 leafBottom += this.padding + leafMap[i].height;
541 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
542 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
543 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
544 if (topInView | bottomInView | middleInView) {
545 //console.log('row to display: ' + j);
546 rowsToDisplay.push(i);
547 if (leafMap[i].leafs[0].num < leastVisible) {
548 leastVisible = leafMap[i].leafs[0].num;
550 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
551 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
554 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
555 leafTop = leafBottom;
558 // create a buffer of preloaded rows before and after the visible rows
559 var firstRow = rowsToDisplay[0];
560 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
561 for (i=1; i<this.thumbRowBuffer+1; i++) {
562 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
564 for (i=1; i<this.thumbRowBuffer+1; i++) {
565 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
568 // Create the thumbnail divs and images (lazy loaded)
577 for (i=0; i<rowsToDisplay.length; i++) {
578 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
579 row = rowsToDisplay[i];
581 for (j=0; j<leafMap[row].leafs.length; j++) {
583 leaf = leafMap[row].leafs[j].num;
585 leafWidth = this.thumbWidth;
586 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
587 leafTop = leafMap[row].top;
588 left = leafMap[row].leafs[index].left + pageViewBuffer;
589 if ('rl' == this.pageProgression){
590 left = viewWidth - leafWidth - left;
593 div = document.createElement("div");
594 div.id = 'pagediv'+leaf;
595 div.style.position = "absolute";
596 div.className = "BRpagedivthumb";
598 left += this.padding;
599 $(div).css('top', leafTop + 'px');
600 $(div).css('left', left+'px');
601 $(div).css('width', leafWidth+'px');
602 $(div).css('height', leafHeight+'px');
603 //$(div).text('loading...');
605 // link to page in single page mode
606 link = document.createElement("a");
607 $(link).data('leaf', leaf);
608 $(link).bind('tap', function(event) {
609 self.firstIndex = $(this).data('leaf');
610 self.switchMode(self.constMode1up);
611 event.preventDefault();
614 // $$$ we don't actually go to this URL (click is handled in handler above)
615 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
618 $('#BRpageview').append(div);
620 img = document.createElement("img");
621 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
623 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
624 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
625 .addClass('BRlazyload')
626 // Store the URL of the image that will replace this one
627 .data('srcURL', this._getPageURI(leaf, thumbReduce));
629 //console.log('displaying thumbnail: ' + leaf);
634 // Remove thumbnails that are not to be displayed
636 for (i=0; i<this.displayedRows.length; i++) {
637 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
638 row = this.displayedRows[i];
640 // $$$ Safari doesn't like the comprehension
641 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
642 //console.log('Removing row ' + row + ' ' + rowLeafs);
644 for (k=0; k<leafMap[row].leafs.length; k++) {
645 index = leafMap[row].leafs[k].num;
646 //console.log('Removing leaf ' + index);
647 $('#pagediv'+index).remove();
651 var mRow = this.displayedRows[i];
652 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
653 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
658 // Update which page is considered current to make sure a visible page is the current one
659 var currentIndex = this.currentIndex();
660 // console.log('current ' + currentIndex);
661 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
662 if (currentIndex < leastVisible) {
663 this.setCurrentIndex(leastVisible);
664 } else if (currentIndex > mostVisible) {
665 this.setCurrentIndex(mostVisible);
668 this.displayedRows = rowsToDisplay.slice();
670 // Update hash, but only if we're currently displaying a leaf
671 // Hack that fixes #365790
672 if (this.displayedRows.length > 0) {
673 this.updateLocationHash();
676 // remove previous highlights
677 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
679 // highlight current page
680 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
682 this.lazyLoadThumbnails();
684 // Update page number box. $$$ refactor to function
685 if (null !== this.getPageNum(this.currentIndex())) {
686 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
688 $("#BRpagenum").val('');
691 this.updateToolbarZoom(this.reduce);
694 BookReader.prototype.lazyLoadThumbnails = function() {
696 // console.log('lazy load');
698 // We check the complete property since load may not be fired if loading from the cache
699 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
701 var loading = $('.BRlazyloading').length;
702 var toLoad = this.thumbMaxLoading - loading;
704 // console.log(' ' + loading + ' thumbnails loading');
705 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
710 // $$$ TODO load those near top (but not beyond) page view first
711 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
712 self.lazyLoadImage(this);
717 BookReader.prototype.lazyLoadImage = function (dummyImage) {
718 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
720 var img = new Image();
724 .addClass('BRlazyloading')
725 .one('load', function() {
726 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
728 $(this).removeClass('BRlazyloading');
730 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
731 // we call the function after a slight delay. Also the img.complete property
732 // is not yet set in IE8 inside this onload handler
733 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
735 .one('error', function() {
736 // Remove class so we no longer count as loading
737 $(this).removeClass('BRlazyloading');
739 .attr( { width: $(dummyImage).width(),
740 height: $(dummyImage).height(),
741 src: $(dummyImage).data('srcURL')
744 // replace with the new img
745 $(dummyImage).before(img).remove();
747 img = null; // tidy up closure
751 // drawLeafsTwoPage()
752 //______________________________________________________________________________
753 BookReader.prototype.drawLeafsTwoPage = function() {
754 var scrollTop = $('#BRtwopageview').attr('scrollTop');
755 var scrollBottom = scrollTop + $('#BRtwopageview').height();
757 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
759 var indexL = this.twoPage.currentIndexL;
761 var heightL = this._getPageHeight(indexL);
762 var widthL = this._getPageWidth(indexL);
764 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
765 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
766 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
767 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
768 //console.log(leafEdgeWidthL);
770 var middle = this.twoPage.middle; // $$$ getter instead?
771 var top = this.twoPageTop();
772 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
774 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
775 this.twoPage.gutter = this.twoPageGutter();
777 this.prefetchImg(indexL);
778 $(this.prefetchedImgs[indexL]).css({
779 position: 'absolute',
780 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
783 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
784 width: this.twoPage.scaledWL + 'px',
786 }).appendTo('#BRtwopageview');
788 var indexR = this.twoPage.currentIndexR;
789 var heightR = this._getPageHeight(indexR);
790 var widthR = this._getPageWidth(indexR);
792 // $$$ should use getwidth2up?
793 //var scaledWR = this.twoPage.height*widthR/heightR;
794 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
795 this.prefetchImg(indexR);
796 $(this.prefetchedImgs[indexR]).css({
797 position: 'absolute',
798 left: this.twoPage.gutter+'px',
801 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
802 width: this.twoPage.scaledWR + 'px',
804 }).appendTo('#BRtwopageview');
807 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
808 this.setMouseHandlers2UP();
809 this.twoPageSetCursor();
811 this.updatePageNumBox2UP();
812 this.updateToolbarZoom(this.reduce);
814 // this.twoPagePlaceFlipAreas(); // No longer used
818 // updatePageNumBox2UP
819 //______________________________________________________________________________
820 BookReader.prototype.updatePageNumBox2UP = function() {
821 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
822 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
824 $("#BRpagenum").val('');
826 this.updateLocationHash();
830 //______________________________________________________________________________
831 BookReader.prototype.loadLeafs = function() {
835 if (null == this.timer) {
836 this.timer=setTimeout(function(){self.drawLeafs()},250);
838 clearTimeout(this.timer);
839 this.timer=setTimeout(function(){self.drawLeafs()},250);
845 // Pass 1 to zoom in, anything else to zoom out
846 //______________________________________________________________________________
847 BookReader.prototype.zoom = function(direction) {
849 case this.constMode1up:
850 if (direction == 1) {
852 return this.zoom1up('in');
854 return this.zoom1up('out');
857 case this.constMode2up:
858 if (direction == 1) {
860 return this.zoom2up('in');
862 return this.zoom2up('out');
865 case this.constModeThumb:
866 // XXX update zoomThumb for named directions
867 return this.zoomThumb(direction);
873 //______________________________________________________________________________
874 BookReader.prototype.zoom1up = function(direction) {
876 if (2 == this.mode) { //can only zoom in 1-page mode
881 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
883 if (this.reduce == reduceFactor.reduce) {
884 // Already at this level
888 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
889 this.onePage.autofit = reduceFactor.autofit;
891 this.pageScale = this.reduce; // preserve current reduce
892 this.resizePageView();
894 $('#BRpageview').empty()
895 this.displayedIndices = [];
898 this.updateToolbarZoom(this.reduce);
900 // Recalculate search hilites
901 this.removeSearchHilites();
902 this.updateSearchHilites();
907 //______________________________________________________________________________
908 BookReader.prototype.resizePageView = function() {
910 // $$$ This code assumes 1up mode
911 // e.g. does not preserve position in thumbnail mode
912 // See http://bugs.launchpad.net/bookreader/+bug/552972
915 case this.constMode1up:
916 case this.constMode2up:
917 this.resizePageView1up();
919 case this.constModeThumb:
920 this.prepareThumbnailView( this.currentIndex() );
923 alert('Resize not implemented for this mode');
927 BookReader.prototype.resizePageView1up = function() {
930 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
931 var viewWidth = $('#BRcontainer').attr('clientWidth');
933 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
934 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
935 var oldPageViewHeight = $('#BRpageview').height();
936 var oldPageViewWidth = $('#BRpageview').width();
938 var oldCenterY = this.centerY1up();
939 var oldCenterX = this.centerX1up();
941 if (0 != oldPageViewHeight) {
942 var scrollRatio = oldCenterY / oldPageViewHeight;
947 // Recalculate 1up reduction factors
948 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
949 $('#BRcontainer').attr('clientHeight') );
950 // Update current reduce (if in autofit)
951 if (this.onePage.autofit) {
952 var reductionFactor = this.nextReduce(this.reduce, this.onePage.autofit, this.onePage.reductionFactors);
953 this.reduce = reductionFactor.reduce;
956 for (i=0; i<this.numLeafs; i++) {
957 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
958 var width = parseInt(this._getPageWidth(i)/this.reduce);
959 if (width>viewWidth) viewWidth=width;
961 $('#BRpageview').height(viewHeight);
962 $('#BRpageview').width(viewWidth);
964 var newCenterY = scrollRatio*viewHeight;
965 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
966 $('#BRcontainer').attr('scrollTop', newTop);
968 // We use clientWidth here to avoid miscalculating due to scroll bar
969 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
970 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
971 newLeft = Math.max(newLeft, 0);
972 $('#BRcontainer').attr('scrollLeft', newLeft);
973 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
975 //this.centerPageView();
978 this.removeSearchHilites();
979 this.updateSearchHilites();
984 //______________________________________________________________________________
985 // Returns the current offset of the viewport center in scaled document coordinates.
986 BookReader.prototype.centerX1up = function() {
988 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
989 centerX = $('#BRpageview').width();
991 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
993 centerX = Math.floor(centerX);
998 //______________________________________________________________________________
999 // Returns the current offset of the viewport center in scaled document coordinates.
1000 BookReader.prototype.centerY1up = function() {
1001 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1002 return Math.floor(centerY);
1006 //______________________________________________________________________________
1007 BookReader.prototype.centerPageView = function() {
1009 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1010 var clientWidth = $('#BRcontainer').attr('clientWidth');
1011 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1012 if (scrollWidth > clientWidth) {
1013 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1018 // zoom2up(direction)
1019 //______________________________________________________________________________
1020 BookReader.prototype.zoom2up = function(direction) {
1022 // Hard stop autoplay
1023 this.stopFlipAnimations();
1025 // Recalculate autofit factors
1026 this.twoPageCalculateReductionFactors();
1028 // Get new zoom state
1029 var reductionFactor = this.nextReduce(this.reduce, direction, this.twoPage.reductionFactors);
1030 if ((this.reduce == reductionFactor.reduce) && (this.twoPage.autofit == reductionFactor.autofit)) {
1034 this.twoPage.autofit = reductionFactor.autofit;
1035 this.reduce = reductionFactor.reduce;
1036 this.pageScale = this.reduce; // preserve current reduce
1038 // Preserve view center position
1039 var oldCenter = this.twoPageGetViewCenter();
1041 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1042 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1043 if (1 == direction) {
1044 for (var img in this.prefetchedImgs) {
1045 delete this.prefetchedImgs[img];
1049 // Prepare view with new center to minimize visual glitches
1050 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1053 BookReader.prototype.zoomThumb = function(direction) {
1054 var oldColumns = this.thumbColumns;
1055 switch (direction) {
1057 this.thumbColumns += 1;
1060 this.thumbColumns -= 1;
1065 if (this.thumbColumns < 2) {
1066 this.thumbColumns = 2;
1067 } else if (this.thumbColumns > 8) {
1068 this.thumbColumns = 8;
1071 if (this.thumbColumns != oldColumns) {
1072 this.prepareThumbnailView();
1076 // Returns the width per thumbnail to display the requested number of columns
1077 // Note: #BRpageview must already exist since its width is used to calculate the
1079 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1080 var padding = (thumbnailColumns + 1) * this.padding;
1081 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1082 return parseInt(width);
1085 // quantizeReduce(reduce)
1086 //______________________________________________________________________________
1087 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1088 BookReader.prototype.quantizeReduce = function(reduce, reductionFactors) {
1089 var quantized = reductionFactors[0].reduce;
1090 var distance = Math.abs(reduce - quantized);
1091 for (var i = 1; i < reductionFactors.length; i++) {
1092 newDistance = Math.abs(reduce - reductionFactors[i].reduce);
1093 if (newDistance < distance) {
1094 distance = newDistance;
1095 quantized = reductionFactors[i].reduce;
1102 // reductionFactors should be array of sorted reduction factors
1103 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1104 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1106 // XXX add 'closest', to replace quantize function
1108 if (direction == 'in') {
1109 var newReduceIndex = 0;
1111 for (var i = 1; i < reductionFactors.length; i++) {
1112 if (reductionFactors[i].reduce < currentReduce) {
1116 return reductionFactors[newReduceIndex];
1118 } else if (direction == 'out') { // zoom out
1119 var lastIndex = reductionFactors.length - 1;
1120 var newReduceIndex = lastIndex;
1122 for (var i = lastIndex; i >= 0; i--) {
1123 if (reductionFactors[i].reduce > currentReduce) {
1127 return reductionFactors[newReduceIndex];
1130 // Asked for specific autofit mode
1131 for (var i = 0; i < reductionFactors.length; i++) {
1132 if (reductionFactors[i].autofit == direction) {
1133 return reductionFactors[i];
1137 alert('Could not find reduction factor for direction ' + direction);
1138 return reductionFactors[0];
1142 BookReader.prototype._reduceSort = function(a, b) {
1143 return a.reduce - b.reduce;
1147 //______________________________________________________________________________
1148 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1149 BookReader.prototype.jumpToPage = function(pageNum) {
1151 var pageIndex = this.getPageIndex(pageNum);
1153 if ('undefined' != typeof(pageIndex)) {
1156 this.jumpToIndex(pageIndex);
1157 $('#BRcontainer').attr('scrollTop', leafTop);
1166 //______________________________________________________________________________
1167 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1169 if (this.constMode2up == this.mode) {
1172 // By checking against min/max we do nothing if requested index
1174 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1175 this.flipBackToIndex(index);
1176 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1177 this.flipFwdToIndex(index);
1180 } else if (this.constModeThumb == this.mode) {
1181 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1191 for (i=0; i<(index+1); i++) {
1192 leafWidth = this.thumbWidth;
1193 if (rightPos + (leafWidth + this.padding) > viewWidth){
1199 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1200 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1201 if (leafIndex==0) { leafTop = bottomPos; }
1202 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1203 rightPos += leafWidth + this.padding;
1206 this.firstIndex=index;
1207 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1210 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1218 for (i=0; i<index; i++) {
1219 h = parseInt(this._getPageHeight(i)/this.reduce);
1220 leafTop += h + this.padding;
1224 //console.log('pageY ' + pageY);
1225 var offset = parseInt( (pageY) / this.reduce);
1226 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1227 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1230 // Show page just a little below the top
1231 leafTop -= this.padding / 2;
1235 var offset = parseInt( (pageX) / this.reduce);
1236 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1239 // Preserve left position
1240 leafLeft = $('#BRcontainer').scrollLeft();
1243 //$('#BRcontainer').attr('scrollTop', leafTop);
1244 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1250 //______________________________________________________________________________
1251 BookReader.prototype.switchMode = function(mode) {
1253 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1255 if (mode == this.mode) {
1259 if (!this.canSwitchToMode(mode)) {
1264 this.removeSearchHilites();
1267 //this.switchToolbarMode(mode);
1269 // reinstate scale if moving from thumbnail view
1270 if (this.pageScale != this.reduce) {
1271 this.reduce = this.pageScale;
1274 // $$$ TODO preserve center of view when switching between mode
1275 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1277 // XXX maybe better to preserve zoom in each mode
1279 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'), $('#BRcontainer').attr('clientHeight'));
1280 this.reduce = this.quantizeReduce(this.reduce, this.onePage.reductionFactors);
1281 this.prepareOnePageView();
1282 } else if (3 == mode) {
1283 $('button.thumb').hide();
1284 $('button.twopg').show();
1285 this.reduce = this.quantizeReduce(this.reduce, this.reductionFactors);
1286 this.prepareThumbnailView();
1288 // $$$ why don't we save autofit?
1289 // this.twoPage.autofit = null; // Take zoom level from other mode
1290 this.twoPageCalculateReductionFactors();
1291 this.reduce = this.quantizeReduce(this.reduce, this.twoPage.reductionFactors);
1292 $('button.thumb').show();
1293 $('button.twopg').hide();
1294 this.prepareTwoPageView();
1295 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1300 //prepareOnePageView()
1301 //______________________________________________________________________________
1302 BookReader.prototype.prepareOnePageView = function() {
1304 // var startLeaf = this.displayedIndices[0];
1305 var startLeaf = this.currentIndex();
1307 $('#BRcontainer').empty();
1308 $('#BRcontainer').css({
1309 overflowY: 'scroll',
1313 $("#BRcontainer").append("<div id='BRpageview'></div>");
1315 // Attaches to first child - child must be present
1316 $('#BRcontainer').dragscrollable();
1317 this.bindGestures($('#BRcontainer'));
1319 // $$$ keep select enabled for now since disabling it breaks keyboard
1320 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1321 // BookReader.util.disableSelect($('#BRpageview'));
1323 this.resizePageView();
1325 this.jumpToIndex(startLeaf);
1326 this.displayedIndices = [];
1328 this.drawLeafsOnePage();
1331 //prepareThumbnailView()
1332 //______________________________________________________________________________
1333 BookReader.prototype.prepareThumbnailView = function() {
1335 $('#BRcontainer').empty();
1336 $('#BRcontainer').css({
1337 overflowY: 'scroll',
1341 $("#BRcontainer").append("<div id='BRpageview'></div>");
1343 $('#BRcontainer').dragscrollable();
1344 this.bindGestures($('#BRcontainer'));
1346 // $$$ keep select enabled for now since disabling it breaks keyboard
1347 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1348 // BookReader.util.disableSelect($('#BRpageview'));
1350 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1351 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1353 this.displayedRows = [];
1355 // Draw leafs with current index directly in view (no animating to the index)
1356 this.drawLeafsThumbnail( this.currentIndex() );
1360 // prepareTwoPageView()
1361 //______________________________________________________________________________
1362 // Some decisions about two page view:
1364 // Both pages will be displayed at the same height, even if they were different physical/scanned
1365 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1366 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1367 // aspect ratio to determine the height.
1369 // The two page view div is resized to keep the middle of the book in the middle of the div
1370 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1371 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1372 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1373 $('#BRcontainer').empty();
1374 $('#BRcontainer').css('overflow', 'auto');
1376 // We want to display two facing pages. We may be missing
1377 // one side of the spread because it is the first/last leaf,
1378 // foldouts, missing pages, etc
1380 //var targetLeaf = this.displayedIndices[0];
1381 var targetLeaf = this.firstIndex;
1383 if (targetLeaf < this.firstDisplayableIndex()) {
1384 targetLeaf = this.firstDisplayableIndex();
1387 if (targetLeaf > this.lastDisplayableIndex()) {
1388 targetLeaf = this.lastDisplayableIndex();
1391 //this.twoPage.currentIndexL = null;
1392 //this.twoPage.currentIndexR = null;
1393 //this.pruneUnusedImgs();
1395 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1396 this.twoPage.currentIndexL = currentSpreadIndices[0];
1397 this.twoPage.currentIndexR = currentSpreadIndices[1];
1398 this.firstIndex = this.twoPage.currentIndexL;
1400 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1402 this.pruneUnusedImgs();
1403 this.prefetch(); // Preload images or reload if scaling has changed
1405 //console.dir(this.twoPage);
1407 // Add the two page view
1408 // $$$ Can we get everything set up and then append?
1409 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1411 // Attaches to first child, so must come after we add the page view
1412 $('#BRcontainer').dragscrollable();
1413 this.bindGestures($('#BRcontainer'));
1415 // $$$ calculate first then set
1416 $('#BRtwopageview').css( {
1417 height: this.twoPage.totalHeight + 'px',
1418 width: this.twoPage.totalWidth + 'px',
1419 position: 'absolute'
1422 // If there will not be scrollbars (e.g. when zooming out) we center the book
1423 // since otherwise the book will be stuck off-center
1424 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1425 centerPercentageX = 0.5;
1427 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1428 centerPercentageY = 0.5;
1431 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1433 this.twoPage.coverDiv = document.createElement('div');
1434 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1435 width: this.twoPage.bookCoverDivWidth + 'px',
1436 height: this.twoPage.bookCoverDivHeight+'px',
1437 visibility: 'visible',
1438 }).appendTo('#BRtwopageview');
1440 this.leafEdgeR = document.createElement('div');
1441 this.leafEdgeR.className = 'BRleafEdgeR';
1442 $(this.leafEdgeR).css({
1443 width: this.twoPage.leafEdgeWidthR + 'px',
1444 height: this.twoPage.height-1 + 'px',
1445 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1446 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px'
1447 }).appendTo('#BRtwopageview');
1449 this.leafEdgeL = document.createElement('div');
1450 this.leafEdgeL.className = 'BRleafEdgeL';
1451 $(this.leafEdgeL).css({
1452 width: this.twoPage.leafEdgeWidthL + 'px',
1453 height: this.twoPage.height-1 + 'px',
1454 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1455 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px'
1456 }).appendTo('#BRtwopageview');
1458 div = document.createElement('div');
1459 $(div).attr('id', 'BRbookspine').css({
1460 width: this.twoPage.bookSpineDivWidth+'px',
1461 height: this.twoPage.bookSpineDivHeight+'px',
1462 left: this.twoPage.bookSpineDivLeft+'px',
1463 top: this.twoPage.bookSpineDivTop+'px'
1464 }).appendTo('#BRtwopageview');
1466 var self = this; // for closure
1468 /* Flip areas no longer used
1469 this.twoPage.leftFlipArea = document.createElement('div');
1470 this.twoPage.leftFlipArea.className = 'BRfliparea';
1471 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1473 width: this.twoPageFlipAreaWidth() + 'px',
1474 height: this.twoPageFlipAreaHeight() + 'px',
1475 position: 'absolute',
1476 left: this.twoPageLeftFlipAreaLeft() + 'px',
1477 top: this.twoPageFlipAreaTop() + 'px',
1480 }).click(function(e) {
1482 }).bind('mousedown', function(e) {
1484 }).appendTo('#BRtwopageview');
1486 this.twoPage.rightFlipArea = document.createElement('div');
1487 this.twoPage.rightFlipArea.className = 'BRfliparea';
1488 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1490 width: this.twoPageFlipAreaWidth() + 'px',
1491 height: this.twoPageFlipAreaHeight() + 'px',
1492 position: 'absolute',
1493 left: this.twoPageRightFlipAreaLeft() + 'px',
1494 top: this.twoPageFlipAreaTop() + 'px',
1497 }).click(function(e) {
1499 }).bind('mousedown', function(e) {
1501 }).appendTo('#BRtwopageview');
1504 this.prepareTwoPagePopUp();
1506 this.displayedIndices = [];
1508 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1509 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1511 this.drawLeafsTwoPage();
1512 this.updateToolbarZoom(this.reduce);
1516 this.removeSearchHilites();
1517 this.updateSearchHilites();
1521 // prepareTwoPagePopUp()
1523 // This function prepares the "View Page n" popup that shows while the mouse is
1524 // over the left/right "stack of sheets" edges. It also binds the mouse
1525 // events for these divs.
1526 //______________________________________________________________________________
1527 BookReader.prototype.prepareTwoPagePopUp = function() {
1529 this.twoPagePopUp = document.createElement('div');
1530 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1531 $(this.twoPagePopUp).css({
1533 // XXXmang move to CSS
1535 position: 'absolute',
1536 fontFamily: 'Arial,sans-serif',
1540 backgroundColor: '#939598',
1542 webkitBorderRadius: '4px',
1543 mozBorderRadius: '4px',
1544 borderRadius: '4px',
1545 whiteSpace: 'nowrap'
1546 }).appendTo('#BRcontainer');
1547 $(this.twoPagePopUp).hide();
1549 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1550 $(e.data.twoPagePopUp).show();
1553 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1554 $(e.data.twoPagePopUp).hide();
1557 $(this.leafEdgeL).bind('click', this, function(e) {
1559 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1560 e.data.jumpToIndex(jumpIndex);
1563 $(this.leafEdgeR).bind('click', this, function(e) {
1565 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1566 e.data.jumpToIndex(jumpIndex);
1569 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1571 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1572 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1574 // $$$ TODO: Make sure popup is positioned so that it is in view
1575 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1576 $(e.data.twoPagePopUp).css({
1577 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - 100 + 'px',
1578 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1582 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1584 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1585 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1587 // $$$ TODO: Make sure popup is positioned so that it is in view
1588 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1589 $(e.data.twoPagePopUp).css({
1590 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() + 100 + 'px',
1591 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1596 // calculateSpreadSize()
1597 //______________________________________________________________________________
1598 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1599 // this.twoPage.currentIndexR
1600 // This function sets this.twoPage.height, twoPage.width
1602 BookReader.prototype.calculateSpreadSize = function() {
1604 var firstIndex = this.twoPage.currentIndexL;
1605 var secondIndex = this.twoPage.currentIndexR;
1606 //console.log('first page is ' + firstIndex);
1608 // Calculate page sizes and total leaf width
1610 if ( this.twoPage.autofit) {
1611 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1613 // set based on reduction factor
1614 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1617 // Both pages together
1618 this.twoPage.height = spreadSize.height;
1619 this.twoPage.width = spreadSize.width;
1622 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1623 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1626 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1627 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1628 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1632 // The width of the book cover div. The combined width of both pages, twice the width
1633 // of the book cover internal padding (2*10) and the page edges
1634 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1635 // The height of the book cover div
1636 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1639 // We calculate the total width and height for the div so that we can make the book
1641 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1642 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1643 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1644 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1645 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1646 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1648 // We want to minimize the unused space in two-up mode (maximize the amount of page
1649 // shown). We give width to the leaf edges and these widths change (though the sum
1650 // of the two remains constant) as we flip through the book. With the book
1651 // cover centered and fixed in the BRcontainer div the page images will meet
1652 // at the "gutter" which is generally offset from the center.
1653 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1654 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1656 // The left edge of the book cover moves depending on the width of the pages
1657 // $$$ change to getter
1658 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1659 // The top edge of the book cover stays a fixed distance from the top
1660 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1663 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1664 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1665 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1668 this.reduce = spreadSize.reduce; // $$$ really set this here?
1671 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1674 // We check which page is closest to a "normal" page and use that to set the height
1675 // for both pages. This means that foldouts and other odd size pages will be displayed
1676 // smaller than the nominal zoom amount.
1677 var canon5Dratio = 1.5;
1680 height: this._getPageHeight(firstIndex),
1681 width: this._getPageWidth(firstIndex)
1685 height: this._getPageHeight(secondIndex),
1686 width: this._getPageWidth(secondIndex)
1689 var firstIndexRatio = first.height / first.width;
1690 var secondIndexRatio = second.height / second.width;
1691 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1694 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1695 ratio = firstIndexRatio;
1696 //console.log('using firstIndexRatio ' + ratio);
1698 ratio = secondIndexRatio;
1699 //console.log('using secondIndexRatio ' + ratio);
1702 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1703 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1704 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1706 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1707 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1709 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1710 ideal.width -= 10; // $$$ fudge factor
1711 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1712 ideal.height -= 20; // fudge factor
1713 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1715 if (ideal.height/ratio <= ideal.width) {
1717 ideal.width = parseInt(ideal.height/ratio);
1720 ideal.height = parseInt(ideal.width*ratio);
1723 // $$$ check this logic with large spreads
1724 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1729 // getSpreadSizeFromReduce()
1730 //______________________________________________________________________________
1731 // Returns the spread size calculated from the reduction factor for the given pages
1732 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1733 var spreadSize = {};
1734 // $$$ Scale this based on reduce?
1735 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1736 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1737 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1739 // $$$ Possibly incorrect -- we should make height "dominant"
1740 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1741 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1742 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1743 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1744 spreadSize.reduce = reduce;
1749 // twoPageGetAutofitReduce()
1750 //______________________________________________________________________________
1751 // Returns the current ideal reduction factor
1752 BookReader.prototype.twoPageGetAutofitReduce = function() {
1753 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1754 return spreadSize.reduce;
1757 BookReader.prototype.onePageGetAutofitWidth = function() {
1758 var widthPadding = 20;
1759 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1762 BookReader.prototype.onePageGetAutofitHeight = function() {
1763 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - this.padding * 2); // make sure a little of adjacent pages show
1766 BookReader.prototype.getMedianPageSize = function() {
1767 if (this._medianPageSize) {
1768 return this._medianPageSize;
1771 // A little expensive but we just do it once
1774 for (var i = 0; i < this.numLeafs; i++) {
1775 widths.push(this.getPageWidth(i));
1776 heights.push(this.getPageHeight(i));
1782 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1783 return this._medianPageSize;
1786 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1787 // the autofit reduction factors.
1788 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1789 this.onePage.reductionFactors = this.reductionFactors.concat(
1791 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1792 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1794 this.onePage.reductionFactors.sort(this._reduceSort);
1797 BookReader.prototype.twoPageCalculateReductionFactors = function() {
1798 this.twoPage.reductionFactors = this.reductionFactors.concat(
1800 { reduce: this.getIdealSpreadSize( this.twoPage.currentIndexL, this.twoPage.currentIndexR ).reduce,
1803 this.twoPage.reductionFactors.sort(this._reduceSort);
1806 // twoPageSetCursor()
1807 //______________________________________________________________________________
1808 // Set the cursor for two page view
1809 BookReader.prototype.twoPageSetCursor = function() {
1810 // console.log('setting cursor');
1811 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1812 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1813 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1814 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1816 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1817 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1822 //______________________________________________________________________________
1823 // Returns the currently active index.
1824 BookReader.prototype.currentIndex = function() {
1825 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1826 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1827 return this.firstIndex; // $$$ TODO page in center of view would be better
1828 } else if (this.mode == this.constMode2up) {
1829 // Only allow indices that are actually present in book
1830 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1832 throw 'currentIndex called for unimplemented mode ' + this.mode;
1836 // setCurrentIndex(index)
1837 //______________________________________________________________________________
1838 // Sets the idea of current index without triggering other actions such as animation.
1839 // Compare to jumpToIndex which animates to that index
1840 BookReader.prototype.setCurrentIndex = function(index) {
1841 this.firstIndex = index;
1846 //______________________________________________________________________________
1847 // Flip the right page over onto the left
1848 BookReader.prototype.right = function() {
1849 if ('rl' != this.pageProgression) {
1859 //______________________________________________________________________________
1860 // Flip to the rightmost page
1861 BookReader.prototype.rightmost = function() {
1862 if ('rl' != this.pageProgression) {
1870 //______________________________________________________________________________
1871 // Flip the left page over onto the right.
1872 BookReader.prototype.left = function() {
1873 if ('rl' != this.pageProgression) {
1883 //______________________________________________________________________________
1884 // Flip to the leftmost page
1885 BookReader.prototype.leftmost = function() {
1886 if ('rl' != this.pageProgression) {
1894 //______________________________________________________________________________
1895 BookReader.prototype.next = function() {
1896 if (2 == this.mode) {
1898 this.flipFwdToIndex(null);
1900 if (this.firstIndex < this.lastDisplayableIndex()) {
1901 this.jumpToIndex(this.firstIndex+1);
1907 //______________________________________________________________________________
1908 BookReader.prototype.prev = function() {
1909 if (2 == this.mode) {
1911 this.flipBackToIndex(null);
1913 if (this.firstIndex >= 1) {
1914 this.jumpToIndex(this.firstIndex-1);
1919 BookReader.prototype.first = function() {
1920 this.jumpToIndex(this.firstDisplayableIndex());
1923 BookReader.prototype.last = function() {
1924 this.jumpToIndex(this.lastDisplayableIndex());
1928 //______________________________________________________________________________
1929 // Scrolls down one screen view
1930 BookReader.prototype.scrollDown = function() {
1931 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1932 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1933 // Whole pages are visible, scroll whole page only
1937 $('#BRcontainer').animate(
1938 { scrollTop: '+=' + this._scrollAmount() + 'px'},
1939 400, 'easeInOutExpo'
1948 //______________________________________________________________________________
1949 // Scrolls up one screen view
1950 BookReader.prototype.scrollUp = function() {
1951 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1952 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1953 // Whole pages are visible, scroll whole page only
1957 $('#BRcontainer').animate(
1958 { scrollTop: '-=' + this._scrollAmount() + 'px'},
1959 400, 'easeInOutExpo'
1968 //______________________________________________________________________________
1969 // The amount to scroll vertically in integer pixels
1970 BookReader.prototype._scrollAmount = function() {
1971 if (this.constMode1up == this.mode) {
1972 // Overlap by % of page size
1973 return parseInt($('#BRcontainer').attr('clientHeight') - this.getPageHeight(this.currentIndex()) / this.reduce * 0.03);
1976 return parseInt(0.9 * $('#BRcontainer').attr('clientHeight'));
1980 // flipBackToIndex()
1981 //______________________________________________________________________________
1982 // to flip back one spread, pass index=null
1983 BookReader.prototype.flipBackToIndex = function(index) {
1985 if (1 == this.mode) return;
1987 var leftIndex = this.twoPage.currentIndexL;
1989 if (this.animating) return;
1991 if (null != this.leafEdgeTmp) {
1992 alert('error: leafEdgeTmp should be null!');
1996 if (null == index) {
1997 index = leftIndex-2;
1999 //if (index<0) return;
2001 var previousIndices = this.getSpreadIndices(index);
2003 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
2007 this.animating = true;
2009 if ('rl' != this.pageProgression) {
2010 // Assume LTR and we are going backward
2011 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
2012 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
2014 // RTL and going backward
2015 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2016 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2020 // flipLeftToRight()
2021 //______________________________________________________________________________
2022 // Flips the page on the left towards the page on the right
2023 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2025 var leftLeaf = this.twoPage.currentIndexL;
2027 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2028 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2029 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2031 var currWidthL = this.getPageWidth2UP(leftLeaf);
2032 var newWidthL = this.getPageWidth2UP(newIndexL);
2033 var newWidthR = this.getPageWidth2UP(newIndexR);
2035 var top = this.twoPageTop();
2036 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2038 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2039 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2041 //animation strategy:
2042 // 0. remove search highlight, if any.
2043 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2044 // of the left leaf and where the user clicked in the leaf edge.
2045 // Note that if this function was triggered by left() and not a
2046 // mouse click, the width of leafEdgeTmp is very small (zero px).
2047 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2048 // leftLeaf to width=0.
2049 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2050 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2051 // its new full width.
2052 // 4. After step 3 is finished, do the following:
2053 // - remove leafEdgeTmp from the dom.
2054 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2055 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2056 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2057 // and width=newLeafEdgeWidthL.
2058 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2059 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2060 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2061 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2062 // - prefetch new adjacent leafs.
2063 // - set up click handlers for both new left and right leafs.
2064 // - redraw the search highlight.
2065 // - update the pagenum box and the url.
2068 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2070 this.leafEdgeTmp = document.createElement('div');
2071 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2072 $(this.leafEdgeTmp).css({
2073 width: leafEdgeTmpW + 'px',
2074 height: this.twoPage.height-1 + 'px',
2075 left: leftEdgeTmpLeft + 'px',
2078 }).appendTo('#BRtwopageview');
2080 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2081 $(this.leafEdgeL).css({
2082 width: newLeafEdgeWidthL+'px',
2083 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2086 // Left gets the offset of the current left leaf from the document
2087 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2088 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2089 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2091 // We change the left leaf to right positioning
2092 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2093 $(this.prefetchedImgs[leftLeaf]).css({
2098 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2099 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2103 this.removeSearchHilites();
2105 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2106 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2108 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2109 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2111 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2112 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2113 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2115 $(self.leafEdgeR).css({
2116 // Moves the right leaf edge
2117 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2118 left: gutter+newWidthR+'px'
2121 $(self.leafEdgeL).css({
2122 // Moves and resizes the left leaf edge
2123 width: newLeafEdgeWidthL+'px',
2124 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2127 // Resizes the brown border div
2128 $(self.twoPage.coverDiv).css({
2129 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2130 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2133 $(self.leafEdgeTmp).remove();
2134 self.leafEdgeTmp = null;
2136 // $$$ TODO refactor with opposite direction flip
2138 self.twoPage.currentIndexL = newIndexL;
2139 self.twoPage.currentIndexR = newIndexR;
2140 self.twoPage.scaledWL = newWidthL;
2141 self.twoPage.scaledWR = newWidthR;
2142 self.twoPage.gutter = gutter;
2144 self.firstIndex = self.twoPage.currentIndexL;
2145 self.displayedIndices = [newIndexL, newIndexR];
2146 self.pruneUnusedImgs();
2148 self.animating = false;
2150 self.updateSearchHilites2UP();
2151 self.updatePageNumBox2UP();
2153 // self.twoPagePlaceFlipAreas(); // No longer used
2154 self.setMouseHandlers2UP();
2155 self.twoPageSetCursor();
2157 if (self.animationFinishedCallback) {
2158 self.animationFinishedCallback();
2159 self.animationFinishedCallback = null;
2167 //______________________________________________________________________________
2168 // Whether we flip left or right is dependent on the page progression
2169 // to flip forward one spread, pass index=null
2170 BookReader.prototype.flipFwdToIndex = function(index) {
2172 if (this.animating) return;
2174 if (null != this.leafEdgeTmp) {
2175 alert('error: leafEdgeTmp should be null!');
2179 if (null == index) {
2180 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2182 if (index > this.lastDisplayableIndex()) return;
2184 this.animating = true;
2186 var nextIndices = this.getSpreadIndices(index);
2188 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2190 if ('rl' != this.pageProgression) {
2191 // We did not specify RTL
2192 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2193 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2196 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2197 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2201 // flipRightToLeft(nextL, nextR, gutter)
2202 // $$$ better not to have to pass gutter in
2203 //______________________________________________________________________________
2204 // Flip from left to right and show the nextL and nextR indices on those sides
2205 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2206 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2207 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2208 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2209 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2211 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2213 var top = this.twoPageTop();
2214 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2216 var middle = this.twoPage.middle;
2217 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2219 this.leafEdgeTmp = document.createElement('div');
2220 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2221 $(this.leafEdgeTmp).css({
2222 width: leafEdgeTmpW + 'px',
2223 height: this.twoPage.height-1 + 'px',
2224 left: gutter+scaledW+'px',
2227 }).appendTo('#BRtwopageview');
2229 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2230 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2232 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2233 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2234 var newWidthL = this.getPageWidth2UP(newIndexL);
2235 var newWidthR = this.getPageWidth2UP(newIndexR);
2237 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2239 var self = this; // closure-tastic!
2241 var speed = this.flipSpeed;
2243 this.removeSearchHilites();
2245 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2246 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2247 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2248 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2249 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2251 $(self.leafEdgeL).css({
2252 width: newLeafEdgeWidthL+'px',
2253 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2256 // Resizes the book cover
2257 $(self.twoPage.coverDiv).css({
2258 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2259 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2262 $(self.leafEdgeTmp).remove();
2263 self.leafEdgeTmp = null;
2265 self.twoPage.currentIndexL = newIndexL;
2266 self.twoPage.currentIndexR = newIndexR;
2267 self.twoPage.scaledWL = newWidthL;
2268 self.twoPage.scaledWR = newWidthR;
2269 self.twoPage.gutter = gutter;
2271 self.firstIndex = self.twoPage.currentIndexL;
2272 self.displayedIndices = [newIndexL, newIndexR];
2273 self.pruneUnusedImgs();
2275 self.animating = false;
2278 self.updateSearchHilites2UP();
2279 self.updatePageNumBox2UP();
2281 // self.twoPagePlaceFlipAreas(); // No longer used
2282 self.setMouseHandlers2UP();
2283 self.twoPageSetCursor();
2285 if (self.animationFinishedCallback) {
2286 self.animationFinishedCallback();
2287 self.animationFinishedCallback = null;
2293 // setMouseHandlers2UP
2294 //______________________________________________________________________________
2295 BookReader.prototype.setMouseHandlers2UP = function() {
2296 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2304 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2307 e.data.self.right();
2314 //______________________________________________________________________________
2315 BookReader.prototype.prefetchImg = function(index) {
2316 var pageURI = this._getPageURI(index);
2318 // Load image if not loaded or URI has changed (e.g. due to scaling)
2319 var loadImage = false;
2320 if (undefined == this.prefetchedImgs[index]) {
2321 //console.log('no image for ' + index);
2323 } else if (pageURI != this.prefetchedImgs[index].uri) {
2324 //console.log('uri changed for ' + index);
2329 //console.log('prefetching ' + index);
2330 var img = document.createElement("img");
2331 img.className = 'BRpageimage';
2332 if (index < 0 || index > (this.numLeafs - 1) ) {
2333 // Facing page at beginning or end, or beyond
2335 'background-color': 'transparent'
2339 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2340 this.prefetchedImgs[index] = img;
2345 // prepareFlipLeftToRight()
2347 //______________________________________________________________________________
2349 // Prepare to flip the left page towards the right. This corresponds to moving
2350 // backward when the page progression is left to right.
2351 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2353 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2355 this.prefetchImg(prevL);
2356 this.prefetchImg(prevR);
2358 var height = this._getPageHeight(prevL);
2359 var width = this._getPageWidth(prevL);
2360 var middle = this.twoPage.middle;
2361 var top = this.twoPageTop();
2362 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2364 // The gutter is the dividing line between the left and right pages.
2365 // It is offset from the middle to create the illusion of thickness to the pages
2366 var gutter = middle + this.gutterOffsetForIndex(prevL);
2368 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2369 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2370 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2373 position: 'absolute',
2374 left: gutter-scaledW+'px',
2375 right: '', // clear right property
2377 height: this.twoPage.height,
2378 width: scaledW+'px',
2379 borderRight: '1px solid black', // XXXmang check
2383 $(this.prefetchedImgs[prevL]).css(leftCSS);
2385 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2387 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2390 position: 'absolute',
2394 height: this.twoPage.height,
2395 borderLeft: '1px solid black', // XXXmang check
2400 $(this.prefetchedImgs[prevR]).css(rightCSS);
2402 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2406 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2407 // prepareFlipRightToLeft()
2408 //______________________________________________________________________________
2409 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2411 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2414 this.prefetchImg(nextL);
2415 this.prefetchImg(nextR);
2417 var height = this._getPageHeight(nextR);
2418 var width = this._getPageWidth(nextR);
2419 var middle = this.twoPage.middle;
2420 var top = this.twoPageTop();
2421 var scaledW = this.twoPage.height*width/height;
2423 var gutter = middle + this.gutterOffsetForIndex(nextL);
2425 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2426 $(this.prefetchedImgs[nextR]).css({
2427 position: 'absolute',
2430 height: this.twoPage.height,
2431 width: scaledW+'px',
2435 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2437 height = this._getPageHeight(nextL);
2438 width = this._getPageWidth(nextL);
2439 scaledW = this.twoPage.height*width/height;
2441 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2442 $(this.prefetchedImgs[nextL]).css({
2443 position: 'absolute',
2444 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2446 height: this.twoPage.height,
2447 width: 0+'px', // Start at 0 width, then grow to the left
2451 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2455 // getNextLeafs() -- NOT RTL AWARE
2456 //______________________________________________________________________________
2457 // BookReader.prototype.getNextLeafs = function(o) {
2458 // //TODO: we might have two left or two right leafs in a row (damaged book)
2459 // //For now, assume that leafs are contiguous.
2461 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2462 // o.L = this.twoPage.currentIndexL+2;
2463 // o.R = this.twoPage.currentIndexL+3;
2466 // getprevLeafs() -- NOT RTL AWARE
2467 //______________________________________________________________________________
2468 // BookReader.prototype.getPrevLeafs = function(o) {
2469 // //TODO: we might have two left or two right leafs in a row (damaged book)
2470 // //For now, assume that leafs are contiguous.
2472 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2473 // o.L = this.twoPage.currentIndexL-2;
2474 // o.R = this.twoPage.currentIndexL-1;
2477 // pruneUnusedImgs()
2478 //______________________________________________________________________________
2479 BookReader.prototype.pruneUnusedImgs = function() {
2480 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2481 for (var key in this.prefetchedImgs) {
2482 //console.log('key is ' + key);
2483 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2484 //console.log('removing key '+ key);
2485 $(this.prefetchedImgs[key]).remove();
2487 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2488 //console.log('deleting key '+ key);
2489 delete this.prefetchedImgs[key];
2495 //______________________________________________________________________________
2496 BookReader.prototype.prefetch = function() {
2498 // $$$ We should check here if the current indices have finished
2499 // loading (with some timeout) before loading more page images
2500 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2502 // prefetch visible pages first
2503 this.prefetchImg(this.twoPage.currentIndexL);
2504 this.prefetchImg(this.twoPage.currentIndexR);
2506 var adjacentPagesToLoad = 3;
2508 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2509 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2511 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2512 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2514 // Load images spreading out from current
2515 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2516 var goingDown = lowCurrent - i;
2517 if (goingDown >= start) {
2518 this.prefetchImg(goingDown);
2520 var goingUp = highCurrent + i;
2521 if (goingUp <= end) {
2522 this.prefetchImg(goingUp);
2527 var lim = this.twoPage.currentIndexL-4;
2529 lim = Math.max(lim, 0);
2530 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2531 this.prefetchImg(i);
2534 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2535 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2536 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2537 this.prefetchImg(i);
2543 // getPageWidth2UP()
2544 //______________________________________________________________________________
2545 BookReader.prototype.getPageWidth2UP = function(index) {
2546 // We return the width based on the dominant height
2547 var height = this._getPageHeight(index);
2548 var width = this._getPageWidth(index);
2549 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2553 //______________________________________________________________________________
2554 BookReader.prototype.search = function(term) {
2555 term = term.replace(/\//g, ' '); // strip slashes
2556 this.searchTerm = term;
2557 $('#BookReaderSearchScript').remove();
2558 var script = document.createElement("script");
2559 script.setAttribute('id', 'BookReaderSearchScript');
2560 script.setAttribute("type", "text/javascript");
2561 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2562 document.getElementsByTagName('head')[0].appendChild(script);
2563 $('#BookReaderSearchBox').val(term);
2564 $('#BookReaderSearchResults').html('Searching...');
2567 // BRSearchCallback()
2568 //______________________________________________________________________________
2569 BookReader.prototype.BRSearchCallback = function(txt) {
2571 if (jQuery.browser.msie) {
2572 var dom=new ActiveXObject("Microsoft.XMLDOM");
2576 var parser = new DOMParser();
2577 var dom = parser.parseFromString(txt, "text/xml");
2580 $('#BookReaderSearchResults').empty();
2581 $('#BookReaderSearchResults').append('<ul>');
2583 for (var key in this.searchResults) {
2584 if (null != this.searchResults[key].div) {
2585 $(this.searchResults[key].div).remove();
2587 delete this.searchResults[key];
2590 var pages = dom.getElementsByTagName('PAGE');
2592 if (0 == pages.length) {
2593 // $$$ it would be nice to echo the (sanitized) search result here
2594 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2596 for (var i = 0; i < pages.length; i++){
2597 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2600 var re = new RegExp (/_(\d{4})\.djvu/);
2601 var reMatch = re.exec(pages[i].getAttribute('file'));
2602 var index = parseInt(reMatch[1], 10);
2603 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2605 var children = pages[i].childNodes;
2607 for (var j=0; j<children.length; j++) {
2608 //console.log(j + ' - ' + children[j].nodeName);
2609 //console.log(children[j].firstChild.nodeValue);
2610 if ('CONTEXT' == children[j].nodeName) {
2611 context += children[j].firstChild.nodeValue;
2612 } else if ('WORD' == children[j].nodeName) {
2613 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2615 var index = this.leafNumToIndex(index);
2616 if (null != index) {
2617 //coordinates are [left, bottom, right, top, [baseline]]
2618 //we'll skip baseline for now...
2619 var coords = children[j].getAttribute('coords').split(',',4);
2620 if (4 == coords.length) {
2621 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2626 var pageName = this.getPageName(index);
2627 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2628 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2629 //TODO: remove hardcoded instance name
2630 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2633 $('#BookReaderSearchResults').append('</ul>');
2635 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2636 $('#BookReaderSearchBox').val(this.searchTerm);
2638 this.updateSearchHilites();
2641 // updateSearchHilites()
2642 //______________________________________________________________________________
2643 BookReader.prototype.updateSearchHilites = function() {
2644 if (2 == this.mode) {
2645 this.updateSearchHilites2UP();
2647 this.updateSearchHilites1UP();
2651 // showSearchHilites1UP()
2652 //______________________________________________________________________________
2653 BookReader.prototype.updateSearchHilites1UP = function() {
2655 for (var key in this.searchResults) {
2657 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2658 var result = this.searchResults[key];
2659 if (null == result.div) {
2660 result.div = document.createElement('div');
2661 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2662 //console.log('appending ' + key);
2665 width: (result.r-result.l)/this.reduce + 'px',
2666 height: (result.b-result.t)/this.reduce + 'px',
2667 left: (result.l)/this.reduce + 'px',
2668 top: (result.t)/this.reduce +'px'
2672 //console.log(key + ' not displayed');
2673 this.searchResults[key].div=null;
2679 //______________________________________________________________________________
2680 // Returns the position of the gutter (line between the page images)
2681 BookReader.prototype.twoPageGutter = function() {
2682 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2686 //______________________________________________________________________________
2687 // Returns the offset for the top of the page images
2688 BookReader.prototype.twoPageTop = function() {
2689 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2692 // twoPageCoverWidth()
2693 //______________________________________________________________________________
2694 // Returns the width of the cover div given the total page width
2695 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2696 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2699 // twoPageGetViewCenter()
2700 //______________________________________________________________________________
2701 // Returns the percentage offset into twopageview div at the center of container div
2702 // { percentageX: float, percentageY: float }
2703 BookReader.prototype.twoPageGetViewCenter = function() {
2706 var containerOffset = $('#BRcontainer').offset();
2707 var viewOffset = $('#BRtwopageview').offset();
2708 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2709 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2714 // twoPageCenterView(percentageX, percentageY)
2715 //______________________________________________________________________________
2716 // Centers the point given by percentage from left,top of twopageview
2717 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2718 if ('undefined' == typeof(percentageX)) {
2721 if ('undefined' == typeof(percentageY)) {
2725 var viewWidth = $('#BRtwopageview').width();
2726 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2727 var intoViewX = percentageX * viewWidth;
2729 var viewHeight = $('#BRtwopageview').height();
2730 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2731 var intoViewY = percentageY * viewHeight;
2733 if (viewWidth < containerClientWidth) {
2734 // Can fit width without scrollbars - center by adjusting offset
2735 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2737 // Need to scroll to center
2738 $('#BRtwopageview').css('left', 0);
2739 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2742 if (viewHeight < containerClientHeight) {
2743 // Fits with scrollbars - add offset
2744 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2746 $('#BRtwopageview').css('top', 0);
2747 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2751 // twoPageFlipAreaHeight
2752 //______________________________________________________________________________
2753 // Returns the integer height of the click-to-flip areas at the edges of the book
2754 BookReader.prototype.twoPageFlipAreaHeight = function() {
2755 return parseInt(this.twoPage.height);
2758 // twoPageFlipAreaWidth
2759 //______________________________________________________________________________
2760 // Returns the integer width of the flip areas
2761 BookReader.prototype.twoPageFlipAreaWidth = function() {
2762 var max = 100; // $$$ TODO base on view width?
2765 var width = this.twoPage.width * 0.15;
2766 return parseInt(BookReader.util.clamp(width, min, max));
2769 // twoPageFlipAreaTop
2770 //______________________________________________________________________________
2771 // Returns integer top offset for flip areas
2772 BookReader.prototype.twoPageFlipAreaTop = function() {
2773 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2776 // twoPageLeftFlipAreaLeft
2777 //______________________________________________________________________________
2778 // Left offset for left flip area
2779 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2780 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2783 // twoPageRightFlipAreaLeft
2784 //______________________________________________________________________________
2785 // Left offset for right flip area
2786 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2787 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2790 // twoPagePlaceFlipAreas
2791 //______________________________________________________________________________
2792 // Readjusts position of flip areas based on current layout
2793 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2794 // We don't set top since it shouldn't change relative to view
2795 $(this.twoPage.leftFlipArea).css({
2796 left: this.twoPageLeftFlipAreaLeft() + 'px',
2797 width: this.twoPageFlipAreaWidth() + 'px'
2799 $(this.twoPage.rightFlipArea).css({
2800 left: this.twoPageRightFlipAreaLeft() + 'px',
2801 width: this.twoPageFlipAreaWidth() + 'px'
2805 // showSearchHilites2UP()
2806 //______________________________________________________________________________
2807 BookReader.prototype.updateSearchHilites2UP = function() {
2809 for (var key in this.searchResults) {
2810 key = parseInt(key, 10);
2811 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2812 var result = this.searchResults[key];
2813 if (null == result.div) {
2814 result.div = document.createElement('div');
2815 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2816 //console.log('appending ' + key);
2819 // We calculate the reduction factor for the specific page because it can be different
2820 // for each page in the spread
2821 var height = this._getPageHeight(key);
2822 var width = this._getPageWidth(key)
2823 var reduce = this.twoPage.height/height;
2824 var scaledW = parseInt(width*reduce);
2826 var gutter = this.twoPageGutter();
2828 if ('L' == this.getPageSide(key)) {
2829 pageL = gutter-scaledW;
2833 var pageT = this.twoPageTop();
2836 width: (result.r-result.l)*reduce + 'px',
2837 height: (result.b-result.t)*reduce + 'px',
2838 left: pageL+(result.l)*reduce + 'px',
2839 top: pageT+(result.t)*reduce +'px'
2843 //console.log(key + ' not displayed');
2844 if (null != this.searchResults[key].div) {
2845 //console.log('removing ' + key);
2846 $(this.searchResults[key].div).remove();
2848 this.searchResults[key].div=null;
2853 // removeSearchHilites()
2854 //______________________________________________________________________________
2855 BookReader.prototype.removeSearchHilites = function() {
2856 for (var key in this.searchResults) {
2857 if (null != this.searchResults[key].div) {
2858 $(this.searchResults[key].div).remove();
2859 this.searchResults[key].div=null;
2865 //______________________________________________________________________________
2866 BookReader.prototype.printPage = function() {
2867 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2870 // Get print URI from current indices and mode
2871 BookReader.prototype.getPrintURI = function() {
2873 if (this.constMode2up == this.mode) {
2874 indexToPrint = this.twoPage.currentIndexL;
2876 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2879 var options = 'id=' + this.subPrefix + '&server=' + this.server + '&zip=' + this.zip
2880 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2881 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2883 if (this.constMode2up == this.mode) {
2884 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2885 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2886 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2888 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2891 return '/bookreader/print.php?' + options;
2894 /* iframe implementation
2895 BookReader.prototype.getPrintFrameContent = function(index) {
2896 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2897 // 8.5x11 so we should end up not overflowing on either paper size.
2898 var paperAspect = 8.5 / 11;
2899 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2903 // Rotate if possible and appropriate, to get larger image size on printed page
2904 if (this.canRotatePage(index)) {
2905 if (imageAspect > 1 && imageAspect > paperAspect) {
2906 // more wide than square, and more wide than paper
2908 imageAspect = 1/imageAspect;
2913 if (imageAspect > paperAspect) {
2914 // wider than paper, fit width
2915 fitAttrs = 'width="95%"';
2917 // taller than paper, fit height
2918 fitAttrs = 'height="95%"';
2921 var imageURL = this._getPageURI(index, 1, rotate);
2922 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2923 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2924 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2925 iframeStr += '</div>';
2926 iframeStr += '</body></html>';
2931 BookReader.prototype.updatePrintFrame = function(delta) {
2932 var newIndex = this.indexToPrint + delta;
2933 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2934 if (newIndex == this.indexToPrint) {
2937 this.indexToPrint = newIndex;
2938 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2939 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2944 //______________________________________________________________________________
2945 BookReader.prototype.showEmbedCode = function() {
2946 this.embedPopup = document.createElement("div");
2947 $(this.embedPopup).css({
2948 position: 'absolute',
2949 top: ($('#BRcontainer').attr('clientHeight')-250)/2 + 'px',
2950 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2957 border: '10px solid #615132',
2958 backgroundColor: "#fff",
2959 MozBorderRadius: '8px',
2960 MozBoxShadow: '0 0 6px #000',
2961 WebkitBorderRadius: '8px',
2962 WebkitBoxShadow: '0 0 6px #000'
2963 }).appendTo('#BookReader');
2965 htmlStr = '<h3 style="background:#615132;padding:10px;margin:0 0 10px;color:#fff;">Embed Bookreader</h3>';
2966 htmlStr += '<p style="padding:10px;line-height:18px;">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>';
2967 htmlStr += '<textarea rows="2" cols="40" style="margin-left:10px;width:368px;height:40px;color:#333;font-size:12px;border:2px inset #ccc;background:#efefef;padding:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;">' + this.getEmbedCode() + '</textarea>';
2968 htmlStr += '<a href="javascript:;" class="popOff" onclick="$(this.parentNode).remove();$(\'.coverUp\').hide();return false" style="color:#999;"><span>Close</span></a>';
2970 this.embedPopup.innerHTML = htmlStr;
2971 $('#BookReader').append('<div class="coverUp" style="position:absolute;z-index:299;width:100%;height:100%;background:#000;opacity:.4;filter:alpha(opacity=40);" onclick="$(\'.popped\').hide();$(this).hide();"></div>');
2972 $(this.embedPopup).find('textarea').click(function() {
2975 $(this.embedPopup).addClass("popped");
2978 // showBookmarkCode()
2979 //______________________________________________________________________________
2980 BookReader.prototype.showBookmarkCode = function() {
2981 this.bookmarkPopup = document.createElement("div");
2982 $(this.bookmarkPopup).css({
2983 position: 'absolute',
2984 top: ($('#BRcontainer').attr('clientHeight')-250)/2 + 'px',
2985 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2992 border: '10px solid #615132',
2993 backgroundColor: "#fff",
2994 MozBorderRadius: '8px',
2995 MozBoxShadow: '0 0 6px #000',
2996 WebkitBorderRadius: '8px',
2997 WebkitBoxShadow: '0 0 6px #000'
2998 }).appendTo('#BookReader');
3000 htmlStr = '<h3 style="background:#615132;padding:10px;margin:0 0 10px;color:#fff;">Add a bookmark</h3>';
3001 htmlStr += '<p style="padding:10px;line-height:18px;">You can add a bookmark to any page in any book. If you elect to make your bookmark public, other readers will be able to see it. <em>You must be logged in to your <a href="">Open Library account</a> to add bookmarks.</em></p>';
3002 htmlStr += '<form name="bookmark" id="bookmark" style="line-height:20px;margin-left:10px;"><label style="padding-bottom"10px;><input type="radio" name="privacy" id="p2" disabled="disabled" checked="checked"/> Make this bookmark public.</label><br/><label style="padding-bottom:10px;"><input type="radio" name="privacy" id="p1" disabled="disabled"/> Keep this bookmark private.</label><br/><br/><button type="submit" style="font-size:20px;" disabled="disabled">Add a bookmark</button></form>';
3003 htmlStr += '<a href="javascript:;" class="popOff" onclick="$(this.parentNode).remove();$(\'.coverUp\').hide();return false;" style="color:#999;"><span>Close</span></a>';
3005 this.bookmarkPopup.innerHTML = htmlStr;
3006 $('#BookReader').append('<div class="coverUp" style="position:absolute;z-index:299;width:100%;height:100%;background:#000;opacity:.4;filter:alpha(opacity=40);" onclick="$(\'.popped\').hide();$(this).hide();"></div>');
3007 $(this.bookmarkPopup).find('textarea').click(function() {
3010 $(this.bookmarkPopup).addClass("popped");
3015 //______________________________________________________________________________
3016 BookReader.prototype.autoToggle = function() {
3018 var bComingFrom1up = false;
3019 if (2 != this.mode) {
3020 bComingFrom1up = true;
3024 // Change to autofit if book is too large
3025 if (this.reduce < this.twoPageGetAutofitReduce()) {
3026 this.zoom2up('auto');
3030 if (null == this.autoTimer) {
3031 this.flipSpeed = 2000;
3033 // $$$ Draw events currently cause layout problems when they occur during animation.
3034 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3035 // we workaround for now by not triggering immediate animation in that case.
3036 // See https://bugs.launchpad.net/gnubook/+bug/328327
3037 if (('rl' == this.pageProgression) && bComingFrom1up) {
3038 // don't flip immediately -- wait until timer fires
3041 this.flipFwdToIndex();
3044 $('#BRtoolbar .play').hide();
3045 $('#BRtoolbar .pause').show();
3046 this.autoTimer=setInterval(function(){
3047 if (self.animating) {return;}
3049 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3050 self.flipBackToIndex(1); // $$$ really what we want?
3052 self.flipFwdToIndex();
3061 //______________________________________________________________________________
3062 // Stop autoplay mode, allowing animations to finish
3063 BookReader.prototype.autoStop = function() {
3064 if (null != this.autoTimer) {
3065 clearInterval(this.autoTimer);
3066 this.flipSpeed = 'fast';
3067 $('#BRtoolbar .pause').hide();
3068 $('#BRtoolbar .play').show();
3069 this.autoTimer = null;
3073 // stopFlipAnimations
3074 //______________________________________________________________________________
3075 // Immediately stop flip animations. Callbacks are triggered.
3076 BookReader.prototype.stopFlipAnimations = function() {
3078 this.autoStop(); // Clear timers
3080 // Stop animation, clear queue, trigger callbacks
3081 if (this.leafEdgeTmp) {
3082 $(this.leafEdgeTmp).stop(false, true);
3084 jQuery.each(this.prefetchedImgs, function() {
3085 $(this).stop(false, true);
3088 // And again since animations also queued in callbacks
3089 if (this.leafEdgeTmp) {
3090 $(this.leafEdgeTmp).stop(false, true);
3092 jQuery.each(this.prefetchedImgs, function() {
3093 $(this).stop(false, true);
3098 // keyboardNavigationIsDisabled(event)
3099 // - returns true if keyboard navigation should be disabled for the event
3100 //______________________________________________________________________________
3101 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3102 if (event.target.tagName == "INPUT") {
3108 // gutterOffsetForIndex
3109 //______________________________________________________________________________
3111 // Returns the gutter offset for the spread containing the given index.
3112 // This function supports RTL
3113 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3115 // To find the offset of the gutter from the middle we calculate our percentage distance
3116 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3117 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3119 // But then again for RTL it's the opposite
3120 if ('rl' == this.pageProgression) {
3128 //______________________________________________________________________________
3129 // Returns the width of the leaf edge div for the page with index given
3130 BookReader.prototype.leafEdgeWidth = function(pindex) {
3131 // $$$ could there be single pixel rounding errors for L vs R?
3132 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3133 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3135 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3139 // jumpIndexForLeftEdgePageX
3140 //______________________________________________________________________________
3141 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3142 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3143 if ('rl' != this.pageProgression) {
3144 // LTR - flipping backward
3145 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3147 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3148 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3152 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3153 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3158 // jumpIndexForRightEdgePageX
3159 //______________________________________________________________________________
3160 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3161 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3162 if ('rl' != this.pageProgression) {
3164 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3165 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3168 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3169 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3174 BookReader.prototype.initToolbar = function(mode, ui) {
3176 $("body").append("<div id='BRtoolbar'>"
3177 + "<span id='BRtoolbarbuttons' style='float:right;'>"
3178 + "<button class='BRicon bookmark modal'></button>"
3179 + "<button class='BRicon link modal'></button>"
3180 + "<button class='BRicon embed modal'></button>"
3181 + "<button class='BRicon read modal'></button>"
3182 + "<button class='BRicon full'></button>"
3183 // + "<div class='BRtoolbarmode2' style='display: none'><button class='BRicon book_leftmost'></button><button class='BRicon book_left'></button><button class='BRicon book_right'></button><button class='BRicon book_rightmost'></button></div>"
3184 // + "<div class='BRtoolbarmode1' style='display: none'><button class='BRicon book_top'></button><button class='BRicon book_up'></button> <button class='BRicon book_down'></button><button class='BRicon book_bottom'></button></div>"
3185 // + "<div class='BRtoolbarmode3' style='display: none'><button class='BRicon book_top'></button><button class='BRicon book_up'></button> <button class='BRicon book_down'></button><button class='BRicon book_bottom'></button></div>"
3186 // + "<button class='BRicon play'></button><button class='BRicon pause' style='display: none'></button>"
3190 + "<a class='logo' href='" + this.logoURL + "'></a>"
3191 + "<button class='BRicon glass'></button>"
3192 /* XXXmang integrate search */
3193 + "<form method='get' id='booksearch'><input type='search' id='textSrch' name='textSrch' val='' placeholder='Search'/><button type='submit' id='btnSrch' name='btnSrch'>GO</button></form>"
3194 + "<button class='BRicon fit'></button>"
3195 + "<button class='BRicon thumb' onclick='br.switchMode(3); return false;'></button>"
3196 + "<button class='BRicon twopg' onclick='br.switchMode(2); return false;'></button>"
3201 this.updateToolbarZoom(this.reduce); // Pretty format
3203 if (ui == "embed" || ui == "touch") {
3204 $("#BookReader a.logo").attr("target","_blank");
3207 // $$$ turn this into a member variable
3208 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3210 // We build in mode 2
3213 this.bindToolbarNavHandlers(jToolbar);
3215 // Setup tooltips -- later we could load these from a file for i18n
3216 var titles = { '.logo': 'Go to Archive.org',
3217 '.zoom_in': 'Zoom in',
3218 '.zoom_out': 'Zoom out',
3219 '.onepg': 'One-page view',
3220 '.twopg': 'Two-page view',
3221 '.thumb': 'Thumbnail view',
3222 '.print': 'Print this page',
3223 '.embed': 'Embed BookReader',
3224 '.link': 'Link to this book (and page)',
3225 '.bookmark': 'Bookmark this page',
3226 '.read': 'Allow BookReader to read this aloud',
3227 '.full': 'Show fullscreen',
3228 '.book_left': 'Flip left',
3229 '.book_right': 'Flip right',
3230 '.book_up': 'Page up',
3231 '.book_down': 'Page down',
3234 '.book_top': 'First page',
3235 '.book_bottom': 'Last page'
3237 if ('rl' == this.pageProgression) {
3238 titles['.book_leftmost'] = 'Last page';
3239 titles['.book_rightmost'] = 'First page';
3241 titles['.book_leftmost'] = 'First page';
3242 titles['.book_rightmost'] = 'Last page';
3245 for (var icon in titles) {
3246 jToolbar.find(icon).attr('title', titles[icon]);
3249 // Hide mode buttons and autoplay if 2up is not available
3250 // $$$ if we end up with more than two modes we should show the applicable buttons
3251 if ( !this.canSwitchToMode(this.constMode2up) ) {
3252 jToolbar.find('.two_page_mode, .play, .pause').hide();
3254 if ( !this.canSwitchToMode(this.constModeThumb) ) {
3255 jToolbar.find('.thumbnail_mode').hide();
3258 // Hide one page button if it is the only mode available
3259 if ( ! (this.canSwitchToMode(this.constMode2up) || this.canSwitchToMode(this.constModeThumb)) ) {
3260 jToolbar.find('.one_page_mode').hide();
3263 // Switch to requested mode -- binds other click handlers
3264 //this.switchToolbarMode(mode);
3269 // switchToolbarMode
3270 //______________________________________________________________________________
3271 // Update the toolbar for the given mode (changes navigation buttons)
3272 // $$$ we should soon split the toolbar out into its own module
3273 BookReader.prototype.switchToolbarMode = function(mode) {
3276 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3277 $('#BRtoolbar .BRtoolbarmode2').hide();
3278 $('#BRtoolbar .BRtoolbarmode3').hide();
3279 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3280 } else if (2 == mode) {
3282 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3283 $('#BRtoolbar .BRtoolbarmode1').hide();
3284 $('#BRtoolbar .BRtoolbarmode3').hide();
3285 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3288 $('#BRtoolbar .BRtoolbarzoom').hide();
3289 $('#BRtoolbar .BRtoolbarmode2').hide();
3290 $('#BRtoolbar .BRtoolbarmode1').hide();
3291 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3295 // bindToolbarNavHandlers
3296 //______________________________________________________________________________
3297 // Binds the toolbar handlers
3298 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3300 var self = this; // closure
3302 jToolbar.find('.book_left').click(function(e) {
3307 jToolbar.find('.book_right').click(function(e) {
3312 jToolbar.find('.book_up').bind('click', function(e) {
3313 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3321 jToolbar.find('.book_down').bind('click', function(e) {
3322 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3330 jToolbar.find('.print').click(function(e) {
3335 jToolbar.find('.embed').click(function(e) {
3336 self.showEmbedCode();
3340 jToolbar.find('.bookmark').click(function(e) {
3341 self.showBookmarkCode();
3345 jToolbar.find('.play').click(function(e) {
3350 jToolbar.find('.pause').click(function(e) {
3355 jToolbar.find('.book_top').click(function(e) {
3360 jToolbar.find('.book_bottom').click(function(e) {
3365 jToolbar.find('.book_leftmost').click(function(e) {
3370 jToolbar.find('.book_rightmost').click(function(e) {
3376 // updateToolbarZoom(reduce)
3377 //______________________________________________________________________________
3378 // Update the displayed zoom factor based on reduction factor
3379 BookReader.prototype.updateToolbarZoom = function(reduce) {
3383 // $$$ TODO preserve zoom/fit for each mode
3384 if (this.mode == this.constMode2up) {
3385 autofit = this.twoPage.autofit;
3387 autofit = this.onePage.autofit;
3391 value = autofit.slice(0,1).toUpperCase() + autofit.slice(1);
3393 value = (100 / reduce).toFixed(2);
3394 // Strip trailing zeroes and decimal if all zeroes
3395 value = value.replace(/0+$/,'');
3396 value = value.replace(/\.$/,'');
3399 $('#BRzoom').text(value);
3402 // firstDisplayableIndex
3403 //______________________________________________________________________________
3404 // Returns the index of the first visible page, dependent on the mode.
3405 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3406 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3407 BookReader.prototype.firstDisplayableIndex = function() {
3408 if (this.mode != this.constMode2up) {
3412 if ('rl' != this.pageProgression) {
3414 if (this.getPageSide(0) == 'L') {
3421 if (this.getPageSide(0) == 'R') {
3429 // lastDisplayableIndex
3430 //______________________________________________________________________________
3431 // Returns the index of the last visible page, dependent on the mode.
3432 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3433 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3434 BookReader.prototype.lastDisplayableIndex = function() {
3436 var lastIndex = this.numLeafs - 1;
3438 if (this.mode != this.constMode2up) {
3442 if ('rl' != this.pageProgression) {
3444 if (this.getPageSide(lastIndex) == 'R') {
3447 return lastIndex + 1;
3451 if (this.getPageSide(lastIndex) == 'L') {
3454 return lastIndex + 1;
3459 // shortTitle(maximumCharacters)
3461 // Returns a shortened version of the title with the maximum number of characters
3462 BookReader.prototype.shortTitle = function(maximumCharacters) {
3463 if (this.bookTitle.length < maximumCharacters) {
3464 return this.bookTitle;
3467 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3472 // Parameter related functions
3474 // updateFromParams(params)
3476 // Update ourselves from the params object.
3478 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3479 BookReader.prototype.updateFromParams = function(params) {
3480 if ('undefined' != typeof(params.mode)) {
3481 this.switchMode(params.mode);
3485 if ('undefined' != typeof(params.searchTerm)) {
3486 if (this.searchTerm != params.searchTerm) {
3487 this.search(params.searchTerm);
3491 // $$$ process /zoom
3493 // We only respect page if index is not set
3494 if ('undefined' != typeof(params.index)) {
3495 if (params.index != this.currentIndex()) {
3496 this.jumpToIndex(params.index);
3498 } else if ('undefined' != typeof(params.page)) {
3499 // $$$ this assumes page numbers are unique
3500 if (params.page != this.getPageNum(this.currentIndex())) {
3501 this.jumpToPage(params.page);
3505 // $$$ process /region
3506 // $$$ process /highlight
3509 // paramsFromFragment(urlFragment)
3511 // Returns a object with configuration parametes from a URL fragment.
3513 // E.g paramsFromFragment(window.location.hash)
3514 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3515 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3519 // For convenience we allow an initial # character (as from window.location.hash)
3520 // but don't require it
3521 if (urlFragment.substr(0,1) == '#') {
3522 urlFragment = urlFragment.substr(1);
3525 // Simple #nn syntax
3526 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3527 if ( !isNaN(oldStyleLeafNum) ) {
3528 params.index = oldStyleLeafNum;
3530 // Done processing if using old-style syntax
3534 // Split into key-value pairs
3535 var urlArray = urlFragment.split('/');
3537 for (var i = 0; i < urlArray.length; i += 2) {
3538 urlHash[urlArray[i]] = urlArray[i+1];
3542 if ('1up' == urlHash['mode']) {
3543 params.mode = this.constMode1up;
3544 } else if ('2up' == urlHash['mode']) {
3545 params.mode = this.constMode2up;
3546 } else if ('thumb' == urlHash['mode']) {
3547 params.mode = this.constModeThumb;
3551 if ('undefined' != typeof(urlHash['page'])) {
3552 // page was set -- may not be int
3553 params.page = urlHash['page'];
3556 // $$$ process /region
3557 // $$$ process /search
3559 if (urlHash['search'] != undefined) {
3560 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3563 // $$$ process /highlight
3568 // paramsFromCurrent()
3570 // Create a params object from the current parameters.
3571 BookReader.prototype.paramsFromCurrent = function() {
3575 var index = this.currentIndex();
3576 var pageNum = this.getPageNum(index);
3577 if ((pageNum === 0) || pageNum) {
3578 params.page = pageNum;
3581 params.index = index;
3582 params.mode = this.mode;
3588 if (this.searchHighlightVisible()) {
3589 params.searchTerm = this.searchTerm;
3595 // fragmentFromParams(params)
3597 // Create a fragment string from the params object.
3598 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3599 BookReader.prototype.fragmentFromParams = function(params) {
3600 var separator = '/';
3604 if ('undefined' != typeof(params.page)) {
3605 fragments.push('page', params.page);
3607 // Don't have page numbering -- use index instead
3608 fragments.push('page', 'n' + params.index);
3615 if ('undefined' != typeof(params.mode)) {
3616 if (params.mode == this.constMode1up) {
3617 fragments.push('mode', '1up');
3618 } else if (params.mode == this.constMode2up) {
3619 fragments.push('mode', '2up');
3620 } else if (params.mode == this.constModeThumb) {
3621 fragments.push('mode', 'thumb');
3623 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3628 if (params.searchTerm) {
3629 fragments.push('search', params.searchTerm);
3632 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3635 // getPageIndex(pageNum)
3637 // Returns the *highest* index the given page number, or undefined
3638 BookReader.prototype.getPageIndex = function(pageNum) {
3639 var pageIndices = this.getPageIndices(pageNum);
3641 if (pageIndices.length > 0) {
3642 return pageIndices[pageIndices.length - 1];
3648 // getPageIndices(pageNum)
3650 // Returns an array (possibly empty) of the indices with the given page number
3651 BookReader.prototype.getPageIndices = function(pageNum) {
3654 // Check for special "nXX" page number
3655 if (pageNum.slice(0,1) == 'n') {
3657 var pageIntStr = pageNum.slice(1, pageNum.length);
3658 var pageIndex = parseInt(pageIntStr);
3659 indices.push(pageIndex);
3662 // Do nothing... will run through page names and see if one matches
3667 for (i=0; i<this.numLeafs; i++) {
3668 if (this.getPageNum(i) == pageNum) {
3676 // getPageName(index)
3678 // Returns the name of the page as it should be displayed in the user interface
3679 BookReader.prototype.getPageName = function(index) {
3680 return 'Page ' + this.getPageNum(index);
3683 // updateLocationHash
3685 // Update the location hash from the current parameters. Call this instead of manually
3686 // using window.location.replace
3687 BookReader.prototype.updateLocationHash = function() {
3688 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3689 window.location.replace(newHash);
3691 // This is the variable checked in the timer. Only user-generated changes
3692 // to the URL will trigger the event.
3693 this.oldLocationHash = newHash;
3696 // startLocationPolling
3698 // Starts polling of window.location to see hash fragment changes
3699 BookReader.prototype.startLocationPolling = function() {
3700 var self = this; // remember who I am
3701 self.oldLocationHash = window.location.hash;
3703 if (this.locationPollId) {
3704 clearInterval(this.locationPollID);
3705 this.locationPollId = null;
3708 this.locationPollId = setInterval(function() {
3709 var newHash = window.location.hash;
3710 if (newHash != self.oldLocationHash) {
3711 if (newHash != self.oldUserHash) { // Only process new user hash once
3712 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3714 // Queue change if animating
3715 if (self.animating) {
3717 self.animationFinishedCallback = function() {
3718 self.updateFromParams(self.paramsFromFragment(newHash));
3720 } else { // update immediately
3721 self.updateFromParams(self.paramsFromFragment(newHash));
3723 self.oldUserHash = newHash;
3731 // Returns true if we can switch to the requested mode
3732 BookReader.prototype.canSwitchToMode = function(mode) {
3733 if (mode == this.constMode2up || mode == this.constModeThumb) {
3734 // check there are enough pages to display
3735 // $$$ this is a workaround for the mis-feature that we can't display
3736 // short books in 2up mode
3737 if (this.numLeafs < 2) {
3745 // searchHighlightVisible
3747 // Returns true if a search highlight is currently being displayed
3748 BookReader.prototype.searchHighlightVisible = function() {
3749 if (this.constMode2up == this.mode) {
3750 if (this.searchResults[this.twoPage.currentIndexL]
3751 || this.searchResults[this.twoPage.currentIndexR]) {
3755 if (this.searchResults[this.currentIndex()]) {
3764 // Returns the page width for the given index, or first or last page if out of range
3765 BookReader.prototype._getPageWidth = function(index) {
3766 // Synthesize a page width for pages not actually present in book.
3767 // May or may not be the best approach.
3768 // If index is out of range we return the width of first or last page
3769 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3770 return this.getPageWidth(index);
3775 // Returns the page height for the given index, or first or last page if out of range
3776 BookReader.prototype._getPageHeight= function(index) {
3777 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3778 return this.getPageHeight(index);
3783 // Returns the page URI or transparent image if out of range
3784 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3785 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3786 return this.imagesBaseURL + "/transparent.png";
3789 if ('undefined' == typeof(reduce)) {
3790 // reduce not passed in
3791 // $$$ this probably won't work for thumbnail mode
3792 var ratio = this.getPageHeight(index) / this.twoPage.height;
3794 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3797 } else if (ratio < 4) {
3799 } else if (ratio < 8) {
3801 } else if (ratio < 16) {
3803 } else if (ratio < 32) {
3811 return this.getPageURI(index, reduce, rotate);
3814 // Library functions
3816 disableSelect: function(jObject) {
3817 // Bind mouse handlers
3818 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3819 jObject.bind('mousedown', function(e) {
3820 // $$$ check here for right-click and don't disable. Also use jQuery style
3821 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3824 // Special hack for IE7
3825 jObject[0].onselectstart = function(e) { return false; };
3828 clamp: function(value, min, max) {
3829 return Math.min(Math.max(value, min), max);
3832 notInArray: function(value, array) {
3833 // inArray returns -1 or undefined if value not in array
3834 return ! (jQuery.inArray(value, array) >= 0);
3837 getIFrameDocument: function(iframe) {
3838 // Adapted from http://xkr.us/articles/dom/iframe-document/
3839 var outer = (iframe.contentWindow || iframe.contentDocument);
3840 return (outer.document || outer);
3843 decodeURIComponentPlus: function(value) {
3844 // Decodes a URI component and converts '+' to ' '
3845 return decodeURIComponent(value).replace(/\+/g, ' ');
3848 encodeURIComponentPlus: function(value) {
3849 // Encodes a URI component and converts ' ' to '+'
3850 return encodeURIComponent(value).replace(/%20/g, '+');
3852 // The final property here must NOT have a comma after it - IE7