2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
6 BookReader is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 BookReader is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
45 this.thumbWidth = 100; // will be overridden during prepareThumbnailView
46 this.thumbRowBuffer = 2; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.thumbMaxLoading = 4; // number of thumbnails to load at once
49 this.displayedRows=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 // $$$ provide finer grained zooming
87 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
89 // Object to hold parameters related to 2up mode
91 coverInternalPadding: 10, // Width of cover
92 coverExternalPadding: 10, // Padding outside of cover
93 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
97 // Background color for pages (e.g. when loading page image)
98 // $$$ TODO dynamically calculate based on page images
99 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
105 //______________________________________________________________________________
106 BookReader.prototype.init = function() {
108 var startIndex = undefined;
109 this.pageScale = this.reduce; // preserve current reduce
111 // Find start index and mode if set in location hash
112 var params = this.paramsFromFragment(window.location.hash);
114 if ('undefined' != typeof(params.index)) {
115 startIndex = params.index;
116 } else if ('undefined' != typeof(params.page)) {
117 startIndex = this.getPageIndex(params.page);
120 if ('undefined' == typeof(startIndex)) {
121 if ('undefined' != typeof(this.titleLeaf)) {
122 startIndex = this.leafNumToIndex(this.titleLeaf);
126 if ('undefined' == typeof(startIndex)) {
130 if ('undefined' != typeof(params.mode)) {
131 this.mode = params.mode;
134 // Set document title -- may have already been set in enclosing html for
135 // search engine visibility
136 document.title = this.shortTitle(50);
138 // Sanitize parameters
139 if ( !this.canSwitchToMode( this.mode ) ) {
140 this.mode = this.constMode1up;
143 $("#BookReader").empty();
145 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
146 $("#BookReader").append("<div id='BRcontainer'></div>");
147 $("#BRcontainer").append("<div id='BRpageview'></div>");
149 $("#BRcontainer").bind('scroll', this, function(e) {
153 this.setupKeyListeners();
154 this.startLocationPolling();
156 $(window).bind('resize', this, function(e) {
157 //console.log('resize!');
158 if (1 == e.data.mode) {
159 //console.log('centering 1page view');
160 e.data.centerPageView();
161 $('#BRpageview').empty()
162 e.data.displayedIndices = [];
163 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
165 } else if (3 == e.data.mode){
166 e.data.prepareThumbnailView();
168 //console.log('drawing 2 page view');
170 // We only need to prepare again in autofit (size of spread changes)
171 if (e.data.twoPage.autofit) {
172 e.data.prepareTwoPageView();
174 // Re-center if the scrollbars have disappeared
175 var center = e.data.twoPageGetViewCenter();
176 var doRecenter = false;
177 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
178 center.percentageX = 0.5;
181 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
182 center.percentageY = 0.5;
186 e.data.twoPageCenterView(center.percentageX, center.percentageY);
192 $('.BRpagediv1up').bind('mousedown', this, function(e) {
193 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
194 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
198 // $$$ refactor this so it's enough to set the first index and call preparePageView
199 // (get rid of mode-specific logic at this point)
200 if (1 == this.mode) {
201 this.firstIndex = startIndex;
202 this.prepareOnePageView();
203 this.jumpToIndex(startIndex);
204 } else if (3 == this.mode) {
205 this.firstIndex = startIndex;
206 this.prepareThumbnailView();
207 this.jumpToIndex(startIndex);
209 //this.resizePageView();
211 this.displayedIndices=[0];
212 this.firstIndex = startIndex;
213 this.displayedIndices = [this.firstIndex];
214 //console.log('titleLeaf: %d', this.titleLeaf);
215 //console.log('displayedIndices: %s', this.displayedIndices);
216 this.prepareTwoPageView();
219 // Enact other parts of initial params
220 this.updateFromParams(params);
223 BookReader.prototype.setupKeyListeners = function() {
236 // We use document here instead of window to avoid a bug in jQuery on IE7
237 $(document).keydown(function(e) {
239 // Keyboard navigation
240 if (!self.keyboardNavigationIsDisabled(e)) {
244 // In 1up mode page scrolling is handled by browser
245 if (2 == self.mode) {
252 if (2 == self.mode) {
266 if (2 == self.mode) {
272 if (2 == self.mode) {
283 //______________________________________________________________________________
284 BookReader.prototype.drawLeafs = function() {
285 if (1 == this.mode) {
286 this.drawLeafsOnePage();
287 } else if (3 == this.mode) {
288 this.drawLeafsThumbnail();
290 this.drawLeafsTwoPage();
295 // bindGestures(jElement)
296 //______________________________________________________________________________
297 BookReader.prototype.bindGestures = function(jElement) {
299 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
301 if (e.originalEvent.scale > 1.5) {
303 } else if (e.originalEvent.scale < 0.6) {
310 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
311 //console.log('setting handler');
312 //console.log(element.tagName);
314 $(element).unbind('tap').bind('tap', data, function(e) {
319 // drawLeafsOnePage()
320 //______________________________________________________________________________
321 BookReader.prototype.drawLeafsOnePage = function() {
322 //alert('drawing leafs!');
326 var scrollTop = $('#BRcontainer').attr('scrollTop');
327 var scrollBottom = scrollTop + $('#BRcontainer').height();
328 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
330 var indicesToDisplay = [];
335 for (i=0; i<this.numLeafs; i++) {
336 var height = parseInt(this._getPageHeight(i)/this.reduce);
338 leafBottom += height;
339 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
340 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
341 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
342 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
343 if (topInView | bottomInView | middleInView) {
344 //console.log('displayed: ' + this.displayedIndices);
345 //console.log('to display: ' + i);
346 indicesToDisplay.push(i);
348 leafTop += height +10;
352 var firstIndexToDraw = indicesToDisplay[0];
353 this.firstIndex = firstIndexToDraw;
355 // Update hash, but only if we're currently displaying a leaf
356 // Hack that fixes #365790
357 if (this.displayedIndices.length > 0) {
358 this.updateLocationHash();
361 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
363 indicesToDisplay.unshift(firstIndexToDraw);
366 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
367 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
368 indicesToDisplay.push(lastIndexToDraw+1);
373 for (i=0; i<firstIndexToDraw; i++) {
374 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
377 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
378 var viewWidth = $('#BRcontainer').attr('scrollWidth');
381 for (i=0; i<indicesToDisplay.length; i++) {
382 var index = indicesToDisplay[i];
383 var height = parseInt(this._getPageHeight(index)/this.reduce);
385 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
386 var width = parseInt(this._getPageWidth(index)/this.reduce);
387 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
388 var div = document.createElement("div");
389 div.className = 'BRpagediv1up';
390 div.id = 'pagediv'+index;
391 div.style.position = "absolute";
392 $(div).css('top', leafTop + 'px');
393 var left = (viewWidth-width)>>1;
394 if (left<0) left = 0;
395 $(div).css('left', left+'px');
396 $(div).css('width', width+'px');
397 $(div).css('height', height+'px');
398 //$(div).text('loading...');
400 $('#BRpageview').append(div);
402 var img = document.createElement("img");
403 img.src = this._getPageURI(index, this.reduce, 0);
404 $(img).css('width', width+'px');
405 $(img).css('height', height+'px');
409 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
412 leafTop += height +10;
416 for (i=0; i<this.displayedIndices.length; i++) {
417 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
418 var index = this.displayedIndices[i];
419 //console.log('Removing leaf ' + index);
420 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
421 $('#pagediv'+index).remove();
423 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
427 this.displayedIndices = indicesToDisplay.slice();
428 this.updateSearchHilites();
430 if (null != this.getPageNum(firstIndexToDraw)) {
431 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
433 $("#BRpagenum").val('');
436 this.updateToolbarZoom(this.reduce);
440 // drawLeafsThumbnail()
441 //______________________________________________________________________________
442 // If seekIndex is defined, the view will be drawn with that page visible (without any
443 // animated scrolling)
444 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
445 //alert('drawing leafs!');
448 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
450 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
464 // Will be set to top of requested seek index, if set
467 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
468 for (i=0; i<this.numLeafs; i++) {
469 leafWidth = this.thumbWidth;
470 if (rightPos + (leafWidth + this.padding) > viewWidth){
476 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
477 if (leafMap[currentRow].leafs===undefined) {
478 leafMap[currentRow].leafs = [];
479 leafMap[currentRow].height = 0;
480 leafMap[currentRow].top = 0;
482 leafMap[currentRow].leafs[leafIndex] = {};
483 leafMap[currentRow].leafs[leafIndex].num = i;
484 leafMap[currentRow].leafs[leafIndex].left = rightPos;
486 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
487 if (leafHeight > leafMap[currentRow].height) {
488 leafMap[currentRow].height = leafHeight;
490 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
491 rightPos += leafWidth + this.padding;
492 if (rightPos > maxRight) { maxRight = rightPos; }
495 if (i == seekIndex) {
496 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
500 // reset the bottom position based on thumbnails
501 $('#BRpageview').height(bottomPos);
503 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
505 // If seekTop is defined, seeking was requested and target found
506 if (typeof(seekTop) != 'undefined') {
507 $('#BRcontainer').scrollTop( seekTop );
510 var scrollTop = $('#BRcontainer').attr('scrollTop');
511 var scrollBottom = scrollTop + $('#BRcontainer').height();
515 var rowsToDisplay = [];
517 // Visible leafs with least/greatest index
518 var leastVisible = this.numLeafs - 1;
521 // Determine the thumbnails in view
522 for (i=0; i<leafMap.length; i++) {
523 leafBottom += this.padding + leafMap[i].height;
524 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
525 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
526 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
527 if (topInView | bottomInView | middleInView) {
528 //console.log('row to display: ' + j);
529 rowsToDisplay.push(i);
530 if (leafMap[i].leafs[0].num < leastVisible) {
531 leastVisible = leafMap[i].leafs[0].num;
533 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
534 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
537 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
538 leafTop = leafBottom;
541 // create a buffer of preloaded rows before and after the visible rows
542 var firstRow = rowsToDisplay[0];
543 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
544 for (i=1; i<this.thumbRowBuffer+1; i++) {
545 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
547 for (i=1; i<this.thumbRowBuffer+1; i++) {
548 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
551 // Create the thumbnail divs and images (lazy loaded)
560 for (i=0; i<rowsToDisplay.length; i++) {
561 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
562 row = rowsToDisplay[i];
564 for (j=0; j<leafMap[row].leafs.length; j++) {
566 leaf = leafMap[row].leafs[j].num;
568 leafWidth = this.thumbWidth;
569 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
570 leafTop = leafMap[row].top;
571 left = leafMap[row].leafs[index].left + pageViewBuffer;
572 if ('rl' == this.pageProgression){
573 left = viewWidth - leafWidth - left;
576 div = document.createElement("div");
577 div.id = 'pagediv'+leaf;
578 div.style.position = "absolute";
579 div.className = "BRpagedivthumb";
581 left += this.padding;
582 $(div).css('top', leafTop + 'px');
583 $(div).css('left', left+'px');
584 $(div).css('width', leafWidth+'px');
585 $(div).css('height', leafHeight+'px');
586 //$(div).text('loading...');
588 // link to page in single page mode
589 link = document.createElement("a");
590 $(link).data('leaf', leaf);
591 $(link).bind('tap', function(event) {
592 self.firstIndex = $(this).data('leaf');
593 self.switchMode(self.constMode1up);
594 event.preventDefault();
597 // $$$ we don't actually go to this URL (click is handled in handler above)
598 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
601 $('#BRpageview').append(div);
603 img = document.createElement("img");
604 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
606 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
607 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
608 .addClass('BRlazyload')
609 // Store the URL of the image that will replace this one
610 .data('srcURL', this._getPageURI(leaf, thumbReduce));
612 //console.log('displaying thumbnail: ' + leaf);
617 // Remove thumbnails that are not to be displayed
619 for (i=0; i<this.displayedRows.length; i++) {
620 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
621 row = this.displayedRows[i];
623 // $$$ Safari doesn't like the comprehension
624 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
625 //console.log('Removing row ' + row + ' ' + rowLeafs);
627 for (k=0; k<leafMap[row].leafs.length; k++) {
628 index = leafMap[row].leafs[k].num;
629 //console.log('Removing leaf ' + index);
630 $('#pagediv'+index).remove();
634 var mRow = this.displayedRows[i];
635 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
636 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
641 // Update which page is considered current to make sure a visible page is the current one
642 var currentIndex = this.currentIndex();
643 // console.log('current ' + currentIndex);
644 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
645 if (currentIndex < leastVisible) {
646 this.setCurrentIndex(leastVisible);
647 } else if (currentIndex > mostVisible) {
648 this.setCurrentIndex(mostVisible);
651 this.displayedRows = rowsToDisplay.slice();
653 // Update hash, but only if we're currently displaying a leaf
654 // Hack that fixes #365790
655 if (this.displayedRows.length > 0) {
656 this.updateLocationHash();
659 // remove previous highlights
660 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
662 // highlight current page
663 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
665 this.lazyLoadThumbnails();
667 // Update page number box. $$$ refactor to function
668 if (null !== this.getPageNum(this.currentIndex())) {
669 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
671 $("#BRpagenum").val('');
674 this.updateToolbarZoom(this.reduce);
677 BookReader.prototype.lazyLoadThumbnails = function() {
679 // console.log('lazy load');
681 // We check the complete property since load may not be fired if loading from the cache
682 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
684 var loading = $('.BRlazyloading').length;
685 var toLoad = this.thumbMaxLoading - loading;
687 // console.log(' ' + loading + ' thumbnails loading');
688 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
693 // $$$ TODO load those near top (but not beyond) page view first
694 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
695 self.lazyLoadImage(this);
700 BookReader.prototype.lazyLoadImage = function (dummyImage) {
701 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
703 var img = new Image();
707 .addClass('BRlazyloading')
708 .one('load', function() {
709 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
711 $(this).removeClass('BRlazyloading');
713 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
714 // we call the function after a slight delay. Also the img.complete property
715 // is not yet set in IE8 inside this onload handler
716 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
718 .one('error', function() {
719 // Remove class so we no longer count as loading
720 $(this).removeClass('BRlazyloading');
722 .attr( { width: $(dummyImage).width(),
723 height: $(dummyImage).height(),
724 src: $(dummyImage).data('srcURL')
727 // replace with the new img
728 $(dummyImage).before(img).remove();
730 img = null; // tidy up closure
734 // drawLeafsTwoPage()
735 //______________________________________________________________________________
736 BookReader.prototype.drawLeafsTwoPage = function() {
737 var scrollTop = $('#BRtwopageview').attr('scrollTop');
738 var scrollBottom = scrollTop + $('#BRtwopageview').height();
740 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
742 var indexL = this.twoPage.currentIndexL;
744 var heightL = this._getPageHeight(indexL);
745 var widthL = this._getPageWidth(indexL);
747 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
748 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
749 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
750 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
751 //console.log(leafEdgeWidthL);
753 var middle = this.twoPage.middle; // $$$ getter instead?
754 var top = this.twoPageTop();
755 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
757 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
758 this.twoPage.gutter = this.twoPageGutter();
760 this.prefetchImg(indexL);
761 $(this.prefetchedImgs[indexL]).css({
762 position: 'absolute',
763 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
766 backgroundColor: this.getPageBackgroundColor(indexL),
767 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
768 width: this.twoPage.scaledWL + 'px',
769 borderRight: '1px solid black',
771 }).appendTo('#BRtwopageview');
773 var indexR = this.twoPage.currentIndexR;
774 var heightR = this._getPageHeight(indexR);
775 var widthR = this._getPageWidth(indexR);
777 // $$$ should use getwidth2up?
778 //var scaledWR = this.twoPage.height*widthR/heightR;
779 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
780 this.prefetchImg(indexR);
781 $(this.prefetchedImgs[indexR]).css({
782 position: 'absolute',
783 left: this.twoPage.gutter+'px',
786 backgroundColor: this.getPageBackgroundColor(indexR),
787 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
788 width: this.twoPage.scaledWR + 'px',
789 borderLeft: '1px solid black',
791 }).appendTo('#BRtwopageview');
794 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
795 this.setMouseHandlers2UP();
796 this.twoPageSetCursor();
798 this.updatePageNumBox2UP();
799 this.updateToolbarZoom(this.reduce);
801 // this.twoPagePlaceFlipAreas(); // No longer used
805 // updatePageNumBox2UP
806 //______________________________________________________________________________
807 BookReader.prototype.updatePageNumBox2UP = function() {
808 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
809 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
811 $("#BRpagenum").val('');
813 this.updateLocationHash();
817 //______________________________________________________________________________
818 BookReader.prototype.loadLeafs = function() {
822 if (null == this.timer) {
823 this.timer=setTimeout(function(){self.drawLeafs()},250);
825 clearTimeout(this.timer);
826 this.timer=setTimeout(function(){self.drawLeafs()},250);
832 // Pass 1 to zoom in, anything else to zoom out
833 //______________________________________________________________________________
834 BookReader.prototype.zoom = function(direction) {
836 case this.constMode1up:
837 return this.zoom1up(direction);
838 case this.constMode2up:
839 return this.zoom2up(direction);
840 case this.constModeThumb:
841 return this.zoomThumb(direction);
846 //______________________________________________________________________________
847 BookReader.prototype.zoom1up = function(dir) {
849 if (2 == this.mode) { //can only zoom in 1-page mode
854 // $$$ with flexible zoom we could "snap" to /2 page reductions
855 // for better scaling
857 if (this.reduce <= 0.5) return;
858 this.reduce*=0.5; //zoom in
860 if (this.reduce >= 8) return;
861 this.reduce*=2; //zoom out
864 this.pageScale = this.reduce; // preserve current reduce
865 this.resizePageView();
867 $('#BRpageview').empty()
868 this.displayedIndices = [];
871 this.updateToolbarZoom(this.reduce);
873 // Recalculate search hilites
874 this.removeSearchHilites();
875 this.updateSearchHilites();
880 //______________________________________________________________________________
881 BookReader.prototype.resizePageView = function() {
883 // $$$ This code assumes 1up mode
884 // e.g. does not preserve position in thumbnail mode
885 // See http://bugs.launchpad.net/bookreader/+bug/552972
888 case this.constMode1up:
889 case this.constMode2up:
890 this.resizePageView1up();
892 case this.constModeThumb:
893 this.prepareThumbnailView( this.currentIndex() );
896 alert('Resize not implemented for this mode');
900 BookReader.prototype.resizePageView1up = function() {
903 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
904 var viewWidth = $('#BRcontainer').attr('clientWidth');
906 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
907 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
908 var oldPageViewHeight = $('#BRpageview').height();
909 var oldPageViewWidth = $('#BRpageview').width();
911 var oldCenterY = this.centerY1up();
912 var oldCenterX = this.centerX1up();
914 if (0 != oldPageViewHeight) {
915 var scrollRatio = oldCenterY / oldPageViewHeight;
920 for (i=0; i<this.numLeafs; i++) {
921 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
922 var width = parseInt(this._getPageWidth(i)/this.reduce);
923 if (width>viewWidth) viewWidth=width;
925 $('#BRpageview').height(viewHeight);
926 $('#BRpageview').width(viewWidth);
928 var newCenterY = scrollRatio*viewHeight;
929 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
930 $('#BRcontainer').attr('scrollTop', newTop);
932 // We use clientWidth here to avoid miscalculating due to scroll bar
933 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
934 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
935 newLeft = Math.max(newLeft, 0);
936 $('#BRcontainer').attr('scrollLeft', newLeft);
937 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
939 //this.centerPageView();
942 this.removeSearchHilites();
943 this.updateSearchHilites();
948 //______________________________________________________________________________
949 // Returns the current offset of the viewport center in scaled document coordinates.
950 BookReader.prototype.centerX1up = function() {
952 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
953 centerX = $('#BRpageview').width();
955 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
957 centerX = Math.floor(centerX);
962 //______________________________________________________________________________
963 // Returns the current offset of the viewport center in scaled document coordinates.
964 BookReader.prototype.centerY1up = function() {
965 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
966 return Math.floor(centerY);
970 //______________________________________________________________________________
971 BookReader.prototype.centerPageView = function() {
973 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
974 var clientWidth = $('#BRcontainer').attr('clientWidth');
975 //console.log('sW='+scrollWidth+' cW='+clientWidth);
976 if (scrollWidth > clientWidth) {
977 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
982 // zoom2up(direction)
983 //______________________________________________________________________________
984 BookReader.prototype.zoom2up = function(direction) {
986 // Hard stop autoplay
987 this.stopFlipAnimations();
989 // Get new zoom state
990 var newZoom = this.twoPageNextReduce(this.reduce, direction);
991 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
994 this.twoPage.autofit = newZoom.autofit;
995 this.reduce = newZoom.reduce;
996 this.pageScale = this.reduce; // preserve current reduce
998 // Preserve view center position
999 var oldCenter = this.twoPageGetViewCenter();
1001 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1002 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1003 if (1 == direction) {
1004 for (var img in this.prefetchedImgs) {
1005 delete this.prefetchedImgs[img];
1009 // Prepare view with new center to minimize visual glitches
1010 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1013 BookReader.prototype.zoomThumb = function(direction) {
1014 var oldColumns = this.thumbColumns;
1015 switch (direction) {
1017 this.thumbColumns += 1;
1020 this.thumbColumns -= 1;
1025 if (this.thumbColumns < 2) {
1026 this.thumbColumns = 2;
1027 } else if (this.thumbColumns > 8) {
1028 this.thumbColumns = 8;
1031 if (this.thumbColumns != oldColumns) {
1032 this.prepareThumbnailView();
1036 // Returns the width per thumbnail to display the requested number of columns
1037 // Note: #BRpageview must already exist since its width is used to calculate the
1039 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1040 var padding = (thumbnailColumns + 1) * this.padding;
1041 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1042 return parseInt(width);
1045 // quantizeReduce(reduce)
1046 //______________________________________________________________________________
1047 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1048 BookReader.prototype.quantizeReduce = function(reduce) {
1049 var quantized = this.reductionFactors[0];
1050 var distance = Math.abs(reduce - quantized);
1051 for (var i = 1; i < this.reductionFactors.length; i++) {
1052 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1053 if (newDistance < distance) {
1054 distance = newDistance;
1055 quantized = this.reductionFactors[i];
1062 // twoPageNextReduce()
1063 //______________________________________________________________________________
1064 // Returns the next reduction level
1065 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1067 var autofitReduce = this.twoPageGetAutofitReduce();
1069 if (0 == direction) { // autofit
1070 result.autofit = true;
1071 result.reduce = autofitReduce;
1073 } else if (1 == direction) { // zoom in
1074 var newReduce = this.reductionFactors[0];
1076 for (var i = 1; i < this.reductionFactors.length; i++) {
1077 if (this.reductionFactors[i] < reduce) {
1078 newReduce = this.reductionFactors[i];
1082 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1084 result.autofit = true;
1085 result.reduce = autofitReduce;
1087 result.autofit = false;
1088 result.reduce = newReduce;
1091 } else { // zoom out
1092 var lastIndex = this.reductionFactors.length - 1;
1093 var newReduce = this.reductionFactors[lastIndex];
1095 for (var i = lastIndex; i >= 0; i--) {
1096 if (this.reductionFactors[i] > reduce) {
1097 newReduce = this.reductionFactors[i];
1101 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1103 result.autofit = true;
1104 result.reduce = autofitReduce;
1106 result.autofit = false;
1107 result.reduce = newReduce;
1115 //______________________________________________________________________________
1116 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1117 BookReader.prototype.jumpToPage = function(pageNum) {
1119 var pageIndex = this.getPageIndex(pageNum);
1121 if ('undefined' != typeof(pageIndex)) {
1124 this.jumpToIndex(pageIndex);
1125 $('#BRcontainer').attr('scrollTop', leafTop);
1134 //______________________________________________________________________________
1135 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1137 if (2 == this.mode) {
1140 // By checking against min/max we do nothing if requested index
1142 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1143 this.flipBackToIndex(index);
1144 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1145 this.flipFwdToIndex(index);
1148 } else if (3 == this.mode) {
1149 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1159 for (i=0; i<(index+1); i++) {
1160 leafWidth = this.thumbWidth;
1161 if (rightPos + (leafWidth + this.padding) > viewWidth){
1167 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1168 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1169 if (leafIndex==0) { leafTop = bottomPos; }
1170 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1171 rightPos += leafWidth + this.padding;
1174 this.firstIndex=index;
1175 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1178 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1185 for (i=0; i<index; i++) {
1186 h = parseInt(this._getPageHeight(i)/this.reduce);
1187 leafTop += h + this.padding;
1191 //console.log('pageY ' + pageY);
1192 var offset = parseInt( (pageY) / this.reduce);
1193 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1194 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1199 var offset = parseInt( (pageX) / this.reduce);
1200 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1204 //$('#BRcontainer').attr('scrollTop', leafTop);
1205 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1211 //______________________________________________________________________________
1212 BookReader.prototype.switchMode = function(mode) {
1214 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1216 if (mode == this.mode) {
1220 if (!this.canSwitchToMode(mode)) {
1225 this.removeSearchHilites();
1228 this.switchToolbarMode(mode);
1230 // reinstate scale if moving from thumbnail view
1231 if (this.pageScale != this.reduce) {
1232 this.reduce = this.pageScale;
1235 // $$$ TODO preserve center of view when switching between mode
1236 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1239 this.reduce = this.quantizeReduce(this.reduce);
1240 this.prepareOnePageView();
1241 } else if (3 == mode) {
1242 this.reduce = this.quantizeReduce(this.reduce);
1243 this.prepareThumbnailView();
1245 // $$$ why don't we save autofit?
1246 this.twoPage.autofit = false; // Take zoom level from other mode
1247 this.reduce = this.quantizeReduce(this.reduce);
1248 this.prepareTwoPageView();
1249 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1254 //prepareOnePageView()
1255 //______________________________________________________________________________
1256 BookReader.prototype.prepareOnePageView = function() {
1258 // var startLeaf = this.displayedIndices[0];
1259 var startLeaf = this.currentIndex();
1261 $('#BRcontainer').empty();
1262 $('#BRcontainer').css({
1263 overflowY: 'scroll',
1267 $("#BRcontainer").append("<div id='BRpageview'></div>");
1269 // Attaches to first child - child must be present
1270 $('#BRcontainer').dragscrollable();
1271 this.bindGestures($('#BRcontainer'));
1273 // $$$ keep select enabled for now since disabling it breaks keyboard
1274 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1275 // BookReader.util.disableSelect($('#BRpageview'));
1277 this.resizePageView();
1279 this.jumpToIndex(startLeaf);
1280 this.displayedIndices = [];
1282 this.drawLeafsOnePage();
1285 //prepareThumbnailView()
1286 //______________________________________________________________________________
1287 BookReader.prototype.prepareThumbnailView = function() {
1289 $('#BRcontainer').empty();
1290 $('#BRcontainer').css({
1291 overflowY: 'scroll',
1295 $("#BRcontainer").append("<div id='BRpageview'></div>");
1297 $('#BRcontainer').dragscrollable();
1298 this.bindGestures($('#BRcontainer'));
1300 // $$$ keep select enabled for now since disabling it breaks keyboard
1301 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1302 // BookReader.util.disableSelect($('#BRpageview'));
1304 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1305 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1307 this.displayedRows = [];
1309 // Draw leafs with current index directly in view (no animating to the index)
1310 this.drawLeafsThumbnail( this.currentIndex() );
1314 // prepareTwoPageView()
1315 //______________________________________________________________________________
1316 // Some decisions about two page view:
1318 // Both pages will be displayed at the same height, even if they were different physical/scanned
1319 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1320 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1321 // aspect ratio to determine the height.
1323 // The two page view div is resized to keep the middle of the book in the middle of the div
1324 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1325 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1326 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1327 $('#BRcontainer').empty();
1328 $('#BRcontainer').css('overflow', 'auto');
1330 // We want to display two facing pages. We may be missing
1331 // one side of the spread because it is the first/last leaf,
1332 // foldouts, missing pages, etc
1334 //var targetLeaf = this.displayedIndices[0];
1335 var targetLeaf = this.firstIndex;
1337 if (targetLeaf < this.firstDisplayableIndex()) {
1338 targetLeaf = this.firstDisplayableIndex();
1341 if (targetLeaf > this.lastDisplayableIndex()) {
1342 targetLeaf = this.lastDisplayableIndex();
1345 //this.twoPage.currentIndexL = null;
1346 //this.twoPage.currentIndexR = null;
1347 //this.pruneUnusedImgs();
1349 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1350 this.twoPage.currentIndexL = currentSpreadIndices[0];
1351 this.twoPage.currentIndexR = currentSpreadIndices[1];
1352 this.firstIndex = this.twoPage.currentIndexL;
1354 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1356 this.pruneUnusedImgs();
1357 this.prefetch(); // Preload images or reload if scaling has changed
1359 //console.dir(this.twoPage);
1361 // Add the two page view
1362 // $$$ Can we get everything set up and then append?
1363 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1365 // Attaches to first child, so must come after we add the page view
1366 $('#BRcontainer').dragscrollable();
1367 this.bindGestures($('#BRcontainer'));
1369 // $$$ calculate first then set
1370 $('#BRtwopageview').css( {
1371 height: this.twoPage.totalHeight + 'px',
1372 width: this.twoPage.totalWidth + 'px',
1373 position: 'absolute'
1376 // If there will not be scrollbars (e.g. when zooming out) we center the book
1377 // since otherwise the book will be stuck off-center
1378 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1379 centerPercentageX = 0.5;
1381 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1382 centerPercentageY = 0.5;
1385 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1387 this.twoPage.coverDiv = document.createElement('div');
1388 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1389 width: this.twoPage.bookCoverDivWidth + 'px',
1390 height: this.twoPage.bookCoverDivHeight+'px',
1391 visibility: 'visible',
1392 position: 'absolute',
1393 left: this.twoPage.bookCoverDivLeft + 'px',
1394 top: this.twoPage.bookCoverDivTop+'px',
1395 }).appendTo('#BRtwopageview');
1397 this.leafEdgeR = document.createElement('div');
1398 this.leafEdgeR.className = 'BRleafEdgeR';
1399 $(this.leafEdgeR).css({
1400 width: this.twoPage.leafEdgeWidthR + 'px',
1401 height: this.twoPage.height-1 + 'px',
1402 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1403 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1404 }).appendTo('#BRtwopageview');
1406 this.leafEdgeL = document.createElement('div');
1407 this.leafEdgeL.className = 'BRleafEdgeL';
1408 $(this.leafEdgeL).css({
1409 width: this.twoPage.leafEdgeWidthL + 'px',
1410 height: this.twoPage.height-1 + 'px',
1411 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1412 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1413 }).appendTo('#BRtwopageview');
1415 div = document.createElement('div');
1416 $(div).attr('id', 'BRbookspine').css({
1417 width: this.twoPage.bookSpineDivWidth+'px',
1418 height: this.twoPage.bookSpineDivHeight+'px',
1419 left: this.twoPage.bookSpineDivLeft+'px',
1420 top: this.twoPage.bookSpineDivTop+'px'
1421 }).appendTo('#BRtwopageview');
1423 var self = this; // for closure
1425 /* Flip areas no longer used
1426 this.twoPage.leftFlipArea = document.createElement('div');
1427 this.twoPage.leftFlipArea.className = 'BRfliparea';
1428 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1430 width: this.twoPageFlipAreaWidth() + 'px',
1431 height: this.twoPageFlipAreaHeight() + 'px',
1432 position: 'absolute',
1433 left: this.twoPageLeftFlipAreaLeft() + 'px',
1434 top: this.twoPageFlipAreaTop() + 'px',
1437 }).bind('click', function(e) {
1439 }).bind('mousedown', function(e) {
1441 }).appendTo('#BRtwopageview');
1443 this.twoPage.rightFlipArea = document.createElement('div');
1444 this.twoPage.rightFlipArea.className = 'BRfliparea';
1445 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1447 width: this.twoPageFlipAreaWidth() + 'px',
1448 height: this.twoPageFlipAreaHeight() + 'px',
1449 position: 'absolute',
1450 left: this.twoPageRightFlipAreaLeft() + 'px',
1451 top: this.twoPageFlipAreaTop() + 'px',
1454 }).bind('click', function(e) {
1456 }).bind('mousedown', function(e) {
1458 }).appendTo('#BRtwopageview');
1461 this.prepareTwoPagePopUp();
1463 this.displayedIndices = [];
1465 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1466 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1468 this.drawLeafsTwoPage();
1469 this.updateToolbarZoom(this.reduce);
1473 this.removeSearchHilites();
1474 this.updateSearchHilites();
1478 // prepareTwoPagePopUp()
1480 // This function prepares the "View Page n" popup that shows while the mouse is
1481 // over the left/right "stack of sheets" edges. It also binds the mouse
1482 // events for these divs.
1483 //______________________________________________________________________________
1484 BookReader.prototype.prepareTwoPagePopUp = function() {
1486 this.twoPagePopUp = document.createElement('div');
1487 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1488 $(this.twoPagePopUp).css({
1490 }).appendTo('#BRcontainer');
1491 $(this.twoPagePopUp).hide();
1493 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1494 $(e.data.twoPagePopUp).show();
1497 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1498 $(e.data.twoPagePopUp).hide();
1501 $(this.leafEdgeL).bind('click', this, function(e) {
1503 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1504 e.data.jumpToIndex(jumpIndex);
1507 $(this.leafEdgeR).bind('click', this, function(e) {
1509 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1510 e.data.jumpToIndex(jumpIndex);
1513 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1515 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1516 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1518 // $$$ TODO: Make sure popup is positioned so that it is in view
1519 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1520 $(e.data.twoPagePopUp).css({
1521 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1522 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1526 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1528 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1529 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1531 // $$$ TODO: Make sure popup is positioned so that it is in view
1532 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1533 $(e.data.twoPagePopUp).css({
1534 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1535 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1540 // calculateSpreadSize()
1541 //______________________________________________________________________________
1542 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1543 // this.twoPage.currentIndexR
1544 // This function sets this.twoPage.height, twoPage.width
1546 BookReader.prototype.calculateSpreadSize = function() {
1548 var firstIndex = this.twoPage.currentIndexL;
1549 var secondIndex = this.twoPage.currentIndexR;
1550 //console.log('first page is ' + firstIndex);
1552 // Calculate page sizes and total leaf width
1554 if ( this.twoPage.autofit) {
1555 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1557 // set based on reduction factor
1558 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1561 // Both pages together
1562 this.twoPage.height = spreadSize.height;
1563 this.twoPage.width = spreadSize.width;
1566 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1567 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1570 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1571 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1572 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1576 // The width of the book cover div. The combined width of both pages, twice the width
1577 // of the book cover internal padding (2*10) and the page edges
1578 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1579 // The height of the book cover div
1580 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1583 // We calculate the total width and height for the div so that we can make the book
1585 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1586 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1587 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1588 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1589 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1590 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1592 // We want to minimize the unused space in two-up mode (maximize the amount of page
1593 // shown). We give width to the leaf edges and these widths change (though the sum
1594 // of the two remains constant) as we flip through the book. With the book
1595 // cover centered and fixed in the BRcontainer div the page images will meet
1596 // at the "gutter" which is generally offset from the center.
1597 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1598 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1600 // The left edge of the book cover moves depending on the width of the pages
1601 // $$$ change to getter
1602 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1603 // The top edge of the book cover stays a fixed distance from the top
1604 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1607 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1608 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1609 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1612 this.reduce = spreadSize.reduce; // $$$ really set this here?
1615 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1618 // We check which page is closest to a "normal" page and use that to set the height
1619 // for both pages. This means that foldouts and other odd size pages will be displayed
1620 // smaller than the nominal zoom amount.
1621 var canon5Dratio = 1.5;
1624 height: this._getPageHeight(firstIndex),
1625 width: this._getPageWidth(firstIndex)
1629 height: this._getPageHeight(secondIndex),
1630 width: this._getPageWidth(secondIndex)
1633 var firstIndexRatio = first.height / first.width;
1634 var secondIndexRatio = second.height / second.width;
1635 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1638 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1639 ratio = firstIndexRatio;
1640 //console.log('using firstIndexRatio ' + ratio);
1642 ratio = secondIndexRatio;
1643 //console.log('using secondIndexRatio ' + ratio);
1646 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1647 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1648 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1650 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1651 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1653 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1654 ideal.width -= 10; // $$$ fudge factor
1655 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1656 ideal.height -= 20; // fudge factor
1657 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1659 if (ideal.height/ratio <= ideal.width) {
1661 ideal.width = parseInt(ideal.height/ratio);
1664 ideal.height = parseInt(ideal.width*ratio);
1667 // $$$ check this logic with large spreads
1668 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1673 // getSpreadSizeFromReduce()
1674 //______________________________________________________________________________
1675 // Returns the spread size calculated from the reduction factor for the given pages
1676 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1677 var spreadSize = {};
1678 // $$$ Scale this based on reduce?
1679 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1680 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1681 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1683 // $$$ Possibly incorrect -- we should make height "dominant"
1684 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1685 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1686 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1687 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1688 spreadSize.reduce = reduce;
1693 // twoPageGetAutofitReduce()
1694 //______________________________________________________________________________
1695 // Returns the current ideal reduction factor
1696 BookReader.prototype.twoPageGetAutofitReduce = function() {
1697 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1698 return spreadSize.reduce;
1701 // twoPageSetCursor()
1702 //______________________________________________________________________________
1703 // Set the cursor for two page view
1704 BookReader.prototype.twoPageSetCursor = function() {
1705 // console.log('setting cursor');
1706 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1707 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1708 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1709 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1711 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1712 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1717 //______________________________________________________________________________
1718 // Returns the currently active index.
1719 BookReader.prototype.currentIndex = function() {
1720 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1721 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1722 return this.firstIndex; // $$$ TODO page in center of view would be better
1723 } else if (this.mode == this.constMode2up) {
1724 // Only allow indices that are actually present in book
1725 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1727 throw 'currentIndex called for unimplemented mode ' + this.mode;
1731 // setCurrentIndex(index)
1732 //______________________________________________________________________________
1733 // Sets the idea of current index without triggering other actions such as animation.
1734 // Compare to jumpToIndex which animates to that index
1735 BookReader.prototype.setCurrentIndex = function(index) {
1736 this.firstIndex = index;
1741 //______________________________________________________________________________
1742 // Flip the right page over onto the left
1743 BookReader.prototype.right = function() {
1744 if ('rl' != this.pageProgression) {
1754 //______________________________________________________________________________
1755 // Flip to the rightmost page
1756 BookReader.prototype.rightmost = function() {
1757 if ('rl' != this.pageProgression) {
1765 //______________________________________________________________________________
1766 // Flip the left page over onto the right.
1767 BookReader.prototype.left = function() {
1768 if ('rl' != this.pageProgression) {
1778 //______________________________________________________________________________
1779 // Flip to the leftmost page
1780 BookReader.prototype.leftmost = function() {
1781 if ('rl' != this.pageProgression) {
1789 //______________________________________________________________________________
1790 BookReader.prototype.next = function() {
1791 if (2 == this.mode) {
1793 this.flipFwdToIndex(null);
1795 if (this.firstIndex < this.lastDisplayableIndex()) {
1796 this.jumpToIndex(this.firstIndex+1);
1802 //______________________________________________________________________________
1803 BookReader.prototype.prev = function() {
1804 if (2 == this.mode) {
1806 this.flipBackToIndex(null);
1808 if (this.firstIndex >= 1) {
1809 this.jumpToIndex(this.firstIndex-1);
1814 BookReader.prototype.first = function() {
1815 this.jumpToIndex(this.firstDisplayableIndex());
1818 BookReader.prototype.last = function() {
1819 this.jumpToIndex(this.lastDisplayableIndex());
1823 //______________________________________________________________________________
1824 // Scrolls down one screen view
1825 BookReader.prototype.scrollDown = function() {
1826 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1827 $('#BRcontainer').animate(
1828 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1829 450, 'easeInOutQuint'
1838 //______________________________________________________________________________
1839 // Scrolls up one screen view
1840 BookReader.prototype.scrollUp = function() {
1841 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1842 $('#BRcontainer').animate(
1843 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1844 450, 'easeInOutQuint'
1853 // flipBackToIndex()
1854 //______________________________________________________________________________
1855 // to flip back one spread, pass index=null
1856 BookReader.prototype.flipBackToIndex = function(index) {
1858 if (1 == this.mode) return;
1860 var leftIndex = this.twoPage.currentIndexL;
1862 if (this.animating) return;
1864 if (null != this.leafEdgeTmp) {
1865 alert('error: leafEdgeTmp should be null!');
1869 if (null == index) {
1870 index = leftIndex-2;
1872 //if (index<0) return;
1874 var previousIndices = this.getSpreadIndices(index);
1876 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1880 this.animating = true;
1882 if ('rl' != this.pageProgression) {
1883 // Assume LTR and we are going backward
1884 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1885 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1887 // RTL and going backward
1888 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1889 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1893 // flipLeftToRight()
1894 //______________________________________________________________________________
1895 // Flips the page on the left towards the page on the right
1896 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1898 var leftLeaf = this.twoPage.currentIndexL;
1900 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1901 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1902 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1904 var currWidthL = this.getPageWidth2UP(leftLeaf);
1905 var newWidthL = this.getPageWidth2UP(newIndexL);
1906 var newWidthR = this.getPageWidth2UP(newIndexR);
1908 var top = this.twoPageTop();
1909 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1911 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1912 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1914 //animation strategy:
1915 // 0. remove search highlight, if any.
1916 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1917 // of the left leaf and where the user clicked in the leaf edge.
1918 // Note that if this function was triggered by left() and not a
1919 // mouse click, the width of leafEdgeTmp is very small (zero px).
1920 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1921 // leftLeaf to width=0.
1922 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1923 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1924 // its new full width.
1925 // 4. After step 3 is finished, do the following:
1926 // - remove leafEdgeTmp from the dom.
1927 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1928 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1929 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1930 // and width=newLeafEdgeWidthL.
1931 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1932 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1933 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1934 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1935 // - prefetch new adjacent leafs.
1936 // - set up click handlers for both new left and right leafs.
1937 // - redraw the search highlight.
1938 // - update the pagenum box and the url.
1941 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1943 this.leafEdgeTmp = document.createElement('div');
1944 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
1945 $(this.leafEdgeTmp).css({
1946 width: leafEdgeTmpW + 'px',
1947 height: this.twoPage.height-1 + 'px',
1948 left: leftEdgeTmpLeft + 'px',
1951 }).appendTo('#BRtwopageview');
1953 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1954 $(this.leafEdgeL).css({
1955 width: newLeafEdgeWidthL+'px',
1956 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1959 // Left gets the offset of the current left leaf from the document
1960 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1961 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1962 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1964 // We change the left leaf to right positioning
1965 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1966 $(this.prefetchedImgs[leftLeaf]).css({
1971 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1972 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1976 this.removeSearchHilites();
1978 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1979 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1981 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1982 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1984 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1985 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1986 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1988 $(self.leafEdgeR).css({
1989 // Moves the right leaf edge
1990 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1991 left: gutter+newWidthR+'px'
1994 $(self.leafEdgeL).css({
1995 // Moves and resizes the left leaf edge
1996 width: newLeafEdgeWidthL+'px',
1997 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2000 // Resizes the brown border div
2001 $(self.twoPage.coverDiv).css({
2002 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2003 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2006 $(self.leafEdgeTmp).remove();
2007 self.leafEdgeTmp = null;
2009 // $$$ TODO refactor with opposite direction flip
2011 self.twoPage.currentIndexL = newIndexL;
2012 self.twoPage.currentIndexR = newIndexR;
2013 self.twoPage.scaledWL = newWidthL;
2014 self.twoPage.scaledWR = newWidthR;
2015 self.twoPage.gutter = gutter;
2017 self.firstIndex = self.twoPage.currentIndexL;
2018 self.displayedIndices = [newIndexL, newIndexR];
2019 self.pruneUnusedImgs();
2021 self.animating = false;
2023 self.updateSearchHilites2UP();
2024 self.updatePageNumBox2UP();
2026 // self.twoPagePlaceFlipAreas(); // No longer used
2027 self.setMouseHandlers2UP();
2028 self.twoPageSetCursor();
2030 if (self.animationFinishedCallback) {
2031 self.animationFinishedCallback();
2032 self.animationFinishedCallback = null;
2040 //______________________________________________________________________________
2041 // Whether we flip left or right is dependent on the page progression
2042 // to flip forward one spread, pass index=null
2043 BookReader.prototype.flipFwdToIndex = function(index) {
2045 if (this.animating) return;
2047 if (null != this.leafEdgeTmp) {
2048 alert('error: leafEdgeTmp should be null!');
2052 if (null == index) {
2053 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2055 if (index > this.lastDisplayableIndex()) return;
2057 this.animating = true;
2059 var nextIndices = this.getSpreadIndices(index);
2061 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2063 if ('rl' != this.pageProgression) {
2064 // We did not specify RTL
2065 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2066 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2069 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2070 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2074 // flipRightToLeft(nextL, nextR, gutter)
2075 // $$$ better not to have to pass gutter in
2076 //______________________________________________________________________________
2077 // Flip from left to right and show the nextL and nextR indices on those sides
2078 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2079 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2080 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2081 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2082 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2084 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2086 var top = this.twoPageTop();
2087 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2089 var middle = this.twoPage.middle;
2090 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2092 this.leafEdgeTmp = document.createElement('div');
2093 $(this.leafEdgeTmp).css({
2094 borderStyle: 'solid none solid solid',
2095 borderColor: 'rgb(51, 51, 34)',
2096 borderWidth: '1px 0px 1px 1px',
2097 width: leafEdgeTmpW + 'px',
2098 height: this.twoPage.height-1 + 'px',
2099 left: gutter+scaledW+'px',
2102 }).appendTo('#BRtwopageview');
2104 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2105 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2107 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2108 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2109 var newWidthL = this.getPageWidth2UP(newIndexL);
2110 var newWidthR = this.getPageWidth2UP(newIndexR);
2112 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2114 var self = this; // closure-tastic!
2116 var speed = this.flipSpeed;
2118 this.removeSearchHilites();
2120 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2121 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2122 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2123 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2124 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2126 $(self.leafEdgeL).css({
2127 width: newLeafEdgeWidthL+'px',
2128 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2131 // Resizes the book cover
2132 $(self.twoPage.coverDiv).css({
2133 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2134 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2137 $(self.leafEdgeTmp).remove();
2138 self.leafEdgeTmp = null;
2140 self.twoPage.currentIndexL = newIndexL;
2141 self.twoPage.currentIndexR = newIndexR;
2142 self.twoPage.scaledWL = newWidthL;
2143 self.twoPage.scaledWR = newWidthR;
2144 self.twoPage.gutter = gutter;
2146 self.firstIndex = self.twoPage.currentIndexL;
2147 self.displayedIndices = [newIndexL, newIndexR];
2148 self.pruneUnusedImgs();
2150 self.animating = false;
2153 self.updateSearchHilites2UP();
2154 self.updatePageNumBox2UP();
2156 // self.twoPagePlaceFlipAreas(); // No longer used
2157 self.setMouseHandlers2UP();
2158 self.twoPageSetCursor();
2160 if (self.animationFinishedCallback) {
2161 self.animationFinishedCallback();
2162 self.animationFinishedCallback = null;
2168 // setMouseHandlers2UP
2169 //______________________________________________________________________________
2170 BookReader.prototype.setMouseHandlers2UP = function() {
2171 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2179 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2182 e.data.self.right();
2189 //______________________________________________________________________________
2190 BookReader.prototype.prefetchImg = function(index) {
2191 var pageURI = this._getPageURI(index);
2193 // Load image if not loaded or URI has changed (e.g. due to scaling)
2194 var loadImage = false;
2195 if (undefined == this.prefetchedImgs[index]) {
2196 //console.log('no image for ' + index);
2198 } else if (pageURI != this.prefetchedImgs[index].uri) {
2199 //console.log('uri changed for ' + index);
2204 //console.log('prefetching ' + index);
2205 var img = document.createElement("img");
2207 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2208 this.prefetchedImgs[index] = img;
2213 // prepareFlipLeftToRight()
2215 //______________________________________________________________________________
2217 // Prepare to flip the left page towards the right. This corresponds to moving
2218 // backward when the page progression is left to right.
2219 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2221 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2223 this.prefetchImg(prevL);
2224 this.prefetchImg(prevR);
2226 var height = this._getPageHeight(prevL);
2227 var width = this._getPageWidth(prevL);
2228 var middle = this.twoPage.middle;
2229 var top = this.twoPageTop();
2230 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2232 // The gutter is the dividing line between the left and right pages.
2233 // It is offset from the middle to create the illusion of thickness to the pages
2234 var gutter = middle + this.gutterOffsetForIndex(prevL);
2236 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2237 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2238 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2241 position: 'absolute',
2242 left: gutter-scaledW+'px',
2243 right: '', // clear right property
2245 height: this.twoPage.height,
2246 width: scaledW+'px',
2247 backgroundColor: this.getPageBackgroundColor(prevL),
2248 borderRight: '1px solid black',
2252 $(this.prefetchedImgs[prevL]).css(leftCSS);
2254 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2256 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2259 position: 'absolute',
2263 height: this.twoPage.height,
2265 backgroundColor: this.getPageBackgroundColor(prevR),
2266 borderLeft: '1px solid black',
2270 $(this.prefetchedImgs[prevR]).css(rightCSS);
2272 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2276 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2277 // prepareFlipRightToLeft()
2278 //______________________________________________________________________________
2279 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2281 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2284 this.prefetchImg(nextL);
2285 this.prefetchImg(nextR);
2287 var height = this._getPageHeight(nextR);
2288 var width = this._getPageWidth(nextR);
2289 var middle = this.twoPage.middle;
2290 var top = this.twoPageTop();
2291 var scaledW = this.twoPage.height*width/height;
2293 var gutter = middle + this.gutterOffsetForIndex(nextL);
2295 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2296 $(this.prefetchedImgs[nextR]).css({
2297 position: 'absolute',
2300 backgroundColor: this.getPageBackgroundColor(nextR),
2301 height: this.twoPage.height,
2302 width: scaledW+'px',
2303 borderLeft: '1px solid black',
2307 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2309 height = this._getPageHeight(nextL);
2310 width = this._getPageWidth(nextL);
2311 scaledW = this.twoPage.height*width/height;
2313 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2314 $(this.prefetchedImgs[nextL]).css({
2315 position: 'absolute',
2316 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2318 backgroundColor: this.getPageBackgroundColor(nextL),
2319 height: this.twoPage.height,
2320 width: 0+'px', // Start at 0 width, then grow to the left
2321 borderRight: '1px solid black',
2325 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2329 // getNextLeafs() -- NOT RTL AWARE
2330 //______________________________________________________________________________
2331 // BookReader.prototype.getNextLeafs = function(o) {
2332 // //TODO: we might have two left or two right leafs in a row (damaged book)
2333 // //For now, assume that leafs are contiguous.
2335 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2336 // o.L = this.twoPage.currentIndexL+2;
2337 // o.R = this.twoPage.currentIndexL+3;
2340 // getprevLeafs() -- NOT RTL AWARE
2341 //______________________________________________________________________________
2342 // BookReader.prototype.getPrevLeafs = function(o) {
2343 // //TODO: we might have two left or two right leafs in a row (damaged book)
2344 // //For now, assume that leafs are contiguous.
2346 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2347 // o.L = this.twoPage.currentIndexL-2;
2348 // o.R = this.twoPage.currentIndexL-1;
2351 // pruneUnusedImgs()
2352 //______________________________________________________________________________
2353 BookReader.prototype.pruneUnusedImgs = function() {
2354 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2355 for (var key in this.prefetchedImgs) {
2356 //console.log('key is ' + key);
2357 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2358 //console.log('removing key '+ key);
2359 $(this.prefetchedImgs[key]).remove();
2361 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2362 //console.log('deleting key '+ key);
2363 delete this.prefetchedImgs[key];
2369 //______________________________________________________________________________
2370 BookReader.prototype.prefetch = function() {
2372 // $$$ We should check here if the current indices have finished
2373 // loading (with some timeout) before loading more page images
2374 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2376 // prefetch visible pages first
2377 this.prefetchImg(this.twoPage.currentIndexL);
2378 this.prefetchImg(this.twoPage.currentIndexR);
2380 var adjacentPagesToLoad = 3;
2382 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2383 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2385 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2386 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2388 // Load images spreading out from current
2389 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2390 var goingDown = lowCurrent - i;
2391 if (goingDown >= start) {
2392 this.prefetchImg(goingDown);
2394 var goingUp = highCurrent + i;
2395 if (goingUp <= end) {
2396 this.prefetchImg(goingUp);
2401 var lim = this.twoPage.currentIndexL-4;
2403 lim = Math.max(lim, 0);
2404 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2405 this.prefetchImg(i);
2408 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2409 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2410 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2411 this.prefetchImg(i);
2417 // getPageWidth2UP()
2418 //______________________________________________________________________________
2419 BookReader.prototype.getPageWidth2UP = function(index) {
2420 // We return the width based on the dominant height
2421 var height = this._getPageHeight(index);
2422 var width = this._getPageWidth(index);
2423 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2427 //______________________________________________________________________________
2428 BookReader.prototype.search = function(term) {
2429 term = term.replace(/\//g, ' '); // strip slashes
2430 this.searchTerm = term;
2431 $('#BookReaderSearchScript').remove();
2432 var script = document.createElement("script");
2433 script.setAttribute('id', 'BookReaderSearchScript');
2434 script.setAttribute("type", "text/javascript");
2435 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2436 document.getElementsByTagName('head')[0].appendChild(script);
2437 $('#BookReaderSearchBox').val(term);
2438 $('#BookReaderSearchResults').html('Searching...');
2441 // BRSearchCallback()
2442 //______________________________________________________________________________
2443 BookReader.prototype.BRSearchCallback = function(txt) {
2445 if (jQuery.browser.msie) {
2446 var dom=new ActiveXObject("Microsoft.XMLDOM");
2450 var parser = new DOMParser();
2451 var dom = parser.parseFromString(txt, "text/xml");
2454 $('#BookReaderSearchResults').empty();
2455 $('#BookReaderSearchResults').append('<ul>');
2457 for (var key in this.searchResults) {
2458 if (null != this.searchResults[key].div) {
2459 $(this.searchResults[key].div).remove();
2461 delete this.searchResults[key];
2464 var pages = dom.getElementsByTagName('PAGE');
2466 if (0 == pages.length) {
2467 // $$$ it would be nice to echo the (sanitized) search result here
2468 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2470 for (var i = 0; i < pages.length; i++){
2471 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2474 var re = new RegExp (/_(\d{4})\.djvu/);
2475 var reMatch = re.exec(pages[i].getAttribute('file'));
2476 var index = parseInt(reMatch[1], 10);
2477 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2479 var children = pages[i].childNodes;
2481 for (var j=0; j<children.length; j++) {
2482 //console.log(j + ' - ' + children[j].nodeName);
2483 //console.log(children[j].firstChild.nodeValue);
2484 if ('CONTEXT' == children[j].nodeName) {
2485 context += children[j].firstChild.nodeValue;
2486 } else if ('WORD' == children[j].nodeName) {
2487 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2489 var index = this.leafNumToIndex(index);
2490 if (null != index) {
2491 //coordinates are [left, bottom, right, top, [baseline]]
2492 //we'll skip baseline for now...
2493 var coords = children[j].getAttribute('coords').split(',',4);
2494 if (4 == coords.length) {
2495 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2500 var pageName = this.getPageName(index);
2501 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2502 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2503 //TODO: remove hardcoded instance name
2504 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2507 $('#BookReaderSearchResults').append('</ul>');
2509 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2510 $('#BookReaderSearchBox').val(this.searchTerm);
2512 this.updateSearchHilites();
2515 // updateSearchHilites()
2516 //______________________________________________________________________________
2517 BookReader.prototype.updateSearchHilites = function() {
2518 if (2 == this.mode) {
2519 this.updateSearchHilites2UP();
2521 this.updateSearchHilites1UP();
2525 // showSearchHilites1UP()
2526 //______________________________________________________________________________
2527 BookReader.prototype.updateSearchHilites1UP = function() {
2529 for (var key in this.searchResults) {
2531 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2532 var result = this.searchResults[key];
2533 if (null == result.div) {
2534 result.div = document.createElement('div');
2535 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2536 //console.log('appending ' + key);
2539 width: (result.r-result.l)/this.reduce + 'px',
2540 height: (result.b-result.t)/this.reduce + 'px',
2541 left: (result.l)/this.reduce + 'px',
2542 top: (result.t)/this.reduce +'px'
2546 //console.log(key + ' not displayed');
2547 this.searchResults[key].div=null;
2553 //______________________________________________________________________________
2554 // Returns the position of the gutter (line between the page images)
2555 BookReader.prototype.twoPageGutter = function() {
2556 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2560 //______________________________________________________________________________
2561 // Returns the offset for the top of the page images
2562 BookReader.prototype.twoPageTop = function() {
2563 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2566 // twoPageCoverWidth()
2567 //______________________________________________________________________________
2568 // Returns the width of the cover div given the total page width
2569 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2570 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2573 // twoPageGetViewCenter()
2574 //______________________________________________________________________________
2575 // Returns the percentage offset into twopageview div at the center of container div
2576 // { percentageX: float, percentageY: float }
2577 BookReader.prototype.twoPageGetViewCenter = function() {
2580 var containerOffset = $('#BRcontainer').offset();
2581 var viewOffset = $('#BRtwopageview').offset();
2582 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2583 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2588 // twoPageCenterView(percentageX, percentageY)
2589 //______________________________________________________________________________
2590 // Centers the point given by percentage from left,top of twopageview
2591 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2592 if ('undefined' == typeof(percentageX)) {
2595 if ('undefined' == typeof(percentageY)) {
2599 var viewWidth = $('#BRtwopageview').width();
2600 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2601 var intoViewX = percentageX * viewWidth;
2603 var viewHeight = $('#BRtwopageview').height();
2604 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2605 var intoViewY = percentageY * viewHeight;
2607 if (viewWidth < containerClientWidth) {
2608 // Can fit width without scrollbars - center by adjusting offset
2609 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2611 // Need to scroll to center
2612 $('#BRtwopageview').css('left', 0);
2613 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2616 if (viewHeight < containerClientHeight) {
2617 // Fits with scrollbars - add offset
2618 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2620 $('#BRtwopageview').css('top', 0);
2621 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2625 // twoPageFlipAreaHeight
2626 //______________________________________________________________________________
2627 // Returns the integer height of the click-to-flip areas at the edges of the book
2628 BookReader.prototype.twoPageFlipAreaHeight = function() {
2629 return parseInt(this.twoPage.height);
2632 // twoPageFlipAreaWidth
2633 //______________________________________________________________________________
2634 // Returns the integer width of the flip areas
2635 BookReader.prototype.twoPageFlipAreaWidth = function() {
2636 var max = 100; // $$$ TODO base on view width?
2639 var width = this.twoPage.width * 0.15;
2640 return parseInt(BookReader.util.clamp(width, min, max));
2643 // twoPageFlipAreaTop
2644 //______________________________________________________________________________
2645 // Returns integer top offset for flip areas
2646 BookReader.prototype.twoPageFlipAreaTop = function() {
2647 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2650 // twoPageLeftFlipAreaLeft
2651 //______________________________________________________________________________
2652 // Left offset for left flip area
2653 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2654 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2657 // twoPageRightFlipAreaLeft
2658 //______________________________________________________________________________
2659 // Left offset for right flip area
2660 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2661 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2664 // twoPagePlaceFlipAreas
2665 //______________________________________________________________________________
2666 // Readjusts position of flip areas based on current layout
2667 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2668 // We don't set top since it shouldn't change relative to view
2669 $(this.twoPage.leftFlipArea).css({
2670 left: this.twoPageLeftFlipAreaLeft() + 'px',
2671 width: this.twoPageFlipAreaWidth() + 'px'
2673 $(this.twoPage.rightFlipArea).css({
2674 left: this.twoPageRightFlipAreaLeft() + 'px',
2675 width: this.twoPageFlipAreaWidth() + 'px'
2679 // showSearchHilites2UP()
2680 //______________________________________________________________________________
2681 BookReader.prototype.updateSearchHilites2UP = function() {
2683 for (var key in this.searchResults) {
2684 key = parseInt(key, 10);
2685 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2686 var result = this.searchResults[key];
2687 if (null == result.div) {
2688 result.div = document.createElement('div');
2689 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2690 //console.log('appending ' + key);
2693 // We calculate the reduction factor for the specific page because it can be different
2694 // for each page in the spread
2695 var height = this._getPageHeight(key);
2696 var width = this._getPageWidth(key)
2697 var reduce = this.twoPage.height/height;
2698 var scaledW = parseInt(width*reduce);
2700 var gutter = this.twoPageGutter();
2702 if ('L' == this.getPageSide(key)) {
2703 pageL = gutter-scaledW;
2707 var pageT = this.twoPageTop();
2710 width: (result.r-result.l)*reduce + 'px',
2711 height: (result.b-result.t)*reduce + 'px',
2712 left: pageL+(result.l)*reduce + 'px',
2713 top: pageT+(result.t)*reduce +'px'
2717 //console.log(key + ' not displayed');
2718 if (null != this.searchResults[key].div) {
2719 //console.log('removing ' + key);
2720 $(this.searchResults[key].div).remove();
2722 this.searchResults[key].div=null;
2727 // removeSearchHilites()
2728 //______________________________________________________________________________
2729 BookReader.prototype.removeSearchHilites = function() {
2730 for (var key in this.searchResults) {
2731 if (null != this.searchResults[key].div) {
2732 $(this.searchResults[key].div).remove();
2733 this.searchResults[key].div=null;
2739 //______________________________________________________________________________
2740 BookReader.prototype.printPage = function() {
2741 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2743 /* iframe implementation
2745 if (null != this.printPopup) { // check if already showing
2748 this.printPopup = document.createElement("div");
2749 $(this.printPopup).css({
2750 position: 'absolute',
2752 left: ($('#BRcontainer').width()-400)/2 + 'px',
2755 border: "3px double #999999",
2757 backgroundColor: "#fff"
2758 }).appendTo('#BookReader');
2761 if (this.constMode1up == this.mode) {
2762 indexToPrint = this.firstIndex;
2764 indexToPrint = this.twoPage.currentIndexL;
2767 this.indexToPrint = indexToPrint;
2769 var htmlStr = '<div style="text-align: center;">';
2770 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2771 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2772 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2773 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2774 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2775 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2777 htmlStr += '</div>';
2778 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2779 htmlStr += '</div>';
2781 this.printPopup.innerHTML = htmlStr;
2783 var iframe = document.createElement('iframe');
2784 iframe.id = 'printFrame';
2785 iframe.name = 'printFrame';
2786 iframe.width = '233px'; // 8.5 x 11 aspect
2787 iframe.height = '300px';
2789 var self = this; // closure
2791 $(iframe).load(function() {
2792 var doc = BookReader.util.getIFrameDocument(this);
2793 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2796 $('#printDiv').prepend(iframe);
2800 // Get print URI from current indices and mode
2801 BookReader.prototype.getPrintURI = function() {
2803 if (this.constMode2up == this.mode) {
2804 indexToPrint = this.twoPage.currentIndexL;
2806 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2809 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2810 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2811 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2813 if (this.constMode2up == this.mode) {
2814 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2815 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2816 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2818 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2821 return '/bookreader/print.php?' + options;
2824 /* iframe implementation
2825 BookReader.prototype.getPrintFrameContent = function(index) {
2826 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2827 // 8.5x11 so we should end up not overflowing on either paper size.
2828 var paperAspect = 8.5 / 11;
2829 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2833 // Rotate if possible and appropriate, to get larger image size on printed page
2834 if (this.canRotatePage(index)) {
2835 if (imageAspect > 1 && imageAspect > paperAspect) {
2836 // more wide than square, and more wide than paper
2838 imageAspect = 1/imageAspect;
2843 if (imageAspect > paperAspect) {
2844 // wider than paper, fit width
2845 fitAttrs = 'width="95%"';
2847 // taller than paper, fit height
2848 fitAttrs = 'height="95%"';
2851 var imageURL = this._getPageURI(index, 1, rotate);
2852 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2853 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2854 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2855 iframeStr += '</div>';
2856 iframeStr += '</body></html>';
2861 BookReader.prototype.updatePrintFrame = function(delta) {
2862 var newIndex = this.indexToPrint + delta;
2863 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2864 if (newIndex == this.indexToPrint) {
2867 this.indexToPrint = newIndex;
2868 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2869 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2874 //______________________________________________________________________________
2875 BookReader.prototype.showEmbedCode = function() {
2876 if (null != this.embedPopup) { // check if already showing
2880 this.embedPopup = document.createElement("div");
2881 $(this.embedPopup).css({
2882 position: 'absolute',
2884 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2887 border: "3px double #999999",
2889 backgroundColor: "#fff"
2890 }).appendTo('#BookReader');
2892 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2893 htmlStr += '<p>The bookreader uses iframes for embedding. It will not work on web hosts that block iframes. The embed feature has been tested on blogspot.com blogs as well as self-hosted Wordpress blogs. This feature will NOT work on wordpress.com blogs.</p>';
2894 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2895 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2897 this.embedPopup.innerHTML = htmlStr;
2898 $(this.embedPopup).find('input').bind('click', function() {
2904 //______________________________________________________________________________
2905 BookReader.prototype.autoToggle = function() {
2907 var bComingFrom1up = false;
2908 if (2 != this.mode) {
2909 bComingFrom1up = true;
2913 // Change to autofit if book is too large
2914 if (this.reduce < this.twoPageGetAutofitReduce()) {
2919 if (null == this.autoTimer) {
2920 this.flipSpeed = 2000;
2922 // $$$ Draw events currently cause layout problems when they occur during animation.
2923 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2924 // we workaround for now by not triggering immediate animation in that case.
2925 // See https://bugs.launchpad.net/gnubook/+bug/328327
2926 if (('rl' == this.pageProgression) && bComingFrom1up) {
2927 // don't flip immediately -- wait until timer fires
2930 this.flipFwdToIndex();
2933 $('#BRtoolbar .play').hide();
2934 $('#BRtoolbar .pause').show();
2935 this.autoTimer=setInterval(function(){
2936 if (self.animating) {return;}
2938 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2939 self.flipBackToIndex(1); // $$$ really what we want?
2941 self.flipFwdToIndex();
2950 //______________________________________________________________________________
2951 // Stop autoplay mode, allowing animations to finish
2952 BookReader.prototype.autoStop = function() {
2953 if (null != this.autoTimer) {
2954 clearInterval(this.autoTimer);
2955 this.flipSpeed = 'fast';
2956 $('#BRtoolbar .pause').hide();
2957 $('#BRtoolbar .play').show();
2958 this.autoTimer = null;
2962 // stopFlipAnimations
2963 //______________________________________________________________________________
2964 // Immediately stop flip animations. Callbacks are triggered.
2965 BookReader.prototype.stopFlipAnimations = function() {
2967 this.autoStop(); // Clear timers
2969 // Stop animation, clear queue, trigger callbacks
2970 if (this.leafEdgeTmp) {
2971 $(this.leafEdgeTmp).stop(false, true);
2973 jQuery.each(this.prefetchedImgs, function() {
2974 $(this).stop(false, true);
2977 // And again since animations also queued in callbacks
2978 if (this.leafEdgeTmp) {
2979 $(this.leafEdgeTmp).stop(false, true);
2981 jQuery.each(this.prefetchedImgs, function() {
2982 $(this).stop(false, true);
2987 // keyboardNavigationIsDisabled(event)
2988 // - returns true if keyboard navigation should be disabled for the event
2989 //______________________________________________________________________________
2990 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2991 if (event.target.tagName == "INPUT") {
2997 // gutterOffsetForIndex
2998 //______________________________________________________________________________
3000 // Returns the gutter offset for the spread containing the given index.
3001 // This function supports RTL
3002 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3004 // To find the offset of the gutter from the middle we calculate our percentage distance
3005 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3006 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3008 // But then again for RTL it's the opposite
3009 if ('rl' == this.pageProgression) {
3017 //______________________________________________________________________________
3018 // Returns the width of the leaf edge div for the page with index given
3019 BookReader.prototype.leafEdgeWidth = function(pindex) {
3020 // $$$ could there be single pixel rounding errors for L vs R?
3021 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3022 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3024 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3028 // jumpIndexForLeftEdgePageX
3029 //______________________________________________________________________________
3030 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3031 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3032 if ('rl' != this.pageProgression) {
3033 // LTR - flipping backward
3034 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3036 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3037 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3041 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3042 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3047 // jumpIndexForRightEdgePageX
3048 //______________________________________________________________________________
3049 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3050 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3051 if ('rl' != this.pageProgression) {
3053 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3054 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3057 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3058 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3063 BookReader.prototype.initToolbar = function(mode, ui) {
3065 $("#BookReader").append("<div id='BRtoolbar'>"
3066 + "<span id='BRtoolbarbuttons' style='float: right'>"
3067 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3068 + "<form class='BRpageform' action='javascript:' onsubmit='br.jumpToPage(this.elements[0].value)'> <span class='label'>Page:<input id='BRpagenum' type='text' size='3' onfocus='br.autoStop();'></input></span></form>"
3069 + "<div class='BRtoolbarmode2' style='display: none'><button class='BRicon rollover book_leftmost' /><button class='BRicon rollover book_left' /><button class='BRicon rollover book_right' /><button class='BRicon rollover book_rightmost' /></div>"
3070 + "<div class='BRtoolbarmode1' style='display: none'><button class='BRicon rollover book_top' /><button class='BRicon rollover book_up' /> <button class='BRicon rollover book_down' /><button class='BRicon rollover book_bottom' /></div>"
3071 + "<div class='BRtoolbarmode3' style='display: none'><button class='BRicon rollover book_top' /><button class='BRicon rollover book_up' /> <button class='BRicon rollover book_down' /><button class='BRicon rollover book_bottom' /></div>"
3072 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3076 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3077 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3078 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3079 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3080 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3081 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3082 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3085 + "<span id='#BRbooktitle'>"
3086 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3090 this.updateToolbarZoom(this.reduce); // Pretty format
3092 if (ui == "embed" || ui == "touch") {
3093 $("#BookReader a.logo").attr("target","_blank");
3096 // $$$ turn this into a member variable
3097 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3099 // We build in mode 2
3102 this.bindToolbarNavHandlers(jToolbar);
3104 // Setup tooltips -- later we could load these from a file for i18n
3105 var titles = { '.logo': 'Go to Archive.org',
3106 '.zoom_in': 'Zoom in',
3107 '.zoom_out': 'Zoom out',
3108 '.one_page_mode': 'One-page view',
3109 '.two_page_mode': 'Two-page view',
3110 '.thumbnail_mode': 'Thumbnail view',
3111 '.print': 'Print this page',
3112 '.embed': 'Embed bookreader',
3113 '.book_left': 'Flip left',
3114 '.book_right': 'Flip right',
3115 '.book_up': 'Page up',
3116 '.book_down': 'Page down',
3119 '.book_top': 'First page',
3120 '.book_bottom': 'Last page'
3122 if ('rl' == this.pageProgression) {
3123 titles['.book_leftmost'] = 'Last page';
3124 titles['.book_rightmost'] = 'First page';
3126 titles['.book_leftmost'] = 'First page';
3127 titles['.book_rightmost'] = 'Last page';
3130 for (var icon in titles) {
3131 jToolbar.find(icon).attr('title', titles[icon]);
3134 // Hide mode buttons and autoplay if 2up is not available
3135 // $$$ if we end up with more than two modes we should show the applicable buttons
3136 if ( !this.canSwitchToMode(this.constMode2up) ) {
3137 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3140 // Switch to requested mode -- binds other click handlers
3141 this.switchToolbarMode(mode);
3146 // switchToolbarMode
3147 //______________________________________________________________________________
3148 // Update the toolbar for the given mode (changes navigation buttons)
3149 // $$$ we should soon split the toolbar out into its own module
3150 BookReader.prototype.switchToolbarMode = function(mode) {
3153 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3154 $('#BRtoolbar .BRtoolbarmode2').hide();
3155 $('#BRtoolbar .BRtoolbarmode3').hide();
3156 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3157 } else if (2 == mode) {
3159 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3160 $('#BRtoolbar .BRtoolbarmode1').hide();
3161 $('#BRtoolbar .BRtoolbarmode3').hide();
3162 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3165 $('#BRtoolbar .BRtoolbarzoom').hide();
3166 $('#BRtoolbar .BRtoolbarmode2').hide();
3167 $('#BRtoolbar .BRtoolbarmode1').hide();
3168 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3172 // bindToolbarNavHandlers
3173 //______________________________________________________________________________
3174 // Binds the toolbar handlers
3175 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3177 var self = this; // closure
3179 jToolbar.find('.book_left').bind('click', function(e) {
3184 jToolbar.find('.book_right').bind('click', function(e) {
3189 jToolbar.find('.book_up').bind('click', function(e) {
3190 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3198 jToolbar.find('.book_down').bind('click', function(e) {
3199 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3207 jToolbar.find('.print').bind('click', function(e) {
3212 jToolbar.find('.embed').bind('click', function(e) {
3213 self.showEmbedCode();
3217 jToolbar.find('.play').bind('click', function(e) {
3222 jToolbar.find('.pause').bind('click', function(e) {
3227 jToolbar.find('.book_top').bind('click', function(e) {
3232 jToolbar.find('.book_bottom').bind('click', function(e) {
3237 jToolbar.find('.book_leftmost').bind('click', function(e) {
3242 jToolbar.find('.book_rightmost').bind('click', function(e) {
3248 // updateToolbarZoom(reduce)
3249 //______________________________________________________________________________
3250 // Update the displayed zoom factor based on reduction factor
3251 BookReader.prototype.updateToolbarZoom = function(reduce) {
3253 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3256 value = (100 / reduce).toFixed(2);
3257 // Strip trailing zeroes and decimal if all zeroes
3258 value = value.replace(/0+$/,'');
3259 value = value.replace(/\.$/,'');
3262 $('#BRzoom').text(value);
3265 // firstDisplayableIndex
3266 //______________________________________________________________________________
3267 // Returns the index of the first visible page, dependent on the mode.
3268 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3269 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3270 BookReader.prototype.firstDisplayableIndex = function() {
3271 if (this.mode != this.constMode2up) {
3275 if ('rl' != this.pageProgression) {
3277 if (this.getPageSide(0) == 'L') {
3284 if (this.getPageSide(0) == 'R') {
3292 // lastDisplayableIndex
3293 //______________________________________________________________________________
3294 // Returns the index of the last visible page, dependent on the mode.
3295 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3296 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3297 BookReader.prototype.lastDisplayableIndex = function() {
3299 var lastIndex = this.numLeafs - 1;
3301 if (this.mode != this.constMode2up) {
3305 if ('rl' != this.pageProgression) {
3307 if (this.getPageSide(lastIndex) == 'R') {
3310 return lastIndex + 1;
3314 if (this.getPageSide(lastIndex) == 'L') {
3317 return lastIndex + 1;
3322 // shortTitle(maximumCharacters)
3324 // Returns a shortened version of the title with the maximum number of characters
3325 BookReader.prototype.shortTitle = function(maximumCharacters) {
3326 if (this.bookTitle.length < maximumCharacters) {
3327 return this.bookTitle;
3330 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3335 // Parameter related functions
3337 // updateFromParams(params)
3339 // Update ourselves from the params object.
3341 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3342 BookReader.prototype.updateFromParams = function(params) {
3343 if ('undefined' != typeof(params.mode)) {
3344 this.switchMode(params.mode);
3348 if ('undefined' != typeof(params.searchTerm)) {
3349 if (this.searchTerm != params.searchTerm) {
3350 this.search(params.searchTerm);
3354 // $$$ process /zoom
3356 // We only respect page if index is not set
3357 if ('undefined' != typeof(params.index)) {
3358 if (params.index != this.currentIndex()) {
3359 this.jumpToIndex(params.index);
3361 } else if ('undefined' != typeof(params.page)) {
3362 // $$$ this assumes page numbers are unique
3363 if (params.page != this.getPageNum(this.currentIndex())) {
3364 this.jumpToPage(params.page);
3368 // $$$ process /region
3369 // $$$ process /highlight
3372 // paramsFromFragment(urlFragment)
3374 // Returns a object with configuration parametes from a URL fragment.
3376 // E.g paramsFromFragment(window.location.hash)
3377 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3378 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3382 // For convenience we allow an initial # character (as from window.location.hash)
3383 // but don't require it
3384 if (urlFragment.substr(0,1) == '#') {
3385 urlFragment = urlFragment.substr(1);
3388 // Simple #nn syntax
3389 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3390 if ( !isNaN(oldStyleLeafNum) ) {
3391 params.index = oldStyleLeafNum;
3393 // Done processing if using old-style syntax
3397 // Split into key-value pairs
3398 var urlArray = urlFragment.split('/');
3400 for (var i = 0; i < urlArray.length; i += 2) {
3401 urlHash[urlArray[i]] = urlArray[i+1];
3405 if ('1up' == urlHash['mode']) {
3406 params.mode = this.constMode1up;
3407 } else if ('2up' == urlHash['mode']) {
3408 params.mode = this.constMode2up;
3409 } else if ('thumb' == urlHash['mode']) {
3410 params.mode = this.constModeThumb;
3414 if ('undefined' != typeof(urlHash['page'])) {
3415 // page was set -- may not be int
3416 params.page = urlHash['page'];
3419 // $$$ process /region
3420 // $$$ process /search
3422 if (urlHash['search'] != undefined) {
3423 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3426 // $$$ process /highlight
3431 // paramsFromCurrent()
3433 // Create a params object from the current parameters.
3434 BookReader.prototype.paramsFromCurrent = function() {
3438 var index = this.currentIndex();
3439 var pageNum = this.getPageNum(index);
3440 if ((pageNum === 0) || pageNum) {
3441 params.page = pageNum;
3444 params.index = index;
3445 params.mode = this.mode;
3451 if (this.searchHighlightVisible()) {
3452 params.searchTerm = this.searchTerm;
3458 // fragmentFromParams(params)
3460 // Create a fragment string from the params object.
3461 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3462 BookReader.prototype.fragmentFromParams = function(params) {
3463 var separator = '/';
3467 if ('undefined' != typeof(params.page)) {
3468 fragments.push('page', params.page);
3470 // Don't have page numbering -- use index instead
3471 fragments.push('page', 'n' + params.index);
3478 if ('undefined' != typeof(params.mode)) {
3479 if (params.mode == this.constMode1up) {
3480 fragments.push('mode', '1up');
3481 } else if (params.mode == this.constMode2up) {
3482 fragments.push('mode', '2up');
3483 } else if (params.mode == this.constModeThumb) {
3484 fragments.push('mode', 'thumb');
3486 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3491 if (params.searchTerm) {
3492 fragments.push('search', params.searchTerm);
3495 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3498 // getPageIndex(pageNum)
3500 // Returns the *highest* index the given page number, or undefined
3501 BookReader.prototype.getPageIndex = function(pageNum) {
3502 var pageIndices = this.getPageIndices(pageNum);
3504 if (pageIndices.length > 0) {
3505 return pageIndices[pageIndices.length - 1];
3511 // getPageIndices(pageNum)
3513 // Returns an array (possibly empty) of the indices with the given page number
3514 BookReader.prototype.getPageIndices = function(pageNum) {
3517 // Check for special "nXX" page number
3518 if (pageNum.slice(0,1) == 'n') {
3520 var pageIntStr = pageNum.slice(1, pageNum.length);
3521 var pageIndex = parseInt(pageIntStr);
3522 indices.push(pageIndex);
3525 // Do nothing... will run through page names and see if one matches
3530 for (i=0; i<this.numLeafs; i++) {
3531 if (this.getPageNum(i) == pageNum) {
3539 // getPageName(index)
3541 // Returns the name of the page as it should be displayed in the user interface
3542 BookReader.prototype.getPageName = function(index) {
3543 return 'Page ' + this.getPageNum(index);
3546 // updateLocationHash
3548 // Update the location hash from the current parameters. Call this instead of manually
3549 // using window.location.replace
3550 BookReader.prototype.updateLocationHash = function() {
3551 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3552 window.location.replace(newHash);
3554 // This is the variable checked in the timer. Only user-generated changes
3555 // to the URL will trigger the event.
3556 this.oldLocationHash = newHash;
3559 // startLocationPolling
3561 // Starts polling of window.location to see hash fragment changes
3562 BookReader.prototype.startLocationPolling = function() {
3563 var self = this; // remember who I am
3564 self.oldLocationHash = window.location.hash;
3566 if (this.locationPollId) {
3567 clearInterval(this.locationPollID);
3568 this.locationPollId = null;
3571 this.locationPollId = setInterval(function() {
3572 var newHash = window.location.hash;
3573 if (newHash != self.oldLocationHash) {
3574 if (newHash != self.oldUserHash) { // Only process new user hash once
3575 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3577 // Queue change if animating
3578 if (self.animating) {
3580 self.animationFinishedCallback = function() {
3581 self.updateFromParams(self.paramsFromFragment(newHash));
3583 } else { // update immediately
3584 self.updateFromParams(self.paramsFromFragment(newHash));
3586 self.oldUserHash = newHash;
3594 // Returns true if we can switch to the requested mode
3595 BookReader.prototype.canSwitchToMode = function(mode) {
3596 if (mode == this.constMode2up) {
3597 // check there are enough pages to display
3598 // $$$ this is a workaround for the mis-feature that we can't display
3599 // short books in 2up mode
3600 if (this.numLeafs < 6) {
3608 // searchHighlightVisible
3610 // Returns true if a search highlight is currently being displayed
3611 BookReader.prototype.searchHighlightVisible = function() {
3612 if (this.constMode2up == this.mode) {
3613 if (this.searchResults[this.twoPage.currentIndexL]
3614 || this.searchResults[this.twoPage.currentIndexR]) {
3618 if (this.searchResults[this.currentIndex()]) {
3625 // getPageBackgroundColor
3627 // Returns a CSS property string for the background color for the given page
3628 // $$$ turn into regular CSS?
3629 BookReader.prototype.getPageBackgroundColor = function(index) {
3630 if (index >= 0 && index < this.numLeafs) {
3632 return this.pageDefaultBackgroundColor;
3640 // Returns the page width for the given index, or first or last page if out of range
3641 BookReader.prototype._getPageWidth = function(index) {
3642 // Synthesize a page width for pages not actually present in book.
3643 // May or may not be the best approach.
3644 // If index is out of range we return the width of first or last page
3645 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3646 return this.getPageWidth(index);
3651 // Returns the page height for the given index, or first or last page if out of range
3652 BookReader.prototype._getPageHeight= function(index) {
3653 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3654 return this.getPageHeight(index);
3659 // Returns the page URI or transparent image if out of range
3660 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3661 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3662 return this.imagesBaseURL + "/transparent.png";
3665 if ('undefined' == typeof(reduce)) {
3666 // reduce not passed in
3667 // $$$ this probably won't work for thumbnail mode
3668 var ratio = this.getPageHeight(index) / this.twoPage.height;
3670 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3673 } else if (ratio < 4) {
3675 } else if (ratio < 8) {
3677 } else if (ratio < 16) {
3679 } else if (ratio < 32) {
3687 return this.getPageURI(index, reduce, rotate);
3690 // Library functions
3692 disableSelect: function(jObject) {
3693 // Bind mouse handlers
3694 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3695 jObject.bind('mousedown', function(e) {
3696 // $$$ check here for right-click and don't disable. Also use jQuery style
3697 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3700 // Special hack for IE7
3701 jObject[0].onselectstart = function(e) { return false; };
3704 clamp: function(value, min, max) {
3705 return Math.min(Math.max(value, min), max);
3708 notInArray: function(value, array) {
3709 // inArray returns -1 or undefined if value not in array
3710 return ! (jQuery.inArray(value, array) >= 0);
3713 getIFrameDocument: function(iframe) {
3714 // Adapted from http://xkr.us/articles/dom/iframe-document/
3715 var outer = (iframe.contentWindow || iframe.contentDocument);
3716 return (outer.document || outer);
3719 decodeURIComponentPlus: function(value) {
3720 // Decodes a URI component and converts '+' to ' '
3721 return decodeURIComponent(value).replace(/\+/g, ' ');
3724 encodeURIComponentPlus: function(value) {
3725 // Encodes a URI component and converts ' ' to '+'
3726 return encodeURIComponent(value).replace(/%20/g, '+');
3728 // The final property here must NOT have a comma after it - IE7