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 border: '1px solid rgb(68, 25, 17)',
1390 width: this.twoPage.bookCoverDivWidth + 'px',
1391 height: this.twoPage.bookCoverDivHeight+'px',
1392 visibility: 'visible',
1393 position: 'absolute',
1394 backgroundColor: '#663929',
1395 left: this.twoPage.bookCoverDivLeft + 'px',
1396 top: this.twoPage.bookCoverDivTop+'px',
1397 MozBorderRadiusTopleft: '7px',
1398 MozBorderRadiusTopright: '7px',
1399 MozBorderRadiusBottomright: '7px',
1400 MozBorderRadiusBottomleft: '7px'
1401 }).appendTo('#BRtwopageview');
1403 this.leafEdgeR = document.createElement('div');
1404 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1405 $(this.leafEdgeR).css({
1406 borderStyle: 'solid solid solid none',
1407 borderColor: 'rgb(51, 51, 34)',
1408 borderWidth: '1px 1px 1px 0px',
1409 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1410 width: this.twoPage.leafEdgeWidthR + 'px',
1411 height: this.twoPage.height-1 + 'px',
1413 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1414 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1415 position: 'absolute'
1416 }).appendTo('#BRtwopageview');
1418 this.leafEdgeL = document.createElement('div');
1419 this.leafEdgeL.className = 'leafEdgeL';
1420 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1421 borderStyle: 'solid none solid solid',
1422 borderColor: 'rgb(51, 51, 34)',
1423 borderWidth: '1px 0px 1px 1px',
1424 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1425 width: this.twoPage.leafEdgeWidthL + 'px',
1426 height: this.twoPage.height-1 + 'px',
1427 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1428 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1429 position: 'absolute'
1430 }).appendTo('#BRtwopageview');
1432 div = document.createElement('div');
1433 $(div).attr('id', 'BRbookspine').css({
1434 border: '1px solid rgb(68, 25, 17)',
1435 width: this.twoPage.bookSpineDivWidth+'px',
1436 height: this.twoPage.bookSpineDivHeight+'px',
1437 position: 'absolute',
1438 backgroundColor: 'rgb(68, 25, 17)',
1439 left: this.twoPage.bookSpineDivLeft+'px',
1440 top: this.twoPage.bookSpineDivTop+'px'
1441 }).appendTo('#BRtwopageview');
1443 var self = this; // for closure
1445 /* Flip areas no longer used
1446 this.twoPage.leftFlipArea = document.createElement('div');
1447 this.twoPage.leftFlipArea.className = 'BRfliparea';
1448 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1450 width: this.twoPageFlipAreaWidth() + 'px',
1451 height: this.twoPageFlipAreaHeight() + 'px',
1452 position: 'absolute',
1453 left: this.twoPageLeftFlipAreaLeft() + 'px',
1454 top: this.twoPageFlipAreaTop() + 'px',
1457 }).bind('click', function(e) {
1459 }).bind('mousedown', function(e) {
1461 }).appendTo('#BRtwopageview');
1463 this.twoPage.rightFlipArea = document.createElement('div');
1464 this.twoPage.rightFlipArea.className = 'BRfliparea';
1465 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1467 width: this.twoPageFlipAreaWidth() + 'px',
1468 height: this.twoPageFlipAreaHeight() + 'px',
1469 position: 'absolute',
1470 left: this.twoPageRightFlipAreaLeft() + 'px',
1471 top: this.twoPageFlipAreaTop() + 'px',
1474 }).bind('click', function(e) {
1476 }).bind('mousedown', function(e) {
1478 }).appendTo('#BRtwopageview');
1481 this.prepareTwoPagePopUp();
1483 this.displayedIndices = [];
1485 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1486 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1488 this.drawLeafsTwoPage();
1489 this.updateToolbarZoom(this.reduce);
1493 this.removeSearchHilites();
1494 this.updateSearchHilites();
1498 // prepareTwoPagePopUp()
1500 // This function prepares the "View Page n" popup that shows while the mouse is
1501 // over the left/right "stack of sheets" edges. It also binds the mouse
1502 // events for these divs.
1503 //______________________________________________________________________________
1504 BookReader.prototype.prepareTwoPagePopUp = function() {
1506 this.twoPagePopUp = document.createElement('div');
1507 $(this.twoPagePopUp).css({
1508 border: '1px solid black',
1510 position: 'absolute',
1511 fontFamily: 'sans-serif',
1514 backgroundColor: 'rgb(255, 255, 238)',
1516 }).appendTo('#BRcontainer');
1517 $(this.twoPagePopUp).hide();
1519 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1520 $(e.data.twoPagePopUp).show();
1523 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1524 $(e.data.twoPagePopUp).hide();
1527 $(this.leafEdgeL).bind('click', this, function(e) {
1529 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1530 e.data.jumpToIndex(jumpIndex);
1533 $(this.leafEdgeR).bind('click', this, function(e) {
1535 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1536 e.data.jumpToIndex(jumpIndex);
1539 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1541 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1542 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1544 // $$$ TODO: Make sure popup is positioned so that it is in view
1545 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1546 $(e.data.twoPagePopUp).css({
1547 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1548 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1552 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1554 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1555 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1557 // $$$ TODO: Make sure popup is positioned so that it is in view
1558 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1559 $(e.data.twoPagePopUp).css({
1560 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1561 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1566 // calculateSpreadSize()
1567 //______________________________________________________________________________
1568 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1569 // this.twoPage.currentIndexR
1570 // This function sets this.twoPage.height, twoPage.width
1572 BookReader.prototype.calculateSpreadSize = function() {
1574 var firstIndex = this.twoPage.currentIndexL;
1575 var secondIndex = this.twoPage.currentIndexR;
1576 //console.log('first page is ' + firstIndex);
1578 // Calculate page sizes and total leaf width
1580 if ( this.twoPage.autofit) {
1581 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1583 // set based on reduction factor
1584 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1587 // Both pages together
1588 this.twoPage.height = spreadSize.height;
1589 this.twoPage.width = spreadSize.width;
1592 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1593 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1596 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1597 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1598 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1602 // The width of the book cover div. The combined width of both pages, twice the width
1603 // of the book cover internal padding (2*10) and the page edges
1604 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1605 // The height of the book cover div
1606 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1609 // We calculate the total width and height for the div so that we can make the book
1611 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1612 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1613 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1614 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1615 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1616 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1618 // We want to minimize the unused space in two-up mode (maximize the amount of page
1619 // shown). We give width to the leaf edges and these widths change (though the sum
1620 // of the two remains constant) as we flip through the book. With the book
1621 // cover centered and fixed in the BRcontainer div the page images will meet
1622 // at the "gutter" which is generally offset from the center.
1623 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1624 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1626 // The left edge of the book cover moves depending on the width of the pages
1627 // $$$ change to getter
1628 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1629 // The top edge of the book cover stays a fixed distance from the top
1630 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1633 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1634 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1635 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1638 this.reduce = spreadSize.reduce; // $$$ really set this here?
1641 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1644 // We check which page is closest to a "normal" page and use that to set the height
1645 // for both pages. This means that foldouts and other odd size pages will be displayed
1646 // smaller than the nominal zoom amount.
1647 var canon5Dratio = 1.5;
1650 height: this._getPageHeight(firstIndex),
1651 width: this._getPageWidth(firstIndex)
1655 height: this._getPageHeight(secondIndex),
1656 width: this._getPageWidth(secondIndex)
1659 var firstIndexRatio = first.height / first.width;
1660 var secondIndexRatio = second.height / second.width;
1661 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1664 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1665 ratio = firstIndexRatio;
1666 //console.log('using firstIndexRatio ' + ratio);
1668 ratio = secondIndexRatio;
1669 //console.log('using secondIndexRatio ' + ratio);
1672 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1673 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1674 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1676 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1677 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1679 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1680 ideal.width -= 10; // $$$ fudge factor
1681 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1682 ideal.height -= 20; // fudge factor
1683 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1685 if (ideal.height/ratio <= ideal.width) {
1687 ideal.width = parseInt(ideal.height/ratio);
1690 ideal.height = parseInt(ideal.width*ratio);
1693 // $$$ check this logic with large spreads
1694 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1699 // getSpreadSizeFromReduce()
1700 //______________________________________________________________________________
1701 // Returns the spread size calculated from the reduction factor for the given pages
1702 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1703 var spreadSize = {};
1704 // $$$ Scale this based on reduce?
1705 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1706 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1707 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1709 // $$$ Possibly incorrect -- we should make height "dominant"
1710 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1711 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1712 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1713 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1714 spreadSize.reduce = reduce;
1719 // twoPageGetAutofitReduce()
1720 //______________________________________________________________________________
1721 // Returns the current ideal reduction factor
1722 BookReader.prototype.twoPageGetAutofitReduce = function() {
1723 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1724 return spreadSize.reduce;
1727 // twoPageSetCursor()
1728 //______________________________________________________________________________
1729 // Set the cursor for two page view
1730 BookReader.prototype.twoPageSetCursor = function() {
1731 // console.log('setting cursor');
1732 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1733 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1734 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1735 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1737 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1738 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1743 //______________________________________________________________________________
1744 // Returns the currently active index.
1745 BookReader.prototype.currentIndex = function() {
1746 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1747 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1748 return this.firstIndex; // $$$ TODO page in center of view would be better
1749 } else if (this.mode == this.constMode2up) {
1750 // Only allow indices that are actually present in book
1751 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1753 throw 'currentIndex called for unimplemented mode ' + this.mode;
1757 // setCurrentIndex(index)
1758 //______________________________________________________________________________
1759 // Sets the idea of current index without triggering other actions such as animation.
1760 // Compare to jumpToIndex which animates to that index
1761 BookReader.prototype.setCurrentIndex = function(index) {
1762 this.firstIndex = index;
1767 //______________________________________________________________________________
1768 // Flip the right page over onto the left
1769 BookReader.prototype.right = function() {
1770 if ('rl' != this.pageProgression) {
1780 //______________________________________________________________________________
1781 // Flip to the rightmost page
1782 BookReader.prototype.rightmost = function() {
1783 if ('rl' != this.pageProgression) {
1791 //______________________________________________________________________________
1792 // Flip the left page over onto the right.
1793 BookReader.prototype.left = function() {
1794 if ('rl' != this.pageProgression) {
1804 //______________________________________________________________________________
1805 // Flip to the leftmost page
1806 BookReader.prototype.leftmost = function() {
1807 if ('rl' != this.pageProgression) {
1815 //______________________________________________________________________________
1816 BookReader.prototype.next = function() {
1817 if (2 == this.mode) {
1819 this.flipFwdToIndex(null);
1821 if (this.firstIndex < this.lastDisplayableIndex()) {
1822 this.jumpToIndex(this.firstIndex+1);
1828 //______________________________________________________________________________
1829 BookReader.prototype.prev = function() {
1830 if (2 == this.mode) {
1832 this.flipBackToIndex(null);
1834 if (this.firstIndex >= 1) {
1835 this.jumpToIndex(this.firstIndex-1);
1840 BookReader.prototype.first = function() {
1841 this.jumpToIndex(this.firstDisplayableIndex());
1844 BookReader.prototype.last = function() {
1845 this.jumpToIndex(this.lastDisplayableIndex());
1849 //______________________________________________________________________________
1850 // Scrolls down one screen view
1851 BookReader.prototype.scrollDown = function() {
1852 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1853 $('#BRcontainer').animate(
1854 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1855 450, 'easeInOutQuint'
1864 //______________________________________________________________________________
1865 // Scrolls up one screen view
1866 BookReader.prototype.scrollUp = function() {
1867 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1868 $('#BRcontainer').animate(
1869 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1870 450, 'easeInOutQuint'
1879 // flipBackToIndex()
1880 //______________________________________________________________________________
1881 // to flip back one spread, pass index=null
1882 BookReader.prototype.flipBackToIndex = function(index) {
1884 if (1 == this.mode) return;
1886 var leftIndex = this.twoPage.currentIndexL;
1888 if (this.animating) return;
1890 if (null != this.leafEdgeTmp) {
1891 alert('error: leafEdgeTmp should be null!');
1895 if (null == index) {
1896 index = leftIndex-2;
1898 //if (index<0) return;
1900 var previousIndices = this.getSpreadIndices(index);
1902 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1906 this.animating = true;
1908 if ('rl' != this.pageProgression) {
1909 // Assume LTR and we are going backward
1910 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1911 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1913 // RTL and going backward
1914 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1915 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1919 // flipLeftToRight()
1920 //______________________________________________________________________________
1921 // Flips the page on the left towards the page on the right
1922 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1924 var leftLeaf = this.twoPage.currentIndexL;
1926 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1927 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1928 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1930 var currWidthL = this.getPageWidth2UP(leftLeaf);
1931 var newWidthL = this.getPageWidth2UP(newIndexL);
1932 var newWidthR = this.getPageWidth2UP(newIndexR);
1934 var top = this.twoPageTop();
1935 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1937 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1938 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1940 //animation strategy:
1941 // 0. remove search highlight, if any.
1942 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1943 // of the left leaf and where the user clicked in the leaf edge.
1944 // Note that if this function was triggered by left() and not a
1945 // mouse click, the width of leafEdgeTmp is very small (zero px).
1946 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1947 // leftLeaf to width=0.
1948 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1949 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1950 // its new full width.
1951 // 4. After step 3 is finished, do the following:
1952 // - remove leafEdgeTmp from the dom.
1953 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1954 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1955 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1956 // and width=newLeafEdgeWidthL.
1957 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1958 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1959 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1960 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1961 // - prefetch new adjacent leafs.
1962 // - set up click handlers for both new left and right leafs.
1963 // - redraw the search highlight.
1964 // - update the pagenum box and the url.
1967 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1969 this.leafEdgeTmp = document.createElement('div');
1970 $(this.leafEdgeTmp).css({
1971 borderStyle: 'solid none solid solid',
1972 borderColor: 'rgb(51, 51, 34)',
1973 borderWidth: '1px 0px 1px 1px',
1974 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1975 width: leafEdgeTmpW + 'px',
1976 height: this.twoPage.height-1 + 'px',
1977 left: leftEdgeTmpLeft + 'px',
1979 position: 'absolute',
1981 }).appendTo('#BRtwopageview');
1983 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1984 $(this.leafEdgeL).css({
1985 width: newLeafEdgeWidthL+'px',
1986 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1989 // Left gets the offset of the current left leaf from the document
1990 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1991 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1992 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1994 // We change the left leaf to right positioning
1995 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1996 $(this.prefetchedImgs[leftLeaf]).css({
2001 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2002 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2006 this.removeSearchHilites();
2008 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2009 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2011 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2012 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2014 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2015 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2016 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2018 $(self.leafEdgeR).css({
2019 // Moves the right leaf edge
2020 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2021 left: gutter+newWidthR+'px'
2024 $(self.leafEdgeL).css({
2025 // Moves and resizes the left leaf edge
2026 width: newLeafEdgeWidthL+'px',
2027 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2030 // Resizes the brown border div
2031 $(self.twoPage.coverDiv).css({
2032 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2033 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2036 $(self.leafEdgeTmp).remove();
2037 self.leafEdgeTmp = null;
2039 // $$$ TODO refactor with opposite direction flip
2041 self.twoPage.currentIndexL = newIndexL;
2042 self.twoPage.currentIndexR = newIndexR;
2043 self.twoPage.scaledWL = newWidthL;
2044 self.twoPage.scaledWR = newWidthR;
2045 self.twoPage.gutter = gutter;
2047 self.firstIndex = self.twoPage.currentIndexL;
2048 self.displayedIndices = [newIndexL, newIndexR];
2049 self.pruneUnusedImgs();
2051 self.animating = false;
2053 self.updateSearchHilites2UP();
2054 self.updatePageNumBox2UP();
2056 // self.twoPagePlaceFlipAreas(); // No longer used
2057 self.setMouseHandlers2UP();
2058 self.twoPageSetCursor();
2060 if (self.animationFinishedCallback) {
2061 self.animationFinishedCallback();
2062 self.animationFinishedCallback = null;
2070 //______________________________________________________________________________
2071 // Whether we flip left or right is dependent on the page progression
2072 // to flip forward one spread, pass index=null
2073 BookReader.prototype.flipFwdToIndex = function(index) {
2075 if (this.animating) return;
2077 if (null != this.leafEdgeTmp) {
2078 alert('error: leafEdgeTmp should be null!');
2082 if (null == index) {
2083 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2085 if (index > this.lastDisplayableIndex()) return;
2087 this.animating = true;
2089 var nextIndices = this.getSpreadIndices(index);
2091 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2093 if ('rl' != this.pageProgression) {
2094 // We did not specify RTL
2095 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2096 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2099 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2100 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2104 // flipRightToLeft(nextL, nextR, gutter)
2105 // $$$ better not to have to pass gutter in
2106 //______________________________________________________________________________
2107 // Flip from left to right and show the nextL and nextR indices on those sides
2108 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2109 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2110 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2111 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2112 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2114 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2116 var top = this.twoPageTop();
2117 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2119 var middle = this.twoPage.middle;
2120 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2122 this.leafEdgeTmp = document.createElement('div');
2123 $(this.leafEdgeTmp).css({
2124 borderStyle: 'solid none solid solid',
2125 borderColor: 'rgb(51, 51, 34)',
2126 borderWidth: '1px 0px 1px 1px',
2127 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2128 width: leafEdgeTmpW + 'px',
2129 height: this.twoPage.height-1 + 'px',
2130 left: gutter+scaledW+'px',
2132 position: 'absolute',
2134 }).appendTo('#BRtwopageview');
2136 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2137 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2139 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2140 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2141 var newWidthL = this.getPageWidth2UP(newIndexL);
2142 var newWidthR = this.getPageWidth2UP(newIndexR);
2144 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2146 var self = this; // closure-tastic!
2148 var speed = this.flipSpeed;
2150 this.removeSearchHilites();
2152 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2153 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2154 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2155 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2156 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2158 $(self.leafEdgeL).css({
2159 width: newLeafEdgeWidthL+'px',
2160 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2163 // Resizes the book cover
2164 $(self.twoPage.coverDiv).css({
2165 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2166 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2169 $(self.leafEdgeTmp).remove();
2170 self.leafEdgeTmp = null;
2172 self.twoPage.currentIndexL = newIndexL;
2173 self.twoPage.currentIndexR = newIndexR;
2174 self.twoPage.scaledWL = newWidthL;
2175 self.twoPage.scaledWR = newWidthR;
2176 self.twoPage.gutter = gutter;
2178 self.firstIndex = self.twoPage.currentIndexL;
2179 self.displayedIndices = [newIndexL, newIndexR];
2180 self.pruneUnusedImgs();
2182 self.animating = false;
2185 self.updateSearchHilites2UP();
2186 self.updatePageNumBox2UP();
2188 // self.twoPagePlaceFlipAreas(); // No longer used
2189 self.setMouseHandlers2UP();
2190 self.twoPageSetCursor();
2192 if (self.animationFinishedCallback) {
2193 self.animationFinishedCallback();
2194 self.animationFinishedCallback = null;
2200 // setMouseHandlers2UP
2201 //______________________________________________________________________________
2202 BookReader.prototype.setMouseHandlers2UP = function() {
2203 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2211 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2214 e.data.self.right();
2221 //______________________________________________________________________________
2222 BookReader.prototype.prefetchImg = function(index) {
2223 var pageURI = this._getPageURI(index);
2225 // Load image if not loaded or URI has changed (e.g. due to scaling)
2226 var loadImage = false;
2227 if (undefined == this.prefetchedImgs[index]) {
2228 //console.log('no image for ' + index);
2230 } else if (pageURI != this.prefetchedImgs[index].uri) {
2231 //console.log('uri changed for ' + index);
2236 //console.log('prefetching ' + index);
2237 var img = document.createElement("img");
2239 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2240 this.prefetchedImgs[index] = img;
2245 // prepareFlipLeftToRight()
2247 //______________________________________________________________________________
2249 // Prepare to flip the left page towards the right. This corresponds to moving
2250 // backward when the page progression is left to right.
2251 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2253 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2255 this.prefetchImg(prevL);
2256 this.prefetchImg(prevR);
2258 var height = this._getPageHeight(prevL);
2259 var width = this._getPageWidth(prevL);
2260 var middle = this.twoPage.middle;
2261 var top = this.twoPageTop();
2262 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2264 // The gutter is the dividing line between the left and right pages.
2265 // It is offset from the middle to create the illusion of thickness to the pages
2266 var gutter = middle + this.gutterOffsetForIndex(prevL);
2268 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2269 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2270 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2273 position: 'absolute',
2274 left: gutter-scaledW+'px',
2275 right: '', // clear right property
2277 height: this.twoPage.height,
2278 width: scaledW+'px',
2279 backgroundColor: this.getPageBackgroundColor(prevL),
2280 borderRight: '1px solid black',
2284 $(this.prefetchedImgs[prevL]).css(leftCSS);
2286 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2288 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2291 position: 'absolute',
2295 height: this.twoPage.height,
2297 backgroundColor: this.getPageBackgroundColor(prevR),
2298 borderLeft: '1px solid black',
2302 $(this.prefetchedImgs[prevR]).css(rightCSS);
2304 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2308 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2309 // prepareFlipRightToLeft()
2310 //______________________________________________________________________________
2311 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2313 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2316 this.prefetchImg(nextL);
2317 this.prefetchImg(nextR);
2319 var height = this._getPageHeight(nextR);
2320 var width = this._getPageWidth(nextR);
2321 var middle = this.twoPage.middle;
2322 var top = this.twoPageTop();
2323 var scaledW = this.twoPage.height*width/height;
2325 var gutter = middle + this.gutterOffsetForIndex(nextL);
2327 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2328 $(this.prefetchedImgs[nextR]).css({
2329 position: 'absolute',
2332 backgroundColor: this.getPageBackgroundColor(nextR),
2333 height: this.twoPage.height,
2334 width: scaledW+'px',
2335 borderLeft: '1px solid black',
2339 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2341 height = this._getPageHeight(nextL);
2342 width = this._getPageWidth(nextL);
2343 scaledW = this.twoPage.height*width/height;
2345 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2346 $(this.prefetchedImgs[nextL]).css({
2347 position: 'absolute',
2348 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2350 backgroundColor: this.getPageBackgroundColor(nextL),
2351 height: this.twoPage.height,
2352 width: 0+'px', // Start at 0 width, then grow to the left
2353 borderRight: '1px solid black',
2357 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2361 // getNextLeafs() -- NOT RTL AWARE
2362 //______________________________________________________________________________
2363 // BookReader.prototype.getNextLeafs = function(o) {
2364 // //TODO: we might have two left or two right leafs in a row (damaged book)
2365 // //For now, assume that leafs are contiguous.
2367 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2368 // o.L = this.twoPage.currentIndexL+2;
2369 // o.R = this.twoPage.currentIndexL+3;
2372 // getprevLeafs() -- NOT RTL AWARE
2373 //______________________________________________________________________________
2374 // BookReader.prototype.getPrevLeafs = function(o) {
2375 // //TODO: we might have two left or two right leafs in a row (damaged book)
2376 // //For now, assume that leafs are contiguous.
2378 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2379 // o.L = this.twoPage.currentIndexL-2;
2380 // o.R = this.twoPage.currentIndexL-1;
2383 // pruneUnusedImgs()
2384 //______________________________________________________________________________
2385 BookReader.prototype.pruneUnusedImgs = function() {
2386 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2387 for (var key in this.prefetchedImgs) {
2388 //console.log('key is ' + key);
2389 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2390 //console.log('removing key '+ key);
2391 $(this.prefetchedImgs[key]).remove();
2393 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2394 //console.log('deleting key '+ key);
2395 delete this.prefetchedImgs[key];
2401 //______________________________________________________________________________
2402 BookReader.prototype.prefetch = function() {
2404 // $$$ We should check here if the current indices have finished
2405 // loading (with some timeout) before loading more page images
2406 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2408 // prefetch visible pages first
2409 this.prefetchImg(this.twoPage.currentIndexL);
2410 this.prefetchImg(this.twoPage.currentIndexR);
2412 var adjacentPagesToLoad = 3;
2414 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2415 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2417 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2418 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2420 // Load images spreading out from current
2421 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2422 var goingDown = lowCurrent - i;
2423 if (goingDown >= start) {
2424 this.prefetchImg(goingDown);
2426 var goingUp = highCurrent + i;
2427 if (goingUp <= end) {
2428 this.prefetchImg(goingUp);
2433 var lim = this.twoPage.currentIndexL-4;
2435 lim = Math.max(lim, 0);
2436 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2437 this.prefetchImg(i);
2440 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2441 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2442 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2443 this.prefetchImg(i);
2449 // getPageWidth2UP()
2450 //______________________________________________________________________________
2451 BookReader.prototype.getPageWidth2UP = function(index) {
2452 // We return the width based on the dominant height
2453 var height = this._getPageHeight(index);
2454 var width = this._getPageWidth(index);
2455 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2459 //______________________________________________________________________________
2460 BookReader.prototype.search = function(term) {
2461 term = term.replace(/\//g, ' '); // strip slashes
2462 this.searchTerm = term;
2463 $('#BookReaderSearchScript').remove();
2464 var script = document.createElement("script");
2465 script.setAttribute('id', 'BookReaderSearchScript');
2466 script.setAttribute("type", "text/javascript");
2467 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2468 document.getElementsByTagName('head')[0].appendChild(script);
2469 $('#BookReaderSearchBox').val(term);
2470 $('#BookReaderSearchResults').html('Searching...');
2473 // BRSearchCallback()
2474 //______________________________________________________________________________
2475 BookReader.prototype.BRSearchCallback = function(txt) {
2477 if (jQuery.browser.msie) {
2478 var dom=new ActiveXObject("Microsoft.XMLDOM");
2482 var parser = new DOMParser();
2483 var dom = parser.parseFromString(txt, "text/xml");
2486 $('#BookReaderSearchResults').empty();
2487 $('#BookReaderSearchResults').append('<ul>');
2489 for (var key in this.searchResults) {
2490 if (null != this.searchResults[key].div) {
2491 $(this.searchResults[key].div).remove();
2493 delete this.searchResults[key];
2496 var pages = dom.getElementsByTagName('PAGE');
2498 if (0 == pages.length) {
2499 // $$$ it would be nice to echo the (sanitized) search result here
2500 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2502 for (var i = 0; i < pages.length; i++){
2503 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2506 var re = new RegExp (/_(\d{4})\.djvu/);
2507 var reMatch = re.exec(pages[i].getAttribute('file'));
2508 var index = parseInt(reMatch[1], 10);
2509 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2511 var children = pages[i].childNodes;
2513 for (var j=0; j<children.length; j++) {
2514 //console.log(j + ' - ' + children[j].nodeName);
2515 //console.log(children[j].firstChild.nodeValue);
2516 if ('CONTEXT' == children[j].nodeName) {
2517 context += children[j].firstChild.nodeValue;
2518 } else if ('WORD' == children[j].nodeName) {
2519 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2521 var index = this.leafNumToIndex(index);
2522 if (null != index) {
2523 //coordinates are [left, bottom, right, top, [baseline]]
2524 //we'll skip baseline for now...
2525 var coords = children[j].getAttribute('coords').split(',',4);
2526 if (4 == coords.length) {
2527 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2532 var pageName = this.getPageName(index);
2533 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2534 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2535 //TODO: remove hardcoded instance name
2536 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2539 $('#BookReaderSearchResults').append('</ul>');
2541 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2542 $('#BookReaderSearchBox').val(this.searchTerm);
2544 this.updateSearchHilites();
2547 // updateSearchHilites()
2548 //______________________________________________________________________________
2549 BookReader.prototype.updateSearchHilites = function() {
2550 if (2 == this.mode) {
2551 this.updateSearchHilites2UP();
2553 this.updateSearchHilites1UP();
2557 // showSearchHilites1UP()
2558 //______________________________________________________________________________
2559 BookReader.prototype.updateSearchHilites1UP = function() {
2561 for (var key in this.searchResults) {
2563 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2564 var result = this.searchResults[key];
2565 if (null == result.div) {
2566 result.div = document.createElement('div');
2567 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2568 //console.log('appending ' + key);
2571 width: (result.r-result.l)/this.reduce + 'px',
2572 height: (result.b-result.t)/this.reduce + 'px',
2573 left: (result.l)/this.reduce + 'px',
2574 top: (result.t)/this.reduce +'px'
2578 //console.log(key + ' not displayed');
2579 this.searchResults[key].div=null;
2585 //______________________________________________________________________________
2586 // Returns the position of the gutter (line between the page images)
2587 BookReader.prototype.twoPageGutter = function() {
2588 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2592 //______________________________________________________________________________
2593 // Returns the offset for the top of the page images
2594 BookReader.prototype.twoPageTop = function() {
2595 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2598 // twoPageCoverWidth()
2599 //______________________________________________________________________________
2600 // Returns the width of the cover div given the total page width
2601 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2602 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2605 // twoPageGetViewCenter()
2606 //______________________________________________________________________________
2607 // Returns the percentage offset into twopageview div at the center of container div
2608 // { percentageX: float, percentageY: float }
2609 BookReader.prototype.twoPageGetViewCenter = function() {
2612 var containerOffset = $('#BRcontainer').offset();
2613 var viewOffset = $('#BRtwopageview').offset();
2614 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2615 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2620 // twoPageCenterView(percentageX, percentageY)
2621 //______________________________________________________________________________
2622 // Centers the point given by percentage from left,top of twopageview
2623 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2624 if ('undefined' == typeof(percentageX)) {
2627 if ('undefined' == typeof(percentageY)) {
2631 var viewWidth = $('#BRtwopageview').width();
2632 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2633 var intoViewX = percentageX * viewWidth;
2635 var viewHeight = $('#BRtwopageview').height();
2636 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2637 var intoViewY = percentageY * viewHeight;
2639 if (viewWidth < containerClientWidth) {
2640 // Can fit width without scrollbars - center by adjusting offset
2641 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2643 // Need to scroll to center
2644 $('#BRtwopageview').css('left', 0);
2645 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2648 if (viewHeight < containerClientHeight) {
2649 // Fits with scrollbars - add offset
2650 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2652 $('#BRtwopageview').css('top', 0);
2653 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2657 // twoPageFlipAreaHeight
2658 //______________________________________________________________________________
2659 // Returns the integer height of the click-to-flip areas at the edges of the book
2660 BookReader.prototype.twoPageFlipAreaHeight = function() {
2661 return parseInt(this.twoPage.height);
2664 // twoPageFlipAreaWidth
2665 //______________________________________________________________________________
2666 // Returns the integer width of the flip areas
2667 BookReader.prototype.twoPageFlipAreaWidth = function() {
2668 var max = 100; // $$$ TODO base on view width?
2671 var width = this.twoPage.width * 0.15;
2672 return parseInt(BookReader.util.clamp(width, min, max));
2675 // twoPageFlipAreaTop
2676 //______________________________________________________________________________
2677 // Returns integer top offset for flip areas
2678 BookReader.prototype.twoPageFlipAreaTop = function() {
2679 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2682 // twoPageLeftFlipAreaLeft
2683 //______________________________________________________________________________
2684 // Left offset for left flip area
2685 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2686 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2689 // twoPageRightFlipAreaLeft
2690 //______________________________________________________________________________
2691 // Left offset for right flip area
2692 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2693 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2696 // twoPagePlaceFlipAreas
2697 //______________________________________________________________________________
2698 // Readjusts position of flip areas based on current layout
2699 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2700 // We don't set top since it shouldn't change relative to view
2701 $(this.twoPage.leftFlipArea).css({
2702 left: this.twoPageLeftFlipAreaLeft() + 'px',
2703 width: this.twoPageFlipAreaWidth() + 'px'
2705 $(this.twoPage.rightFlipArea).css({
2706 left: this.twoPageRightFlipAreaLeft() + 'px',
2707 width: this.twoPageFlipAreaWidth() + 'px'
2711 // showSearchHilites2UP()
2712 //______________________________________________________________________________
2713 BookReader.prototype.updateSearchHilites2UP = function() {
2715 for (var key in this.searchResults) {
2716 key = parseInt(key, 10);
2717 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2718 var result = this.searchResults[key];
2719 if (null == result.div) {
2720 result.div = document.createElement('div');
2721 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2722 //console.log('appending ' + key);
2725 // We calculate the reduction factor for the specific page because it can be different
2726 // for each page in the spread
2727 var height = this._getPageHeight(key);
2728 var width = this._getPageWidth(key)
2729 var reduce = this.twoPage.height/height;
2730 var scaledW = parseInt(width*reduce);
2732 var gutter = this.twoPageGutter();
2734 if ('L' == this.getPageSide(key)) {
2735 pageL = gutter-scaledW;
2739 var pageT = this.twoPageTop();
2742 width: (result.r-result.l)*reduce + 'px',
2743 height: (result.b-result.t)*reduce + 'px',
2744 left: pageL+(result.l)*reduce + 'px',
2745 top: pageT+(result.t)*reduce +'px'
2749 //console.log(key + ' not displayed');
2750 if (null != this.searchResults[key].div) {
2751 //console.log('removing ' + key);
2752 $(this.searchResults[key].div).remove();
2754 this.searchResults[key].div=null;
2759 // removeSearchHilites()
2760 //______________________________________________________________________________
2761 BookReader.prototype.removeSearchHilites = function() {
2762 for (var key in this.searchResults) {
2763 if (null != this.searchResults[key].div) {
2764 $(this.searchResults[key].div).remove();
2765 this.searchResults[key].div=null;
2771 //______________________________________________________________________________
2772 BookReader.prototype.printPage = function() {
2773 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2775 /* iframe implementation
2777 if (null != this.printPopup) { // check if already showing
2780 this.printPopup = document.createElement("div");
2781 $(this.printPopup).css({
2782 position: 'absolute',
2784 left: ($('#BRcontainer').width()-400)/2 + 'px',
2787 border: "3px double #999999",
2789 backgroundColor: "#fff"
2790 }).appendTo('#BookReader');
2793 if (this.constMode1up == this.mode) {
2794 indexToPrint = this.firstIndex;
2796 indexToPrint = this.twoPage.currentIndexL;
2799 this.indexToPrint = indexToPrint;
2801 var htmlStr = '<div style="text-align: center;">';
2802 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>';
2803 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2804 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2805 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2806 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2807 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2809 htmlStr += '</div>';
2810 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2811 htmlStr += '</div>';
2813 this.printPopup.innerHTML = htmlStr;
2815 var iframe = document.createElement('iframe');
2816 iframe.id = 'printFrame';
2817 iframe.name = 'printFrame';
2818 iframe.width = '233px'; // 8.5 x 11 aspect
2819 iframe.height = '300px';
2821 var self = this; // closure
2823 $(iframe).load(function() {
2824 var doc = BookReader.util.getIFrameDocument(this);
2825 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2828 $('#printDiv').prepend(iframe);
2832 // Get print URI from current indices and mode
2833 BookReader.prototype.getPrintURI = function() {
2835 if (this.constMode2up == this.mode) {
2836 indexToPrint = this.twoPage.currentIndexL;
2838 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2841 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2842 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2843 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2845 if (this.constMode2up == this.mode) {
2846 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2847 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2848 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2850 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2853 return '/bookreader/print.php?' + options;
2856 /* iframe implementation
2857 BookReader.prototype.getPrintFrameContent = function(index) {
2858 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2859 // 8.5x11 so we should end up not overflowing on either paper size.
2860 var paperAspect = 8.5 / 11;
2861 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2865 // Rotate if possible and appropriate, to get larger image size on printed page
2866 if (this.canRotatePage(index)) {
2867 if (imageAspect > 1 && imageAspect > paperAspect) {
2868 // more wide than square, and more wide than paper
2870 imageAspect = 1/imageAspect;
2875 if (imageAspect > paperAspect) {
2876 // wider than paper, fit width
2877 fitAttrs = 'width="95%"';
2879 // taller than paper, fit height
2880 fitAttrs = 'height="95%"';
2883 var imageURL = this._getPageURI(index, 1, rotate);
2884 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2885 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2886 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2887 iframeStr += '</div>';
2888 iframeStr += '</body></html>';
2893 BookReader.prototype.updatePrintFrame = function(delta) {
2894 var newIndex = this.indexToPrint + delta;
2895 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2896 if (newIndex == this.indexToPrint) {
2899 this.indexToPrint = newIndex;
2900 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2901 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2906 //______________________________________________________________________________
2907 BookReader.prototype.showEmbedCode = function() {
2908 if (null != this.embedPopup) { // check if already showing
2912 this.embedPopup = document.createElement("div");
2913 $(this.embedPopup).css({
2914 position: 'absolute',
2916 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2919 border: "3px double #999999",
2921 backgroundColor: "#fff"
2922 }).appendTo('#BookReader');
2924 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2925 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>';
2926 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2927 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2929 this.embedPopup.innerHTML = htmlStr;
2930 $(this.embedPopup).find('input').bind('click', function() {
2936 //______________________________________________________________________________
2937 BookReader.prototype.autoToggle = function() {
2939 var bComingFrom1up = false;
2940 if (2 != this.mode) {
2941 bComingFrom1up = true;
2945 // Change to autofit if book is too large
2946 if (this.reduce < this.twoPageGetAutofitReduce()) {
2951 if (null == this.autoTimer) {
2952 this.flipSpeed = 2000;
2954 // $$$ Draw events currently cause layout problems when they occur during animation.
2955 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2956 // we workaround for now by not triggering immediate animation in that case.
2957 // See https://bugs.launchpad.net/gnubook/+bug/328327
2958 if (('rl' == this.pageProgression) && bComingFrom1up) {
2959 // don't flip immediately -- wait until timer fires
2962 this.flipFwdToIndex();
2965 $('#BRtoolbar .play').hide();
2966 $('#BRtoolbar .pause').show();
2967 this.autoTimer=setInterval(function(){
2968 if (self.animating) {return;}
2970 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2971 self.flipBackToIndex(1); // $$$ really what we want?
2973 self.flipFwdToIndex();
2982 //______________________________________________________________________________
2983 // Stop autoplay mode, allowing animations to finish
2984 BookReader.prototype.autoStop = function() {
2985 if (null != this.autoTimer) {
2986 clearInterval(this.autoTimer);
2987 this.flipSpeed = 'fast';
2988 $('#BRtoolbar .pause').hide();
2989 $('#BRtoolbar .play').show();
2990 this.autoTimer = null;
2994 // stopFlipAnimations
2995 //______________________________________________________________________________
2996 // Immediately stop flip animations. Callbacks are triggered.
2997 BookReader.prototype.stopFlipAnimations = function() {
2999 this.autoStop(); // Clear timers
3001 // Stop animation, clear queue, trigger callbacks
3002 if (this.leafEdgeTmp) {
3003 $(this.leafEdgeTmp).stop(false, true);
3005 jQuery.each(this.prefetchedImgs, function() {
3006 $(this).stop(false, true);
3009 // And again since animations also queued in callbacks
3010 if (this.leafEdgeTmp) {
3011 $(this.leafEdgeTmp).stop(false, true);
3013 jQuery.each(this.prefetchedImgs, function() {
3014 $(this).stop(false, true);
3019 // keyboardNavigationIsDisabled(event)
3020 // - returns true if keyboard navigation should be disabled for the event
3021 //______________________________________________________________________________
3022 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3023 if (event.target.tagName == "INPUT") {
3029 // gutterOffsetForIndex
3030 //______________________________________________________________________________
3032 // Returns the gutter offset for the spread containing the given index.
3033 // This function supports RTL
3034 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3036 // To find the offset of the gutter from the middle we calculate our percentage distance
3037 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3038 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3040 // But then again for RTL it's the opposite
3041 if ('rl' == this.pageProgression) {
3049 //______________________________________________________________________________
3050 // Returns the width of the leaf edge div for the page with index given
3051 BookReader.prototype.leafEdgeWidth = function(pindex) {
3052 // $$$ could there be single pixel rounding errors for L vs R?
3053 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3054 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3056 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3060 // jumpIndexForLeftEdgePageX
3061 //______________________________________________________________________________
3062 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3063 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3064 if ('rl' != this.pageProgression) {
3065 // LTR - flipping backward
3066 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3068 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3069 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3073 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3074 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3079 // jumpIndexForRightEdgePageX
3080 //______________________________________________________________________________
3081 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3082 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3083 if ('rl' != this.pageProgression) {
3085 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3086 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3089 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3090 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3095 BookReader.prototype.initToolbar = function(mode, ui) {
3097 $("#BookReader").append("<div id='BRtoolbar'>"
3098 + "<span id='BRtoolbarbuttons' style='float: right'>"
3099 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3100 + "<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>"
3101 + "<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>"
3102 + "<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>"
3103 + "<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>"
3104 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3108 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3109 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3110 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3111 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3112 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3113 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3114 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3117 + "<span id='#BRbooktitle'>"
3118 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3122 this.updateToolbarZoom(this.reduce); // Pretty format
3124 if (ui == "embed" || ui == "touch") {
3125 $("#BookReader a.logo").attr("target","_blank");
3128 // $$$ turn this into a member variable
3129 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3131 // We build in mode 2
3134 this.bindToolbarNavHandlers(jToolbar);
3136 // Setup tooltips -- later we could load these from a file for i18n
3137 var titles = { '.logo': 'Go to Archive.org',
3138 '.zoom_in': 'Zoom in',
3139 '.zoom_out': 'Zoom out',
3140 '.one_page_mode': 'One-page view',
3141 '.two_page_mode': 'Two-page view',
3142 '.thumbnail_mode': 'Thumbnail view',
3143 '.print': 'Print this page',
3144 '.embed': 'Embed bookreader',
3145 '.book_left': 'Flip left',
3146 '.book_right': 'Flip right',
3147 '.book_up': 'Page up',
3148 '.book_down': 'Page down',
3151 '.book_top': 'First page',
3152 '.book_bottom': 'Last page'
3154 if ('rl' == this.pageProgression) {
3155 titles['.book_leftmost'] = 'Last page';
3156 titles['.book_rightmost'] = 'First page';
3158 titles['.book_leftmost'] = 'First page';
3159 titles['.book_rightmost'] = 'Last page';
3162 for (var icon in titles) {
3163 jToolbar.find(icon).attr('title', titles[icon]);
3166 // Hide mode buttons and autoplay if 2up is not available
3167 // $$$ if we end up with more than two modes we should show the applicable buttons
3168 if ( !this.canSwitchToMode(this.constMode2up) ) {
3169 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3172 // Switch to requested mode -- binds other click handlers
3173 this.switchToolbarMode(mode);
3178 // switchToolbarMode
3179 //______________________________________________________________________________
3180 // Update the toolbar for the given mode (changes navigation buttons)
3181 // $$$ we should soon split the toolbar out into its own module
3182 BookReader.prototype.switchToolbarMode = function(mode) {
3185 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3186 $('#BRtoolbar .BRtoolbarmode2').hide();
3187 $('#BRtoolbar .BRtoolbarmode3').hide();
3188 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3189 } else if (2 == mode) {
3191 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3192 $('#BRtoolbar .BRtoolbarmode1').hide();
3193 $('#BRtoolbar .BRtoolbarmode3').hide();
3194 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3197 $('#BRtoolbar .BRtoolbarzoom').hide();
3198 $('#BRtoolbar .BRtoolbarmode2').hide();
3199 $('#BRtoolbar .BRtoolbarmode1').hide();
3200 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3204 // bindToolbarNavHandlers
3205 //______________________________________________________________________________
3206 // Binds the toolbar handlers
3207 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3209 var self = this; // closure
3211 jToolbar.find('.book_left').bind('click', function(e) {
3216 jToolbar.find('.book_right').bind('click', function(e) {
3221 jToolbar.find('.book_up').bind('click', function(e) {
3222 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3230 jToolbar.find('.book_down').bind('click', function(e) {
3231 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3239 jToolbar.find('.print').bind('click', function(e) {
3244 jToolbar.find('.embed').bind('click', function(e) {
3245 self.showEmbedCode();
3249 jToolbar.find('.play').bind('click', function(e) {
3254 jToolbar.find('.pause').bind('click', function(e) {
3259 jToolbar.find('.book_top').bind('click', function(e) {
3264 jToolbar.find('.book_bottom').bind('click', function(e) {
3269 jToolbar.find('.book_leftmost').bind('click', function(e) {
3274 jToolbar.find('.book_rightmost').bind('click', function(e) {
3280 // updateToolbarZoom(reduce)
3281 //______________________________________________________________________________
3282 // Update the displayed zoom factor based on reduction factor
3283 BookReader.prototype.updateToolbarZoom = function(reduce) {
3285 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3288 value = (100 / reduce).toFixed(2);
3289 // Strip trailing zeroes and decimal if all zeroes
3290 value = value.replace(/0+$/,'');
3291 value = value.replace(/\.$/,'');
3294 $('#BRzoom').text(value);
3297 // firstDisplayableIndex
3298 //______________________________________________________________________________
3299 // Returns the index of the first visible page, dependent on the mode.
3300 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3301 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3302 BookReader.prototype.firstDisplayableIndex = function() {
3303 if (this.mode != this.constMode2up) {
3307 if ('rl' != this.pageProgression) {
3309 if (this.getPageSide(0) == 'L') {
3316 if (this.getPageSide(0) == 'R') {
3324 // lastDisplayableIndex
3325 //______________________________________________________________________________
3326 // Returns the index of the last visible page, dependent on the mode.
3327 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3328 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3329 BookReader.prototype.lastDisplayableIndex = function() {
3331 var lastIndex = this.numLeafs - 1;
3333 if (this.mode != this.constMode2up) {
3337 if ('rl' != this.pageProgression) {
3339 if (this.getPageSide(lastIndex) == 'R') {
3342 return lastIndex + 1;
3346 if (this.getPageSide(lastIndex) == 'L') {
3349 return lastIndex + 1;
3354 // shortTitle(maximumCharacters)
3356 // Returns a shortened version of the title with the maximum number of characters
3357 BookReader.prototype.shortTitle = function(maximumCharacters) {
3358 if (this.bookTitle.length < maximumCharacters) {
3359 return this.bookTitle;
3362 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3367 // Parameter related functions
3369 // updateFromParams(params)
3371 // Update ourselves from the params object.
3373 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3374 BookReader.prototype.updateFromParams = function(params) {
3375 if ('undefined' != typeof(params.mode)) {
3376 this.switchMode(params.mode);
3380 if ('undefined' != typeof(params.searchTerm)) {
3381 if (this.searchTerm != params.searchTerm) {
3382 this.search(params.searchTerm);
3386 // $$$ process /zoom
3388 // We only respect page if index is not set
3389 if ('undefined' != typeof(params.index)) {
3390 if (params.index != this.currentIndex()) {
3391 this.jumpToIndex(params.index);
3393 } else if ('undefined' != typeof(params.page)) {
3394 // $$$ this assumes page numbers are unique
3395 if (params.page != this.getPageNum(this.currentIndex())) {
3396 this.jumpToPage(params.page);
3400 // $$$ process /region
3401 // $$$ process /highlight
3404 // paramsFromFragment(urlFragment)
3406 // Returns a object with configuration parametes from a URL fragment.
3408 // E.g paramsFromFragment(window.location.hash)
3409 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3410 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3414 // For convenience we allow an initial # character (as from window.location.hash)
3415 // but don't require it
3416 if (urlFragment.substr(0,1) == '#') {
3417 urlFragment = urlFragment.substr(1);
3420 // Simple #nn syntax
3421 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3422 if ( !isNaN(oldStyleLeafNum) ) {
3423 params.index = oldStyleLeafNum;
3425 // Done processing if using old-style syntax
3429 // Split into key-value pairs
3430 var urlArray = urlFragment.split('/');
3432 for (var i = 0; i < urlArray.length; i += 2) {
3433 urlHash[urlArray[i]] = urlArray[i+1];
3437 if ('1up' == urlHash['mode']) {
3438 params.mode = this.constMode1up;
3439 } else if ('2up' == urlHash['mode']) {
3440 params.mode = this.constMode2up;
3441 } else if ('thumb' == urlHash['mode']) {
3442 params.mode = this.constModeThumb;
3446 if ('undefined' != typeof(urlHash['page'])) {
3447 // page was set -- may not be int
3448 params.page = urlHash['page'];
3451 // $$$ process /region
3452 // $$$ process /search
3454 if (urlHash['search'] != undefined) {
3455 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3458 // $$$ process /highlight
3463 // paramsFromCurrent()
3465 // Create a params object from the current parameters.
3466 BookReader.prototype.paramsFromCurrent = function() {
3470 var index = this.currentIndex();
3471 var pageNum = this.getPageNum(index);
3472 if ((pageNum === 0) || pageNum) {
3473 params.page = pageNum;
3476 params.index = index;
3477 params.mode = this.mode;
3483 if (this.searchHighlightVisible()) {
3484 params.searchTerm = this.searchTerm;
3490 // fragmentFromParams(params)
3492 // Create a fragment string from the params object.
3493 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3494 BookReader.prototype.fragmentFromParams = function(params) {
3495 var separator = '/';
3499 if ('undefined' != typeof(params.page)) {
3500 fragments.push('page', params.page);
3502 // Don't have page numbering -- use index instead
3503 fragments.push('page', 'n' + params.index);
3510 if ('undefined' != typeof(params.mode)) {
3511 if (params.mode == this.constMode1up) {
3512 fragments.push('mode', '1up');
3513 } else if (params.mode == this.constMode2up) {
3514 fragments.push('mode', '2up');
3515 } else if (params.mode == this.constModeThumb) {
3516 fragments.push('mode', 'thumb');
3518 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3523 if (params.searchTerm) {
3524 fragments.push('search', params.searchTerm);
3527 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3530 // getPageIndex(pageNum)
3532 // Returns the *highest* index the given page number, or undefined
3533 BookReader.prototype.getPageIndex = function(pageNum) {
3534 var pageIndices = this.getPageIndices(pageNum);
3536 if (pageIndices.length > 0) {
3537 return pageIndices[pageIndices.length - 1];
3543 // getPageIndices(pageNum)
3545 // Returns an array (possibly empty) of the indices with the given page number
3546 BookReader.prototype.getPageIndices = function(pageNum) {
3549 // Check for special "nXX" page number
3550 if (pageNum.slice(0,1) == 'n') {
3552 var pageIntStr = pageNum.slice(1, pageNum.length);
3553 var pageIndex = parseInt(pageIntStr);
3554 indices.push(pageIndex);
3557 // Do nothing... will run through page names and see if one matches
3562 for (i=0; i<this.numLeafs; i++) {
3563 if (this.getPageNum(i) == pageNum) {
3571 // getPageName(index)
3573 // Returns the name of the page as it should be displayed in the user interface
3574 BookReader.prototype.getPageName = function(index) {
3575 return 'Page ' + this.getPageNum(index);
3578 // updateLocationHash
3580 // Update the location hash from the current parameters. Call this instead of manually
3581 // using window.location.replace
3582 BookReader.prototype.updateLocationHash = function() {
3583 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3584 window.location.replace(newHash);
3586 // This is the variable checked in the timer. Only user-generated changes
3587 // to the URL will trigger the event.
3588 this.oldLocationHash = newHash;
3591 // startLocationPolling
3593 // Starts polling of window.location to see hash fragment changes
3594 BookReader.prototype.startLocationPolling = function() {
3595 var self = this; // remember who I am
3596 self.oldLocationHash = window.location.hash;
3598 if (this.locationPollId) {
3599 clearInterval(this.locationPollID);
3600 this.locationPollId = null;
3603 this.locationPollId = setInterval(function() {
3604 var newHash = window.location.hash;
3605 if (newHash != self.oldLocationHash) {
3606 if (newHash != self.oldUserHash) { // Only process new user hash once
3607 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3609 // Queue change if animating
3610 if (self.animating) {
3612 self.animationFinishedCallback = function() {
3613 self.updateFromParams(self.paramsFromFragment(newHash));
3615 } else { // update immediately
3616 self.updateFromParams(self.paramsFromFragment(newHash));
3618 self.oldUserHash = newHash;
3626 // Returns true if we can switch to the requested mode
3627 BookReader.prototype.canSwitchToMode = function(mode) {
3628 if (mode == this.constMode2up) {
3629 // check there are enough pages to display
3630 // $$$ this is a workaround for the mis-feature that we can't display
3631 // short books in 2up mode
3632 if (this.numLeafs < 6) {
3640 // searchHighlightVisible
3642 // Returns true if a search highlight is currently being displayed
3643 BookReader.prototype.searchHighlightVisible = function() {
3644 if (this.constMode2up == this.mode) {
3645 if (this.searchResults[this.twoPage.currentIndexL]
3646 || this.searchResults[this.twoPage.currentIndexR]) {
3650 if (this.searchResults[this.currentIndex()]) {
3657 // getPageBackgroundColor
3659 // Returns a CSS property string for the background color for the given page
3660 // $$$ turn into regular CSS?
3661 BookReader.prototype.getPageBackgroundColor = function(index) {
3662 if (index >= 0 && index < this.numLeafs) {
3664 return this.pageDefaultBackgroundColor;
3672 // Returns the page width for the given index, or first or last page if out of range
3673 BookReader.prototype._getPageWidth = function(index) {
3674 // Synthesize a page width for pages not actually present in book.
3675 // May or may not be the best approach.
3676 // If index is out of range we return the width of first or last page
3677 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3678 return this.getPageWidth(index);
3683 // Returns the page height for the given index, or first or last page if out of range
3684 BookReader.prototype._getPageHeight= function(index) {
3685 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3686 return this.getPageHeight(index);
3691 // Returns the page URI or transparent image if out of range
3692 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3693 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3694 return this.imagesBaseURL + "/transparent.png";
3697 if ('undefined' == typeof(reduce)) {
3698 // reduce not passed in
3699 // $$$ this probably won't work for thumbnail mode
3700 var ratio = this.getPageHeight(index) / this.twoPage.height;
3702 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3705 } else if (ratio < 4) {
3707 } else if (ratio < 8) {
3709 } else if (ratio < 16) {
3711 } else if (ratio < 32) {
3719 return this.getPageURI(index, reduce, rotate);
3722 // Library functions
3724 disableSelect: function(jObject) {
3725 // Bind mouse handlers
3726 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3727 jObject.bind('mousedown', function(e) {
3728 // $$$ check here for right-click and don't disable. Also use jQuery style
3729 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3732 // Special hack for IE7
3733 jObject[0].onselectstart = function(e) { return false; };
3736 clamp: function(value, min, max) {
3737 return Math.min(Math.max(value, min), max);
3740 notInArray: function(value, array) {
3741 // inArray returns -1 or undefined if value not in array
3742 return ! (jQuery.inArray(value, array) >= 0);
3745 getIFrameDocument: function(iframe) {
3746 // Adapted from http://xkr.us/articles/dom/iframe-document/
3747 var outer = (iframe.contentWindow || iframe.contentDocument);
3748 return (outer.document || outer);
3751 decodeURIComponentPlus: function(value) {
3752 // Decodes a URI component and converts '+' to ' '
3753 return decodeURIComponent(value).replace(/\+/g, ' ');
3756 encodeURIComponentPlus: function(value) {
3757 // Encodes a URI component and converts ' ' to '+'
3758 return encodeURIComponent(value).replace(/%20/g, '+');
3760 // The final property here must NOT have a comma after it - IE7