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 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
88 // Object to hold parameters related to 2up mode
90 coverInternalPadding: 10, // Width of cover
91 coverExternalPadding: 10, // Padding outside of cover
92 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
96 // Background color for pages (e.g. when loading page image)
97 // $$$ TODO dynamically calculate based on page images
98 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
104 //______________________________________________________________________________
105 BookReader.prototype.init = function() {
107 var startIndex = undefined;
108 this.pageScale = this.reduce; // preserve current reduce
110 // Find start index and mode if set in location hash
111 var params = this.paramsFromFragment(window.location.hash);
113 if ('undefined' != typeof(params.index)) {
114 startIndex = params.index;
115 } else if ('undefined' != typeof(params.page)) {
116 startIndex = this.getPageIndex(params.page);
119 if ('undefined' == typeof(startIndex)) {
120 if ('undefined' != typeof(this.titleLeaf)) {
121 startIndex = this.leafNumToIndex(this.titleLeaf);
125 if ('undefined' == typeof(startIndex)) {
129 if ('undefined' != typeof(params.mode)) {
130 this.mode = params.mode;
133 // Set document title -- may have already been set in enclosing html for
134 // search engine visibility
135 document.title = this.shortTitle(50);
137 // Sanitize parameters
138 if ( !this.canSwitchToMode( this.mode ) ) {
139 this.mode = this.constMode1up;
142 $("#BookReader").empty();
143 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
144 $("#BookReader").append("<div id='BRcontainer'></div>");
145 $("#BRcontainer").append("<div id='BRpageview'></div>");
147 $("#BRcontainer").bind('scroll', this, function(e) {
151 this.setupKeyListeners();
152 this.startLocationPolling();
154 $(window).bind('resize', this, function(e) {
155 //console.log('resize!');
156 if (1 == e.data.mode) {
157 //console.log('centering 1page view');
158 e.data.centerPageView();
159 $('#BRpageview').empty()
160 e.data.displayedIndices = [];
161 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
163 } else if (3 == e.data.mode){
164 e.data.prepareThumbnailView();
166 //console.log('drawing 2 page view');
168 // We only need to prepare again in autofit (size of spread changes)
169 if (e.data.twoPage.autofit) {
170 e.data.prepareTwoPageView();
172 // Re-center if the scrollbars have disappeared
173 var center = e.data.twoPageGetViewCenter();
174 var doRecenter = false;
175 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
176 center.percentageX = 0.5;
179 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
180 center.percentageY = 0.5;
184 e.data.twoPageCenterView(center.percentageX, center.percentageY);
190 $('.BRpagediv1up').bind('mousedown', this, function(e) {
191 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
192 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
196 if (1 == this.mode) {
197 this.resizePageView();
198 this.firstIndex = startIndex;
199 this.jumpToIndex(startIndex);
200 } else if (3 == this.mode) {
201 this.firstIndex = startIndex;
202 this.prepareThumbnailView();
203 this.jumpToIndex(startIndex);
205 //this.resizePageView();
207 this.displayedIndices=[0];
208 this.firstIndex = startIndex;
209 this.displayedIndices = [this.firstIndex];
210 //console.log('titleLeaf: %d', this.titleLeaf);
211 //console.log('displayedIndices: %s', this.displayedIndices);
212 this.prepareTwoPageView();
215 // Enact other parts of initial params
216 this.updateFromParams(params);
219 BookReader.prototype.setupKeyListeners = function() {
232 // We use document here instead of window to avoid a bug in jQuery on IE7
233 $(document).keydown(function(e) {
235 // Keyboard navigation
236 if (!self.keyboardNavigationIsDisabled(e)) {
240 // In 1up mode page scrolling is handled by browser
241 if (2 == self.mode) {
248 if (2 == self.mode) {
262 if (2 == self.mode) {
268 if (2 == self.mode) {
279 //______________________________________________________________________________
280 BookReader.prototype.drawLeafs = function() {
281 if (1 == this.mode) {
282 this.drawLeafsOnePage();
283 } else if(3 == this.mode) {
284 this.drawLeafsThumbnail();
286 this.drawLeafsTwoPage();
291 //______________________________________________________________________________
292 BookReader.prototype.setDragHandler = function(div) {
293 div.dragging = false;
295 $(div).unbind('mousedown').bind('mousedown', function(e) {
298 //console.log('mousedown at ' + e.pageY);
300 this.dragging = true;
301 this.prevMouseX = e.pageX;
302 this.prevMouseY = e.pageY;
304 var startX = e.pageX;
305 var startY = e.pageY;
306 var startTop = $('#BRcontainer').attr('scrollTop');
307 var startLeft = $('#BRcontainer').attr('scrollLeft');
311 $(div).unbind('mousemove').bind('mousemove', function(ee) {
314 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
316 var offsetX = ee.pageX - this.prevMouseX;
317 var offsetY = ee.pageY - this.prevMouseY;
320 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
321 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
324 this.prevMouseX = ee.pageX;
325 this.prevMouseY = ee.pageY;
329 $(div).unbind('mouseup').bind('mouseup', function(ee) {
331 //console.log('mouseup');
333 this.dragging = false;
336 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
338 //console.log('mouseleave');
340 this.dragging = false;
343 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
345 //console.log('mouseenter');
347 this.dragging = false;
351 // setDragHandler2UP()
352 //______________________________________________________________________________
353 BookReader.prototype.setDragHandler2UP = function(div) {
354 div.dragging = false;
356 $(div).unbind('mousedown').bind('mousedown', function(e) {
359 //console.log('mousedown at ' + e.pageY);
361 this.dragStart = {x: e.pageX, y: e.pageY };
362 this.mouseDown = true;
363 this.dragging = false; // wait until drag distance
364 this.prevMouseX = e.pageX;
365 this.prevMouseY = e.pageY;
367 var startX = e.pageX;
368 var startY = e.pageY;
369 var startTop = $('#BRcontainer').attr('scrollTop');
370 var startLeft = $('#BRcontainer').attr('scrollLeft');
374 $(div).unbind('mousemove').bind('mousemove', function(ee) {
377 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
379 var offsetX = ee.pageX - this.prevMouseX;
380 var offsetY = ee.pageY - this.prevMouseY;
382 var minDragDistance = 5; // $$$ constant
384 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
386 if (this.mouseDown && (distance > minDragDistance)) {
387 //console.log('drag start!');
389 this.dragging = true;
393 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
394 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
395 this.prevMouseX = ee.pageX;
396 this.prevMouseY = ee.pageY;
403 $(div).unbind('mouseup').bind('mouseup', function(ee) {
405 //console.log('mouseup');
407 this.dragging = false;
408 this.mouseDown = false;
413 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
415 //console.log('mouseleave');
417 this.dragging = false;
418 this.mouseDown = false;
421 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
423 //console.log('mouseenter');
425 this.dragging = false;
426 this.mouseDown = false;
430 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
431 //console.log('setting handler');
432 //console.log(element.tagName);
434 $(element).unbind('click').bind('click', data, function(e) {
437 //console.log('click!');
439 if (this.mouseDown && (!this.dragging)) {
440 //console.log('click not dragging!');
444 this.dragging = false;
445 this.mouseDown = false;
449 // drawLeafsOnePage()
450 //______________________________________________________________________________
451 BookReader.prototype.drawLeafsOnePage = function() {
452 //alert('drawing leafs!');
456 var scrollTop = $('#BRcontainer').attr('scrollTop');
457 var scrollBottom = scrollTop + $('#BRcontainer').height();
458 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
460 var indicesToDisplay = [];
465 for (i=0; i<this.numLeafs; i++) {
466 var height = parseInt(this._getPageHeight(i)/this.reduce);
468 leafBottom += height;
469 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
470 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
471 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
472 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
473 if (topInView | bottomInView | middleInView) {
474 //console.log('displayed: ' + this.displayedIndices);
475 //console.log('to display: ' + i);
476 indicesToDisplay.push(i);
478 leafTop += height +10;
482 var firstIndexToDraw = indicesToDisplay[0];
483 this.firstIndex = firstIndexToDraw;
485 // Update hash, but only if we're currently displaying a leaf
486 // Hack that fixes #365790
487 if (this.displayedIndices.length > 0) {
488 this.updateLocationHash();
491 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
493 indicesToDisplay.unshift(firstIndexToDraw);
496 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
497 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
498 indicesToDisplay.push(lastIndexToDraw+1);
503 for (i=0; i<firstIndexToDraw; i++) {
504 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
507 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
508 var viewWidth = $('#BRcontainer').attr('scrollWidth');
511 for (i=0; i<indicesToDisplay.length; i++) {
512 var index = indicesToDisplay[i];
513 var height = parseInt(this._getPageHeight(index)/this.reduce);
515 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
516 var width = parseInt(this._getPageWidth(index)/this.reduce);
517 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
518 var div = document.createElement("div");
519 div.className = 'BRpagediv1up';
520 div.id = 'pagediv'+index;
521 div.style.position = "absolute";
522 $(div).css('top', leafTop + 'px');
523 var left = (viewWidth-width)>>1;
524 if (left<0) left = 0;
525 $(div).css('left', left+'px');
526 $(div).css('width', width+'px');
527 $(div).css('height', height+'px');
528 //$(div).text('loading...');
530 this.setDragHandler(div);
532 $('#BRpageview').append(div);
534 var img = document.createElement("img");
535 img.src = this._getPageURI(index, this.reduce, 0);
536 $(img).css('width', width+'px');
537 $(img).css('height', height+'px');
541 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
544 leafTop += height +10;
548 for (i=0; i<this.displayedIndices.length; i++) {
549 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
550 var index = this.displayedIndices[i];
551 //console.log('Removing leaf ' + index);
552 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
553 $('#pagediv'+index).remove();
555 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
559 this.displayedIndices = indicesToDisplay.slice();
560 this.updateSearchHilites();
562 if (null != this.getPageNum(firstIndexToDraw)) {
563 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
565 $("#BRpagenum").val('');
568 this.updateToolbarZoom(this.reduce);
572 // drawLeafsThumbnail()
573 //______________________________________________________________________________
574 BookReader.prototype.drawLeafsThumbnail = function() {
575 //alert('drawing leafs!');
578 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
580 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
592 for (i=0; i<this.numLeafs; i++) {
593 leafWidth = this.thumbWidth;
594 if (rightPos + (leafWidth + this.padding) > viewWidth){
600 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
601 if (leafMap[currentRow].leafs===undefined) {
602 leafMap[currentRow].leafs = [];
603 leafMap[currentRow].height = 0;
604 leafMap[currentRow].top = 0;
606 leafMap[currentRow].leafs[leafIndex] = {};
607 leafMap[currentRow].leafs[leafIndex].num = i;
608 leafMap[currentRow].leafs[leafIndex].left = rightPos;
610 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
611 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
612 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
613 rightPos += leafWidth + this.padding;
614 if (rightPos > maxRight) { maxRight = rightPos; }
618 // reset the bottom position based on thumbnails
619 $('#BRpageview').height(bottomPos);
621 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
622 var scrollTop = $('#BRcontainer').attr('scrollTop');
623 var scrollBottom = scrollTop + $('#BRcontainer').height();
627 var rowsToDisplay = [];
629 for (i=0; i<leafMap.length; i++) {
630 leafBottom += this.padding + leafMap[i].height;
631 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
632 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
633 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
634 if (topInView | bottomInView | middleInView) {
635 //console.log('row to display: ' + j);
636 rowsToDisplay.push(i);
638 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
639 leafTop = leafBottom;
642 // create a buffer of preloaded rows before and after the visible rows
643 var firstRow = rowsToDisplay[0];
644 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
645 for (i=1; i<this.thumbRowBuffer+1; i++) {
646 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
648 for (i=1; i<this.thumbRowBuffer+1; i++) {
649 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
652 // Update hash, but only if we're currently displaying a leaf
653 // Hack that fixes #365790
654 if (this.displayedRows.length > 0) {
655 this.updateLocationHash();
666 for (i=0; i<rowsToDisplay.length; i++) {
667 if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {
668 row = rowsToDisplay[i];
670 for (j=0; j<leafMap[row].leafs.length; j++) {
672 leaf = leafMap[row].leafs[j].num;
674 leafWidth = this.thumbWidth;
675 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
676 leafTop = leafMap[row].top;
677 left = leafMap[row].leafs[index].left + pageViewBuffer;
678 if ('rl' == this.pageProgression){
679 left = viewWidth - leafWidth - left;
682 div = document.createElement("div");
683 div.id = 'pagediv'+leaf;
684 div.style.position = "absolute";
685 div.className = "BRpagedivthumb";
687 left += this.padding;
688 $(div).css('top', leafTop + 'px');
689 $(div).css('left', left+'px');
690 $(div).css('width', leafWidth+'px');
691 $(div).css('height', leafHeight+'px');
692 //$(div).text('loading...');
694 // link to page in single page mode
695 // $$$ direct JS calls instead should reduce visual disruption
696 link = document.createElement("a");
697 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
700 $('#BRpageview').append(div);
702 img = document.createElement("img");
703 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
705 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
706 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
707 .addClass('BRlazyload')
708 // Store the URL of the image that will replace this one
709 .data('srcURL', this._getPageURI(leaf, thumbReduce));
711 //console.log('displaying thumbnail: ' + leaf);
716 // remove previous highlights
717 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
719 // highlight current page
720 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
723 for (i=0; i<this.displayedRows.length; i++) {
724 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
725 row = this.displayedRows[i];
727 // $$$ Safari doesn't like the comprehension
728 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
729 //console.log('Removing row ' + row + ' ' + rowLeafs);
731 for (k=0; k<leafMap[row].leafs.length; k++) {
732 index = leafMap[row].leafs[k].num;
733 //console.log('Removing leaf ' + index);
734 $('#pagediv'+index).remove();
738 var mRow = this.displayedRows[i];
739 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
740 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
745 this.displayedRows = rowsToDisplay.slice();
747 this.lazyLoadThumbnails();
749 if (null !== this.getPageNum(this.currentIndex())) {
750 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
752 $("#BRpagenum").val('');
755 this.updateToolbarZoom(this.reduce);
758 BookReader.prototype.lazyLoadThumbnails = function() {
760 // console.log('lazy load');
762 // We check the complete property since load may not be fired if loading from the cache
763 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
765 var loading = $('.BRlazyloading').length;
766 var toLoad = this.thumbMaxLoading - loading;
768 // console.log(' ' + loading + ' thumbnails loading');
769 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
774 // $$$ TODO load those near top (but not beyond) page view first
775 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
776 self.lazyLoadImage(this);
781 BookReader.prototype.lazyLoadImage = function (dummyImage) {
782 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
784 var img = new Image();
788 .addClass('BRlazyloading')
789 .one('load', function() {
790 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
792 $(this).removeClass('BRlazyloading');
794 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
795 // we call the function after a slight delay. Also the img.complete property
796 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
798 .one('error', function() {
799 // Remove class so we no longer count as loading
800 $(this).removeClass('BRlazyloading');
802 .attr( { width: $(dummyImage).width(),
803 height: $(dummyImage).height(),
804 src: $(dummyImage).data('srcURL')
807 // replace with the new img
808 $(dummyImage).before(img).remove();
810 img = null; // tidy up closure
814 // drawLeafsTwoPage()
815 //______________________________________________________________________________
816 BookReader.prototype.drawLeafsTwoPage = function() {
817 var scrollTop = $('#BRtwopageview').attr('scrollTop');
818 var scrollBottom = scrollTop + $('#BRtwopageview').height();
820 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
822 var indexL = this.twoPage.currentIndexL;
824 var heightL = this._getPageHeight(indexL);
825 var widthL = this._getPageWidth(indexL);
827 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
828 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
829 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
830 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
831 //console.log(leafEdgeWidthL);
833 var middle = this.twoPage.middle; // $$$ getter instead?
834 var top = this.twoPageTop();
835 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
837 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
838 this.twoPage.gutter = this.twoPageGutter();
840 this.prefetchImg(indexL);
841 $(this.prefetchedImgs[indexL]).css({
842 position: 'absolute',
843 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
846 backgroundColor: this.getPageBackgroundColor(indexL),
847 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
848 width: this.twoPage.scaledWL + 'px',
849 borderRight: '1px solid black',
851 }).appendTo('#BRtwopageview');
853 var indexR = this.twoPage.currentIndexR;
854 var heightR = this._getPageHeight(indexR);
855 var widthR = this._getPageWidth(indexR);
857 // $$$ should use getwidth2up?
858 //var scaledWR = this.twoPage.height*widthR/heightR;
859 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
860 this.prefetchImg(indexR);
861 $(this.prefetchedImgs[indexR]).css({
862 position: 'absolute',
863 left: this.twoPage.gutter+'px',
866 backgroundColor: this.getPageBackgroundColor(indexR),
867 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
868 width: this.twoPage.scaledWR + 'px',
869 borderLeft: '1px solid black',
871 }).appendTo('#BRtwopageview');
874 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
875 this.setMouseHandlers2UP();
876 this.twoPageSetCursor();
878 this.updatePageNumBox2UP();
879 this.updateToolbarZoom(this.reduce);
881 // this.twoPagePlaceFlipAreas(); // No longer used
885 // updatePageNumBox2UP
886 //______________________________________________________________________________
887 BookReader.prototype.updatePageNumBox2UP = function() {
888 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
889 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
891 $("#BRpagenum").val('');
893 this.updateLocationHash();
897 //______________________________________________________________________________
898 BookReader.prototype.loadLeafs = function() {
902 if (null == this.timer) {
903 this.timer=setTimeout(function(){self.drawLeafs()},250);
905 clearTimeout(this.timer);
906 this.timer=setTimeout(function(){self.drawLeafs()},250);
912 // Pass 1 to zoom in, anything else to zoom out
913 //______________________________________________________________________________
914 BookReader.prototype.zoom = function(direction) {
916 case this.constMode1up:
917 return this.zoom1up(direction);
918 case this.constMode2up:
919 return this.zoom2up(direction);
920 case this.constModeThumb:
921 return this.zoomThumb(direction);
926 //______________________________________________________________________________
927 BookReader.prototype.zoom1up = function(dir) {
929 if (2 == this.mode) { //can only zoom in 1-page mode
934 // $$$ with flexible zoom we could "snap" to /2 page reductions
935 // for better scaling
937 if (this.reduce <= 0.5) return;
938 this.reduce*=0.5; //zoom in
940 if (this.reduce >= 8) return;
941 this.reduce*=2; //zoom out
944 this.pageScale = this.reduce; // preserve current reduce
945 this.resizePageView();
947 $('#BRpageview').empty()
948 this.displayedIndices = [];
951 this.updateToolbarZoom(this.reduce);
953 // Recalculate search hilites
954 this.removeSearchHilites();
955 this.updateSearchHilites();
960 //______________________________________________________________________________
961 BookReader.prototype.resizePageView = function() {
964 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
965 var viewWidth = $('#BRcontainer').attr('clientWidth');
967 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
968 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
969 var oldPageViewHeight = $('#BRpageview').height();
970 var oldPageViewWidth = $('#BRpageview').width();
972 var oldCenterY = this.centerY1up();
973 var oldCenterX = this.centerX1up();
975 if (0 != oldPageViewHeight) {
976 var scrollRatio = oldCenterY / oldPageViewHeight;
981 for (i=0; i<this.numLeafs; i++) {
982 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
983 var width = parseInt(this._getPageWidth(i)/this.reduce);
984 if (width>viewWidth) viewWidth=width;
986 $('#BRpageview').height(viewHeight);
987 $('#BRpageview').width(viewWidth);
989 var newCenterY = scrollRatio*viewHeight;
990 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
991 $('#BRcontainer').attr('scrollTop', newTop);
993 // We use clientWidth here to avoid miscalculating due to scroll bar
994 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
995 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
996 newLeft = Math.max(newLeft, 0);
997 $('#BRcontainer').attr('scrollLeft', newLeft);
998 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
1000 //this.centerPageView();
1003 // Not really needed until there is 1up autofit
1004 this.removeSearchHilites();
1005 this.updateSearchHilites();
1009 //______________________________________________________________________________
1010 // Returns the current offset of the viewport center in scaled document coordinates.
1011 BookReader.prototype.centerX1up = function() {
1013 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
1014 centerX = $('#BRpageview').width();
1016 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
1018 centerX = Math.floor(centerX);
1023 //______________________________________________________________________________
1024 // Returns the current offset of the viewport center in scaled document coordinates.
1025 BookReader.prototype.centerY1up = function() {
1026 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1027 return Math.floor(centerY);
1031 //______________________________________________________________________________
1032 BookReader.prototype.centerPageView = function() {
1034 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1035 var clientWidth = $('#BRcontainer').attr('clientWidth');
1036 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1037 if (scrollWidth > clientWidth) {
1038 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1043 // zoom2up(direction)
1044 //______________________________________________________________________________
1045 BookReader.prototype.zoom2up = function(direction) {
1047 // Hard stop autoplay
1048 this.stopFlipAnimations();
1050 // Get new zoom state
1051 var newZoom = this.twoPageNextReduce(this.reduce, direction);
1052 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
1055 this.twoPage.autofit = newZoom.autofit;
1056 this.reduce = newZoom.reduce;
1057 this.pageScale = this.reduce; // preserve current reduce
1059 // Preserve view center position
1060 var oldCenter = this.twoPageGetViewCenter();
1062 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1063 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1064 if (1 == direction) {
1065 for (var img in this.prefetchedImgs) {
1066 delete this.prefetchedImgs[img];
1070 // Prepare view with new center to minimize visual glitches
1071 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1074 BookReader.prototype.zoomThumb = function(direction) {
1075 var oldColumns = this.thumbColumns;
1076 switch (direction) {
1078 this.thumbColumns += 1;
1081 this.thumbColumns -= 1;
1086 if (this.thumbColumns < 2) {
1087 this.thumbColumns = 2;
1088 } else if (this.thumbColumns > 8) {
1089 this.thumbColumns = 8;
1092 if (this.thumbColumns != oldColumns) {
1093 this.prepareThumbnailView();
1094 this.jumpToIndex(this.currentIndex());
1098 // Returns the width per thumbnail to display the requested number of columns
1099 // Note: #BRpageview must already exist since its width is used to calculate the
1101 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1102 var padding = (thumbnailColumns + 1) * this.padding;
1103 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1104 return parseInt(width);
1107 // quantizeReduce(reduce)
1108 //______________________________________________________________________________
1109 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1110 BookReader.prototype.quantizeReduce = function(reduce) {
1111 var quantized = this.reductionFactors[0];
1112 var distance = Math.abs(reduce - quantized);
1113 for (var i = 1; i < this.reductionFactors.length; i++) {
1114 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1115 if (newDistance < distance) {
1116 distance = newDistance;
1117 quantized = this.reductionFactors[i];
1124 // twoPageNextReduce()
1125 //______________________________________________________________________________
1126 // Returns the next reduction level
1127 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1129 var autofitReduce = this.twoPageGetAutofitReduce();
1131 if (0 == direction) { // autofit
1132 result.autofit = true;
1133 result.reduce = autofitReduce;
1135 } else if (1 == direction) { // zoom in
1136 var newReduce = this.reductionFactors[0];
1138 for (var i = 1; i < this.reductionFactors.length; i++) {
1139 if (this.reductionFactors[i] < reduce) {
1140 newReduce = this.reductionFactors[i];
1144 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1146 result.autofit = true;
1147 result.reduce = autofitReduce;
1149 result.autofit = false;
1150 result.reduce = newReduce;
1153 } else { // zoom out
1154 var lastIndex = this.reductionFactors.length - 1;
1155 var newReduce = this.reductionFactors[lastIndex];
1157 for (var i = lastIndex; i >= 0; i--) {
1158 if (this.reductionFactors[i] > reduce) {
1159 newReduce = this.reductionFactors[i];
1163 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1165 result.autofit = true;
1166 result.reduce = autofitReduce;
1168 result.autofit = false;
1169 result.reduce = newReduce;
1177 //______________________________________________________________________________
1178 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1179 BookReader.prototype.jumpToPage = function(pageNum) {
1181 var pageIndex = this.getPageIndex(pageNum);
1183 if ('undefined' != typeof(pageIndex)) {
1186 this.jumpToIndex(pageIndex);
1187 $('#BRcontainer').attr('scrollTop', leafTop);
1196 //______________________________________________________________________________
1197 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1199 if (2 == this.mode) {
1202 // By checking against min/max we do nothing if requested index
1204 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1205 this.flipBackToIndex(index);
1206 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1207 this.flipFwdToIndex(index);
1210 } else if (3 == this.mode) {
1211 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1221 for (i=0; i<(index+1); i++) {
1222 leafWidth = this.thumbWidth;
1223 if (rightPos + (leafWidth + this.padding) > viewWidth){
1228 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1229 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1230 if (leafIndex==0) { leafTop = bottomPos; }
1231 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1232 rightPos += leafWidth + this.padding;
1235 this.firstIndex=index;
1236 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1239 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1246 for (i=0; i<index; i++) {
1247 h = parseInt(this._getPageHeight(i)/this.reduce);
1248 leafTop += h + this.padding;
1252 //console.log('pageY ' + pageY);
1253 var offset = parseInt( (pageY) / this.reduce);
1254 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1255 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1260 var offset = parseInt( (pageX) / this.reduce);
1261 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1265 //$('#BRcontainer').attr('scrollTop', leafTop);
1266 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1272 //______________________________________________________________________________
1273 BookReader.prototype.switchMode = function(mode) {
1275 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1277 if (mode == this.mode) {
1281 if (!this.canSwitchToMode(mode)) {
1286 this.removeSearchHilites();
1289 this.switchToolbarMode(mode);
1291 // reinstate scale if moving from thumbnail view
1292 if (this.pageScale != this.reduce) {
1293 this.reduce = this.pageScale;
1296 // $$$ TODO preserve center of view when switching between mode
1297 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1300 this.reduce = this.quantizeReduce(this.reduce);
1301 this.prepareOnePageView();
1302 } else if (3 == mode) {
1303 this.reduce = this.quantizeReduce(this.reduce);
1304 this.prepareThumbnailView();
1305 this.jumpToIndex(this.currentIndex());
1307 // $$$ why don't we save autofit?
1308 this.twoPage.autofit = false; // Take zoom level from other mode
1309 this.reduce = this.quantizeReduce(this.reduce);
1310 this.prepareTwoPageView();
1311 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1316 //prepareOnePageView()
1317 //______________________________________________________________________________
1318 BookReader.prototype.prepareOnePageView = function() {
1320 // var startLeaf = this.displayedIndices[0];
1321 var startLeaf = this.currentIndex();
1323 $('#BRcontainer').empty();
1324 $('#BRcontainer').css({
1325 overflowY: 'scroll',
1329 $("#BRcontainer").append("<div id='BRpageview'></div>");
1330 // $$$ keep select enabled for now since disabling it breaks keyboard
1331 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1332 // BookReader.util.disableSelect($('#BRpageview'));
1334 this.resizePageView();
1336 this.jumpToIndex(startLeaf);
1337 this.displayedIndices = [];
1339 this.drawLeafsOnePage();
1342 //prepareThumbnailView()
1343 //______________________________________________________________________________
1344 BookReader.prototype.prepareThumbnailView = function() {
1346 $('#BRcontainer').empty();
1347 $('#BRcontainer').css({
1348 overflowY: 'scroll',
1352 $("#BRcontainer").append("<div id='BRpageview'></div>");
1354 // $$$ keep select enabled for now since disabling it breaks keyboard
1355 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1356 // BookReader.util.disableSelect($('#BRpageview'));
1358 var startLeaf = this.currentIndex();
1359 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1360 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1362 this.resizePageView();
1364 this.displayedRows = [];
1365 this.drawLeafsThumbnail();
1368 // prepareTwoPageView()
1369 //______________________________________________________________________________
1370 // Some decisions about two page view:
1372 // Both pages will be displayed at the same height, even if they were different physical/scanned
1373 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1374 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1375 // aspect ratio to determine the height.
1377 // The two page view div is resized to keep the middle of the book in the middle of the div
1378 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1379 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1380 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1381 $('#BRcontainer').empty();
1382 $('#BRcontainer').css('overflow', 'auto');
1384 // We want to display two facing pages. We may be missing
1385 // one side of the spread because it is the first/last leaf,
1386 // foldouts, missing pages, etc
1388 //var targetLeaf = this.displayedIndices[0];
1389 var targetLeaf = this.firstIndex;
1391 if (targetLeaf < this.firstDisplayableIndex()) {
1392 targetLeaf = this.firstDisplayableIndex();
1395 if (targetLeaf > this.lastDisplayableIndex()) {
1396 targetLeaf = this.lastDisplayableIndex();
1399 //this.twoPage.currentIndexL = null;
1400 //this.twoPage.currentIndexR = null;
1401 //this.pruneUnusedImgs();
1403 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1404 this.twoPage.currentIndexL = currentSpreadIndices[0];
1405 this.twoPage.currentIndexR = currentSpreadIndices[1];
1406 this.firstIndex = this.twoPage.currentIndexL;
1408 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1410 this.pruneUnusedImgs();
1411 this.prefetch(); // Preload images or reload if scaling has changed
1413 //console.dir(this.twoPage);
1415 // Add the two page view
1416 // $$$ Can we get everything set up and then append?
1417 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1419 // $$$ calculate first then set
1420 $('#BRtwopageview').css( {
1421 height: this.twoPage.totalHeight + 'px',
1422 width: this.twoPage.totalWidth + 'px',
1423 position: 'absolute'
1426 // If there will not be scrollbars (e.g. when zooming out) we center the book
1427 // since otherwise the book will be stuck off-center
1428 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1429 centerPercentageX = 0.5;
1431 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1432 centerPercentageY = 0.5;
1435 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1437 this.twoPage.coverDiv = document.createElement('div');
1438 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1439 border: '1px solid rgb(68, 25, 17)',
1440 width: this.twoPage.bookCoverDivWidth + 'px',
1441 height: this.twoPage.bookCoverDivHeight+'px',
1442 visibility: 'visible',
1443 position: 'absolute',
1444 backgroundColor: '#663929',
1445 left: this.twoPage.bookCoverDivLeft + 'px',
1446 top: this.twoPage.bookCoverDivTop+'px',
1447 MozBorderRadiusTopleft: '7px',
1448 MozBorderRadiusTopright: '7px',
1449 MozBorderRadiusBottomright: '7px',
1450 MozBorderRadiusBottomleft: '7px'
1451 }).appendTo('#BRtwopageview');
1453 this.leafEdgeR = document.createElement('div');
1454 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1455 $(this.leafEdgeR).css({
1456 borderStyle: 'solid solid solid none',
1457 borderColor: 'rgb(51, 51, 34)',
1458 borderWidth: '1px 1px 1px 0px',
1459 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1460 width: this.twoPage.leafEdgeWidthR + 'px',
1461 height: this.twoPage.height-1 + 'px',
1463 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1464 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1465 position: 'absolute'
1466 }).appendTo('#BRtwopageview');
1468 this.leafEdgeL = document.createElement('div');
1469 this.leafEdgeL.className = 'leafEdgeL';
1470 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1471 borderStyle: 'solid none solid solid',
1472 borderColor: 'rgb(51, 51, 34)',
1473 borderWidth: '1px 0px 1px 1px',
1474 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1475 width: this.twoPage.leafEdgeWidthL + 'px',
1476 height: this.twoPage.height-1 + 'px',
1477 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1478 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1479 position: 'absolute'
1480 }).appendTo('#BRtwopageview');
1482 div = document.createElement('div');
1483 $(div).attr('id', 'BRbookspine').css({
1484 border: '1px solid rgb(68, 25, 17)',
1485 width: this.twoPage.bookSpineDivWidth+'px',
1486 height: this.twoPage.bookSpineDivHeight+'px',
1487 position: 'absolute',
1488 backgroundColor: 'rgb(68, 25, 17)',
1489 left: this.twoPage.bookSpineDivLeft+'px',
1490 top: this.twoPage.bookSpineDivTop+'px'
1491 }).appendTo('#BRtwopageview');
1493 var self = this; // for closure
1495 /* Flip areas no longer used
1496 this.twoPage.leftFlipArea = document.createElement('div');
1497 this.twoPage.leftFlipArea.className = 'BRfliparea';
1498 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1500 width: this.twoPageFlipAreaWidth() + 'px',
1501 height: this.twoPageFlipAreaHeight() + 'px',
1502 position: 'absolute',
1503 left: this.twoPageLeftFlipAreaLeft() + 'px',
1504 top: this.twoPageFlipAreaTop() + 'px',
1507 }).bind('click', function(e) {
1509 }).bind('mousedown', function(e) {
1511 }).appendTo('#BRtwopageview');
1513 this.twoPage.rightFlipArea = document.createElement('div');
1514 this.twoPage.rightFlipArea.className = 'BRfliparea';
1515 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1517 width: this.twoPageFlipAreaWidth() + 'px',
1518 height: this.twoPageFlipAreaHeight() + 'px',
1519 position: 'absolute',
1520 left: this.twoPageRightFlipAreaLeft() + 'px',
1521 top: this.twoPageFlipAreaTop() + 'px',
1524 }).bind('click', function(e) {
1526 }).bind('mousedown', function(e) {
1528 }).appendTo('#BRtwopageview');
1531 this.prepareTwoPagePopUp();
1533 this.displayedIndices = [];
1535 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1536 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1538 this.drawLeafsTwoPage();
1539 this.updateToolbarZoom(this.reduce);
1543 this.removeSearchHilites();
1544 this.updateSearchHilites();
1548 // prepareTwoPagePopUp()
1550 // This function prepares the "View Page n" popup that shows while the mouse is
1551 // over the left/right "stack of sheets" edges. It also binds the mouse
1552 // events for these divs.
1553 //______________________________________________________________________________
1554 BookReader.prototype.prepareTwoPagePopUp = function() {
1556 this.twoPagePopUp = document.createElement('div');
1557 $(this.twoPagePopUp).css({
1558 border: '1px solid black',
1560 position: 'absolute',
1561 fontFamily: 'sans-serif',
1564 backgroundColor: 'rgb(255, 255, 238)',
1566 }).appendTo('#BRcontainer');
1567 $(this.twoPagePopUp).hide();
1569 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1570 $(e.data.twoPagePopUp).show();
1573 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1574 $(e.data.twoPagePopUp).hide();
1577 $(this.leafEdgeL).bind('click', this, function(e) {
1579 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1580 e.data.jumpToIndex(jumpIndex);
1583 $(this.leafEdgeR).bind('click', this, function(e) {
1585 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1586 e.data.jumpToIndex(jumpIndex);
1589 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1591 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1592 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1594 // $$$ TODO: Make sure popup is positioned so that it is in view
1595 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1596 $(e.data.twoPagePopUp).css({
1597 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1598 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1602 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1604 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1605 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1607 // $$$ TODO: Make sure popup is positioned so that it is in view
1608 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1609 $(e.data.twoPagePopUp).css({
1610 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1611 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1616 // calculateSpreadSize()
1617 //______________________________________________________________________________
1618 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1619 // this.twoPage.currentIndexR
1620 // This function sets this.twoPage.height, twoPage.width
1622 BookReader.prototype.calculateSpreadSize = function() {
1624 var firstIndex = this.twoPage.currentIndexL;
1625 var secondIndex = this.twoPage.currentIndexR;
1626 //console.log('first page is ' + firstIndex);
1628 // Calculate page sizes and total leaf width
1630 if ( this.twoPage.autofit) {
1631 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1633 // set based on reduction factor
1634 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1637 // Both pages together
1638 this.twoPage.height = spreadSize.height;
1639 this.twoPage.width = spreadSize.width;
1642 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1643 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1646 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1647 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1648 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1652 // The width of the book cover div. The combined width of both pages, twice the width
1653 // of the book cover internal padding (2*10) and the page edges
1654 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1655 // The height of the book cover div
1656 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1659 // We calculate the total width and height for the div so that we can make the book
1661 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1662 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1663 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1664 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1665 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1666 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1668 // We want to minimize the unused space in two-up mode (maximize the amount of page
1669 // shown). We give width to the leaf edges and these widths change (though the sum
1670 // of the two remains constant) as we flip through the book. With the book
1671 // cover centered and fixed in the BRcontainer div the page images will meet
1672 // at the "gutter" which is generally offset from the center.
1673 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1674 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1676 // The left edge of the book cover moves depending on the width of the pages
1677 // $$$ change to getter
1678 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1679 // The top edge of the book cover stays a fixed distance from the top
1680 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1683 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1684 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1685 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1688 this.reduce = spreadSize.reduce; // $$$ really set this here?
1691 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1694 // We check which page is closest to a "normal" page and use that to set the height
1695 // for both pages. This means that foldouts and other odd size pages will be displayed
1696 // smaller than the nominal zoom amount.
1697 var canon5Dratio = 1.5;
1700 height: this._getPageHeight(firstIndex),
1701 width: this._getPageWidth(firstIndex)
1705 height: this._getPageHeight(secondIndex),
1706 width: this._getPageWidth(secondIndex)
1709 var firstIndexRatio = first.height / first.width;
1710 var secondIndexRatio = second.height / second.width;
1711 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1714 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1715 ratio = firstIndexRatio;
1716 //console.log('using firstIndexRatio ' + ratio);
1718 ratio = secondIndexRatio;
1719 //console.log('using secondIndexRatio ' + ratio);
1722 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1723 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1724 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1726 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1727 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1729 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1730 ideal.width -= 10; // $$$ fudge factor
1731 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1732 ideal.height -= 20; // fudge factor
1733 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1735 if (ideal.height/ratio <= ideal.width) {
1737 ideal.width = parseInt(ideal.height/ratio);
1740 ideal.height = parseInt(ideal.width*ratio);
1743 // $$$ check this logic with large spreads
1744 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1749 // getSpreadSizeFromReduce()
1750 //______________________________________________________________________________
1751 // Returns the spread size calculated from the reduction factor for the given pages
1752 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1753 var spreadSize = {};
1754 // $$$ Scale this based on reduce?
1755 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1756 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1757 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1759 // $$$ Possibly incorrect -- we should make height "dominant"
1760 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1761 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1762 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1763 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1764 spreadSize.reduce = reduce;
1769 // twoPageGetAutofitReduce()
1770 //______________________________________________________________________________
1771 // Returns the current ideal reduction factor
1772 BookReader.prototype.twoPageGetAutofitReduce = function() {
1773 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1774 return spreadSize.reduce;
1777 // twoPageSetCursor()
1778 //______________________________________________________________________________
1779 // Set the cursor for two page view
1780 BookReader.prototype.twoPageSetCursor = function() {
1781 // console.log('setting cursor');
1782 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1783 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1784 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1785 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1787 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1788 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1793 //______________________________________________________________________________
1794 // Returns the currently active index.
1795 BookReader.prototype.currentIndex = function() {
1796 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1797 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1798 return this.firstIndex; // $$$ TODO page in center of view would be better
1799 } else if (this.mode == this.constMode2up) {
1800 // Only allow indices that are actually present in book
1801 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1803 throw 'currentIndex called for unimplemented mode ' + this.mode;
1808 //______________________________________________________________________________
1809 // Flip the right page over onto the left
1810 BookReader.prototype.right = function() {
1811 if ('rl' != this.pageProgression) {
1821 //______________________________________________________________________________
1822 // Flip to the rightmost page
1823 BookReader.prototype.rightmost = function() {
1824 if ('rl' != this.pageProgression) {
1832 //______________________________________________________________________________
1833 // Flip the left page over onto the right.
1834 BookReader.prototype.left = function() {
1835 if ('rl' != this.pageProgression) {
1845 //______________________________________________________________________________
1846 // Flip to the leftmost page
1847 BookReader.prototype.leftmost = function() {
1848 if ('rl' != this.pageProgression) {
1856 //______________________________________________________________________________
1857 BookReader.prototype.next = function() {
1858 if (2 == this.mode) {
1860 this.flipFwdToIndex(null);
1862 if (this.firstIndex < this.lastDisplayableIndex()) {
1863 this.jumpToIndex(this.firstIndex+1);
1869 //______________________________________________________________________________
1870 BookReader.prototype.prev = function() {
1871 if (2 == this.mode) {
1873 this.flipBackToIndex(null);
1875 if (this.firstIndex >= 1) {
1876 this.jumpToIndex(this.firstIndex-1);
1881 BookReader.prototype.first = function() {
1882 this.jumpToIndex(this.firstDisplayableIndex());
1885 BookReader.prototype.last = function() {
1886 this.jumpToIndex(this.lastDisplayableIndex());
1890 //______________________________________________________________________________
1891 // Scrolls down one screen view
1892 BookReader.prototype.scrollDown = function() {
1893 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1894 $('#BRcontainer').animate(
1895 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1896 450, 'easeInOutQuint'
1905 //______________________________________________________________________________
1906 // Scrolls up one screen view
1907 BookReader.prototype.scrollUp = function() {
1908 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1909 $('#BRcontainer').animate(
1910 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1911 450, 'easeInOutQuint'
1920 // flipBackToIndex()
1921 //______________________________________________________________________________
1922 // to flip back one spread, pass index=null
1923 BookReader.prototype.flipBackToIndex = function(index) {
1925 if (1 == this.mode) return;
1927 var leftIndex = this.twoPage.currentIndexL;
1929 if (this.animating) return;
1931 if (null != this.leafEdgeTmp) {
1932 alert('error: leafEdgeTmp should be null!');
1936 if (null == index) {
1937 index = leftIndex-2;
1939 //if (index<0) return;
1941 var previousIndices = this.getSpreadIndices(index);
1943 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1947 this.animating = true;
1949 if ('rl' != this.pageProgression) {
1950 // Assume LTR and we are going backward
1951 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1952 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1954 // RTL and going backward
1955 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1956 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1960 // flipLeftToRight()
1961 //______________________________________________________________________________
1962 // Flips the page on the left towards the page on the right
1963 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1965 var leftLeaf = this.twoPage.currentIndexL;
1967 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1968 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1969 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1971 var currWidthL = this.getPageWidth2UP(leftLeaf);
1972 var newWidthL = this.getPageWidth2UP(newIndexL);
1973 var newWidthR = this.getPageWidth2UP(newIndexR);
1975 var top = this.twoPageTop();
1976 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1978 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1979 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1981 //animation strategy:
1982 // 0. remove search highlight, if any.
1983 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1984 // of the left leaf and where the user clicked in the leaf edge.
1985 // Note that if this function was triggered by left() and not a
1986 // mouse click, the width of leafEdgeTmp is very small (zero px).
1987 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1988 // leftLeaf to width=0.
1989 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1990 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1991 // its new full width.
1992 // 4. After step 3 is finished, do the following:
1993 // - remove leafEdgeTmp from the dom.
1994 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1995 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1996 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1997 // and width=newLeafEdgeWidthL.
1998 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1999 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2000 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2001 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2002 // - prefetch new adjacent leafs.
2003 // - set up click handlers for both new left and right leafs.
2004 // - redraw the search highlight.
2005 // - update the pagenum box and the url.
2008 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2010 this.leafEdgeTmp = document.createElement('div');
2011 $(this.leafEdgeTmp).css({
2012 borderStyle: 'solid none solid solid',
2013 borderColor: 'rgb(51, 51, 34)',
2014 borderWidth: '1px 0px 1px 1px',
2015 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2016 width: leafEdgeTmpW + 'px',
2017 height: this.twoPage.height-1 + 'px',
2018 left: leftEdgeTmpLeft + 'px',
2020 position: 'absolute',
2022 }).appendTo('#BRtwopageview');
2024 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2025 $(this.leafEdgeL).css({
2026 width: newLeafEdgeWidthL+'px',
2027 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2030 // Left gets the offset of the current left leaf from the document
2031 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2032 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2033 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2035 // We change the left leaf to right positioning
2036 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2037 $(this.prefetchedImgs[leftLeaf]).css({
2042 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2043 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2047 this.removeSearchHilites();
2049 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2050 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2052 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2053 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2055 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2056 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2057 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2059 $(self.leafEdgeR).css({
2060 // Moves the right leaf edge
2061 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2062 left: gutter+newWidthR+'px'
2065 $(self.leafEdgeL).css({
2066 // Moves and resizes the left leaf edge
2067 width: newLeafEdgeWidthL+'px',
2068 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2071 // Resizes the brown border div
2072 $(self.twoPage.coverDiv).css({
2073 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2074 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2077 $(self.leafEdgeTmp).remove();
2078 self.leafEdgeTmp = null;
2080 // $$$ TODO refactor with opposite direction flip
2082 self.twoPage.currentIndexL = newIndexL;
2083 self.twoPage.currentIndexR = newIndexR;
2084 self.twoPage.scaledWL = newWidthL;
2085 self.twoPage.scaledWR = newWidthR;
2086 self.twoPage.gutter = gutter;
2088 self.firstIndex = self.twoPage.currentIndexL;
2089 self.displayedIndices = [newIndexL, newIndexR];
2090 self.pruneUnusedImgs();
2092 self.animating = false;
2094 self.updateSearchHilites2UP();
2095 self.updatePageNumBox2UP();
2097 // self.twoPagePlaceFlipAreas(); // No longer used
2098 self.setMouseHandlers2UP();
2099 self.twoPageSetCursor();
2101 if (self.animationFinishedCallback) {
2102 self.animationFinishedCallback();
2103 self.animationFinishedCallback = null;
2111 //______________________________________________________________________________
2112 // Whether we flip left or right is dependent on the page progression
2113 // to flip forward one spread, pass index=null
2114 BookReader.prototype.flipFwdToIndex = function(index) {
2116 if (this.animating) return;
2118 if (null != this.leafEdgeTmp) {
2119 alert('error: leafEdgeTmp should be null!');
2123 if (null == index) {
2124 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2126 if (index > this.lastDisplayableIndex()) return;
2128 this.animating = true;
2130 var nextIndices = this.getSpreadIndices(index);
2132 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2134 if ('rl' != this.pageProgression) {
2135 // We did not specify RTL
2136 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2137 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2140 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2141 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2145 // flipRightToLeft(nextL, nextR, gutter)
2146 // $$$ better not to have to pass gutter in
2147 //______________________________________________________________________________
2148 // Flip from left to right and show the nextL and nextR indices on those sides
2149 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2150 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2151 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2152 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2153 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2155 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2157 var top = this.twoPageTop();
2158 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2160 var middle = this.twoPage.middle;
2161 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2163 this.leafEdgeTmp = document.createElement('div');
2164 $(this.leafEdgeTmp).css({
2165 borderStyle: 'solid none solid solid',
2166 borderColor: 'rgb(51, 51, 34)',
2167 borderWidth: '1px 0px 1px 1px',
2168 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2169 width: leafEdgeTmpW + 'px',
2170 height: this.twoPage.height-1 + 'px',
2171 left: gutter+scaledW+'px',
2173 position: 'absolute',
2175 }).appendTo('#BRtwopageview');
2177 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2178 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2180 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2181 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2182 var newWidthL = this.getPageWidth2UP(newIndexL);
2183 var newWidthR = this.getPageWidth2UP(newIndexR);
2185 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2187 var self = this; // closure-tastic!
2189 var speed = this.flipSpeed;
2191 this.removeSearchHilites();
2193 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2194 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2195 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2196 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2197 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2199 $(self.leafEdgeL).css({
2200 width: newLeafEdgeWidthL+'px',
2201 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2204 // Resizes the book cover
2205 $(self.twoPage.coverDiv).css({
2206 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2207 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2210 $(self.leafEdgeTmp).remove();
2211 self.leafEdgeTmp = null;
2213 self.twoPage.currentIndexL = newIndexL;
2214 self.twoPage.currentIndexR = newIndexR;
2215 self.twoPage.scaledWL = newWidthL;
2216 self.twoPage.scaledWR = newWidthR;
2217 self.twoPage.gutter = gutter;
2219 self.firstIndex = self.twoPage.currentIndexL;
2220 self.displayedIndices = [newIndexL, newIndexR];
2221 self.pruneUnusedImgs();
2223 self.animating = false;
2226 self.updateSearchHilites2UP();
2227 self.updatePageNumBox2UP();
2229 // self.twoPagePlaceFlipAreas(); // No longer used
2230 self.setMouseHandlers2UP();
2231 self.twoPageSetCursor();
2233 if (self.animationFinishedCallback) {
2234 self.animationFinishedCallback();
2235 self.animationFinishedCallback = null;
2241 // setMouseHandlers2UP
2242 //______________________________________________________________________________
2243 BookReader.prototype.setMouseHandlers2UP = function() {
2245 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2250 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2257 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2258 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2265 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2266 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2269 e.data.self.right();
2275 //______________________________________________________________________________
2276 BookReader.prototype.prefetchImg = function(index) {
2277 var pageURI = this._getPageURI(index);
2279 // Load image if not loaded or URI has changed (e.g. due to scaling)
2280 var loadImage = false;
2281 if (undefined == this.prefetchedImgs[index]) {
2282 //console.log('no image for ' + index);
2284 } else if (pageURI != this.prefetchedImgs[index].uri) {
2285 //console.log('uri changed for ' + index);
2290 //console.log('prefetching ' + index);
2291 var img = document.createElement("img");
2293 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2294 this.prefetchedImgs[index] = img;
2299 // prepareFlipLeftToRight()
2301 //______________________________________________________________________________
2303 // Prepare to flip the left page towards the right. This corresponds to moving
2304 // backward when the page progression is left to right.
2305 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2307 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2309 this.prefetchImg(prevL);
2310 this.prefetchImg(prevR);
2312 var height = this._getPageHeight(prevL);
2313 var width = this._getPageWidth(prevL);
2314 var middle = this.twoPage.middle;
2315 var top = this.twoPageTop();
2316 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2318 // The gutter is the dividing line between the left and right pages.
2319 // It is offset from the middle to create the illusion of thickness to the pages
2320 var gutter = middle + this.gutterOffsetForIndex(prevL);
2322 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2323 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2324 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2327 position: 'absolute',
2328 left: gutter-scaledW+'px',
2329 right: '', // clear right property
2331 height: this.twoPage.height,
2332 width: scaledW+'px',
2333 backgroundColor: this.getPageBackgroundColor(prevL),
2334 borderRight: '1px solid black',
2338 $(this.prefetchedImgs[prevL]).css(leftCSS);
2340 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2342 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2345 position: 'absolute',
2349 height: this.twoPage.height,
2351 backgroundColor: this.getPageBackgroundColor(prevR),
2352 borderLeft: '1px solid black',
2356 $(this.prefetchedImgs[prevR]).css(rightCSS);
2358 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2362 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2363 // prepareFlipRightToLeft()
2364 //______________________________________________________________________________
2365 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2367 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2370 this.prefetchImg(nextL);
2371 this.prefetchImg(nextR);
2373 var height = this._getPageHeight(nextR);
2374 var width = this._getPageWidth(nextR);
2375 var middle = this.twoPage.middle;
2376 var top = this.twoPageTop();
2377 var scaledW = this.twoPage.height*width/height;
2379 var gutter = middle + this.gutterOffsetForIndex(nextL);
2381 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2382 $(this.prefetchedImgs[nextR]).css({
2383 position: 'absolute',
2386 backgroundColor: this.getPageBackgroundColor(nextR),
2387 height: this.twoPage.height,
2388 width: scaledW+'px',
2389 borderLeft: '1px solid black',
2393 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2395 height = this._getPageHeight(nextL);
2396 width = this._getPageWidth(nextL);
2397 scaledW = this.twoPage.height*width/height;
2399 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2400 $(this.prefetchedImgs[nextL]).css({
2401 position: 'absolute',
2402 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2404 backgroundColor: this.getPageBackgroundColor(nextL),
2405 height: this.twoPage.height,
2406 width: 0+'px', // Start at 0 width, then grow to the left
2407 borderRight: '1px solid black',
2411 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2415 // getNextLeafs() -- NOT RTL AWARE
2416 //______________________________________________________________________________
2417 // BookReader.prototype.getNextLeafs = function(o) {
2418 // //TODO: we might have two left or two right leafs in a row (damaged book)
2419 // //For now, assume that leafs are contiguous.
2421 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2422 // o.L = this.twoPage.currentIndexL+2;
2423 // o.R = this.twoPage.currentIndexL+3;
2426 // getprevLeafs() -- NOT RTL AWARE
2427 //______________________________________________________________________________
2428 // BookReader.prototype.getPrevLeafs = function(o) {
2429 // //TODO: we might have two left or two right leafs in a row (damaged book)
2430 // //For now, assume that leafs are contiguous.
2432 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2433 // o.L = this.twoPage.currentIndexL-2;
2434 // o.R = this.twoPage.currentIndexL-1;
2437 // pruneUnusedImgs()
2438 //______________________________________________________________________________
2439 BookReader.prototype.pruneUnusedImgs = function() {
2440 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2441 for (var key in this.prefetchedImgs) {
2442 //console.log('key is ' + key);
2443 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2444 //console.log('removing key '+ key);
2445 $(this.prefetchedImgs[key]).remove();
2447 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2448 //console.log('deleting key '+ key);
2449 delete this.prefetchedImgs[key];
2455 //______________________________________________________________________________
2456 BookReader.prototype.prefetch = function() {
2458 // $$$ We should check here if the current indices have finished
2459 // loading (with some timeout) before loading more page images
2460 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2462 // prefetch visible pages first
2463 this.prefetchImg(this.twoPage.currentIndexL);
2464 this.prefetchImg(this.twoPage.currentIndexR);
2466 var adjacentPagesToLoad = 3;
2468 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2469 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2471 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2472 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2474 // Load images spreading out from current
2475 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2476 var goingDown = lowCurrent - i;
2477 if (goingDown >= start) {
2478 this.prefetchImg(goingDown);
2480 var goingUp = highCurrent + i;
2481 if (goingUp <= end) {
2482 this.prefetchImg(goingUp);
2487 var lim = this.twoPage.currentIndexL-4;
2489 lim = Math.max(lim, 0);
2490 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2491 this.prefetchImg(i);
2494 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2495 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2496 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2497 this.prefetchImg(i);
2503 // getPageWidth2UP()
2504 //______________________________________________________________________________
2505 BookReader.prototype.getPageWidth2UP = function(index) {
2506 // We return the width based on the dominant height
2507 var height = this._getPageHeight(index);
2508 var width = this._getPageWidth(index);
2509 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2513 //______________________________________________________________________________
2514 BookReader.prototype.search = function(term) {
2515 term = term.replace(/\//g, ' '); // strip slashes
2516 this.searchTerm = term;
2517 $('#BookReaderSearchScript').remove();
2518 var script = document.createElement("script");
2519 script.setAttribute('id', 'BookReaderSearchScript');
2520 script.setAttribute("type", "text/javascript");
2521 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2522 document.getElementsByTagName('head')[0].appendChild(script);
2523 $('#BookReaderSearchBox').val(term);
2524 $('#BookReaderSearchResults').html('Searching...');
2527 // BRSearchCallback()
2528 //______________________________________________________________________________
2529 BookReader.prototype.BRSearchCallback = function(txt) {
2531 if (jQuery.browser.msie) {
2532 var dom=new ActiveXObject("Microsoft.XMLDOM");
2536 var parser = new DOMParser();
2537 var dom = parser.parseFromString(txt, "text/xml");
2540 $('#BookReaderSearchResults').empty();
2541 $('#BookReaderSearchResults').append('<ul>');
2543 for (var key in this.searchResults) {
2544 if (null != this.searchResults[key].div) {
2545 $(this.searchResults[key].div).remove();
2547 delete this.searchResults[key];
2550 var pages = dom.getElementsByTagName('PAGE');
2552 if (0 == pages.length) {
2553 // $$$ it would be nice to echo the (sanitized) search result here
2554 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2556 for (var i = 0; i < pages.length; i++){
2557 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2560 var re = new RegExp (/_(\d{4})\.djvu/);
2561 var reMatch = re.exec(pages[i].getAttribute('file'));
2562 var index = parseInt(reMatch[1], 10);
2563 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2565 var children = pages[i].childNodes;
2567 for (var j=0; j<children.length; j++) {
2568 //console.log(j + ' - ' + children[j].nodeName);
2569 //console.log(children[j].firstChild.nodeValue);
2570 if ('CONTEXT' == children[j].nodeName) {
2571 context += children[j].firstChild.nodeValue;
2572 } else if ('WORD' == children[j].nodeName) {
2573 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2575 var index = this.leafNumToIndex(index);
2576 if (null != index) {
2577 //coordinates are [left, bottom, right, top, [baseline]]
2578 //we'll skip baseline for now...
2579 var coords = children[j].getAttribute('coords').split(',',4);
2580 if (4 == coords.length) {
2581 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2586 var pageName = this.getPageName(index);
2587 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2588 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2589 //TODO: remove hardcoded instance name
2590 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2593 $('#BookReaderSearchResults').append('</ul>');
2595 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2596 $('#BookReaderSearchBox').val(this.searchTerm);
2598 this.updateSearchHilites();
2601 // updateSearchHilites()
2602 //______________________________________________________________________________
2603 BookReader.prototype.updateSearchHilites = function() {
2604 if (2 == this.mode) {
2605 this.updateSearchHilites2UP();
2607 this.updateSearchHilites1UP();
2611 // showSearchHilites1UP()
2612 //______________________________________________________________________________
2613 BookReader.prototype.updateSearchHilites1UP = function() {
2615 for (var key in this.searchResults) {
2617 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2618 var result = this.searchResults[key];
2619 if(null == result.div) {
2620 result.div = document.createElement('div');
2621 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2622 //console.log('appending ' + key);
2625 width: (result.r-result.l)/this.reduce + 'px',
2626 height: (result.b-result.t)/this.reduce + 'px',
2627 left: (result.l)/this.reduce + 'px',
2628 top: (result.t)/this.reduce +'px'
2632 //console.log(key + ' not displayed');
2633 this.searchResults[key].div=null;
2639 //______________________________________________________________________________
2640 // Returns the position of the gutter (line between the page images)
2641 BookReader.prototype.twoPageGutter = function() {
2642 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2646 //______________________________________________________________________________
2647 // Returns the offset for the top of the page images
2648 BookReader.prototype.twoPageTop = function() {
2649 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2652 // twoPageCoverWidth()
2653 //______________________________________________________________________________
2654 // Returns the width of the cover div given the total page width
2655 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2656 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2659 // twoPageGetViewCenter()
2660 //______________________________________________________________________________
2661 // Returns the percentage offset into twopageview div at the center of container div
2662 // { percentageX: float, percentageY: float }
2663 BookReader.prototype.twoPageGetViewCenter = function() {
2666 var containerOffset = $('#BRcontainer').offset();
2667 var viewOffset = $('#BRtwopageview').offset();
2668 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2669 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2674 // twoPageCenterView(percentageX, percentageY)
2675 //______________________________________________________________________________
2676 // Centers the point given by percentage from left,top of twopageview
2677 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2678 if ('undefined' == typeof(percentageX)) {
2681 if ('undefined' == typeof(percentageY)) {
2685 var viewWidth = $('#BRtwopageview').width();
2686 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2687 var intoViewX = percentageX * viewWidth;
2689 var viewHeight = $('#BRtwopageview').height();
2690 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2691 var intoViewY = percentageY * viewHeight;
2693 if (viewWidth < containerClientWidth) {
2694 // Can fit width without scrollbars - center by adjusting offset
2695 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2697 // Need to scroll to center
2698 $('#BRtwopageview').css('left', 0);
2699 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2702 if (viewHeight < containerClientHeight) {
2703 // Fits with scrollbars - add offset
2704 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2706 $('#BRtwopageview').css('top', 0);
2707 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2711 // twoPageFlipAreaHeight
2712 //______________________________________________________________________________
2713 // Returns the integer height of the click-to-flip areas at the edges of the book
2714 BookReader.prototype.twoPageFlipAreaHeight = function() {
2715 return parseInt(this.twoPage.height);
2718 // twoPageFlipAreaWidth
2719 //______________________________________________________________________________
2720 // Returns the integer width of the flip areas
2721 BookReader.prototype.twoPageFlipAreaWidth = function() {
2722 var max = 100; // $$$ TODO base on view width?
2725 var width = this.twoPage.width * 0.15;
2726 return parseInt(BookReader.util.clamp(width, min, max));
2729 // twoPageFlipAreaTop
2730 //______________________________________________________________________________
2731 // Returns integer top offset for flip areas
2732 BookReader.prototype.twoPageFlipAreaTop = function() {
2733 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2736 // twoPageLeftFlipAreaLeft
2737 //______________________________________________________________________________
2738 // Left offset for left flip area
2739 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2740 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2743 // twoPageRightFlipAreaLeft
2744 //______________________________________________________________________________
2745 // Left offset for right flip area
2746 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2747 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2750 // twoPagePlaceFlipAreas
2751 //______________________________________________________________________________
2752 // Readjusts position of flip areas based on current layout
2753 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2754 // We don't set top since it shouldn't change relative to view
2755 $(this.twoPage.leftFlipArea).css({
2756 left: this.twoPageLeftFlipAreaLeft() + 'px',
2757 width: this.twoPageFlipAreaWidth() + 'px'
2759 $(this.twoPage.rightFlipArea).css({
2760 left: this.twoPageRightFlipAreaLeft() + 'px',
2761 width: this.twoPageFlipAreaWidth() + 'px'
2765 // showSearchHilites2UP()
2766 //______________________________________________________________________________
2767 BookReader.prototype.updateSearchHilites2UP = function() {
2769 for (var key in this.searchResults) {
2770 key = parseInt(key, 10);
2771 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2772 var result = this.searchResults[key];
2773 if(null == result.div) {
2774 result.div = document.createElement('div');
2775 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2776 //console.log('appending ' + key);
2779 // We calculate the reduction factor for the specific page because it can be different
2780 // for each page in the spread
2781 var height = this._getPageHeight(key);
2782 var width = this._getPageWidth(key)
2783 var reduce = this.twoPage.height/height;
2784 var scaledW = parseInt(width*reduce);
2786 var gutter = this.twoPageGutter();
2788 if ('L' == this.getPageSide(key)) {
2789 pageL = gutter-scaledW;
2793 var pageT = this.twoPageTop();
2796 width: (result.r-result.l)*reduce + 'px',
2797 height: (result.b-result.t)*reduce + 'px',
2798 left: pageL+(result.l)*reduce + 'px',
2799 top: pageT+(result.t)*reduce +'px'
2803 //console.log(key + ' not displayed');
2804 if (null != this.searchResults[key].div) {
2805 //console.log('removing ' + key);
2806 $(this.searchResults[key].div).remove();
2808 this.searchResults[key].div=null;
2813 // removeSearchHilites()
2814 //______________________________________________________________________________
2815 BookReader.prototype.removeSearchHilites = function() {
2816 for (var key in this.searchResults) {
2817 if (null != this.searchResults[key].div) {
2818 $(this.searchResults[key].div).remove();
2819 this.searchResults[key].div=null;
2825 //______________________________________________________________________________
2826 BookReader.prototype.printPage = function() {
2827 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2829 /* iframe implementation
2831 if (null != this.printPopup) { // check if already showing
2834 this.printPopup = document.createElement("div");
2835 $(this.printPopup).css({
2836 position: 'absolute',
2838 left: ($('#BRcontainer').width()-400)/2 + 'px',
2841 border: "3px double #999999",
2843 backgroundColor: "#fff"
2844 }).appendTo('#BookReader');
2847 if (this.constMode1up == this.mode) {
2848 indexToPrint = this.firstIndex;
2850 indexToPrint = this.twoPage.currentIndexL;
2853 this.indexToPrint = indexToPrint;
2855 var htmlStr = '<div style="text-align: center;">';
2856 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>';
2857 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2858 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2859 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2860 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2861 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2863 htmlStr += '</div>';
2864 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2865 htmlStr += '</div>';
2867 this.printPopup.innerHTML = htmlStr;
2869 var iframe = document.createElement('iframe');
2870 iframe.id = 'printFrame';
2871 iframe.name = 'printFrame';
2872 iframe.width = '233px'; // 8.5 x 11 aspect
2873 iframe.height = '300px';
2875 var self = this; // closure
2877 $(iframe).load(function() {
2878 var doc = BookReader.util.getIFrameDocument(this);
2879 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2882 $('#printDiv').prepend(iframe);
2886 // Get print URI from current indices and mode
2887 BookReader.prototype.getPrintURI = function() {
2889 if (this.constMode2up == this.mode) {
2890 indexToPrint = this.twoPage.currentIndexL;
2892 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2895 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2896 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2897 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2899 if (this.constMode2up == this.mode) {
2900 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2901 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2902 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2904 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2907 return '/bookreader/print.php?' + options;
2910 /* iframe implementation
2911 BookReader.prototype.getPrintFrameContent = function(index) {
2912 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2913 // 8.5x11 so we should end up not overflowing on either paper size.
2914 var paperAspect = 8.5 / 11;
2915 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2919 // Rotate if possible and appropriate, to get larger image size on printed page
2920 if (this.canRotatePage(index)) {
2921 if (imageAspect > 1 && imageAspect > paperAspect) {
2922 // more wide than square, and more wide than paper
2924 imageAspect = 1/imageAspect;
2929 if (imageAspect > paperAspect) {
2930 // wider than paper, fit width
2931 fitAttrs = 'width="95%"';
2933 // taller than paper, fit height
2934 fitAttrs = 'height="95%"';
2937 var imageURL = this._getPageURI(index, 1, rotate);
2938 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2939 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2940 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2941 iframeStr += '</div>';
2942 iframeStr += '</body></html>';
2947 BookReader.prototype.updatePrintFrame = function(delta) {
2948 var newIndex = this.indexToPrint + delta;
2949 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2950 if (newIndex == this.indexToPrint) {
2953 this.indexToPrint = newIndex;
2954 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2955 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2960 //______________________________________________________________________________
2961 BookReader.prototype.showEmbedCode = function() {
2962 if (null != this.embedPopup) { // check if already showing
2966 this.embedPopup = document.createElement("div");
2967 $(this.embedPopup).css({
2968 position: 'absolute',
2970 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2973 border: "3px double #999999",
2975 backgroundColor: "#fff"
2976 }).appendTo('#BookReader');
2978 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2979 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>';
2980 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2981 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2983 this.embedPopup.innerHTML = htmlStr;
2984 $(this.embedPopup).find('input').bind('click', function() {
2990 //______________________________________________________________________________
2991 BookReader.prototype.autoToggle = function() {
2993 var bComingFrom1up = false;
2994 if (2 != this.mode) {
2995 bComingFrom1up = true;
2999 // Change to autofit if book is too large
3000 if (this.reduce < this.twoPageGetAutofitReduce()) {
3005 if (null == this.autoTimer) {
3006 this.flipSpeed = 2000;
3008 // $$$ Draw events currently cause layout problems when they occur during animation.
3009 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3010 // we workaround for now by not triggering immediate animation in that case.
3011 // See https://bugs.launchpad.net/gnubook/+bug/328327
3012 if (('rl' == this.pageProgression) && bComingFrom1up) {
3013 // don't flip immediately -- wait until timer fires
3016 this.flipFwdToIndex();
3019 $('#BRtoolbar .play').hide();
3020 $('#BRtoolbar .pause').show();
3021 this.autoTimer=setInterval(function(){
3022 if (self.animating) {return;}
3024 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3025 self.flipBackToIndex(1); // $$$ really what we want?
3027 self.flipFwdToIndex();
3036 //______________________________________________________________________________
3037 // Stop autoplay mode, allowing animations to finish
3038 BookReader.prototype.autoStop = function() {
3039 if (null != this.autoTimer) {
3040 clearInterval(this.autoTimer);
3041 this.flipSpeed = 'fast';
3042 $('#BRtoolbar .pause').hide();
3043 $('#BRtoolbar .play').show();
3044 this.autoTimer = null;
3048 // stopFlipAnimations
3049 //______________________________________________________________________________
3050 // Immediately stop flip animations. Callbacks are triggered.
3051 BookReader.prototype.stopFlipAnimations = function() {
3053 this.autoStop(); // Clear timers
3055 // Stop animation, clear queue, trigger callbacks
3056 if (this.leafEdgeTmp) {
3057 $(this.leafEdgeTmp).stop(false, true);
3059 jQuery.each(this.prefetchedImgs, function() {
3060 $(this).stop(false, true);
3063 // And again since animations also queued in callbacks
3064 if (this.leafEdgeTmp) {
3065 $(this.leafEdgeTmp).stop(false, true);
3067 jQuery.each(this.prefetchedImgs, function() {
3068 $(this).stop(false, true);
3073 // keyboardNavigationIsDisabled(event)
3074 // - returns true if keyboard navigation should be disabled for the event
3075 //______________________________________________________________________________
3076 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3077 if (event.target.tagName == "INPUT") {
3083 // gutterOffsetForIndex
3084 //______________________________________________________________________________
3086 // Returns the gutter offset for the spread containing the given index.
3087 // This function supports RTL
3088 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3090 // To find the offset of the gutter from the middle we calculate our percentage distance
3091 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3092 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3094 // But then again for RTL it's the opposite
3095 if ('rl' == this.pageProgression) {
3103 //______________________________________________________________________________
3104 // Returns the width of the leaf edge div for the page with index given
3105 BookReader.prototype.leafEdgeWidth = function(pindex) {
3106 // $$$ could there be single pixel rounding errors for L vs R?
3107 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3108 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3110 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3114 // jumpIndexForLeftEdgePageX
3115 //______________________________________________________________________________
3116 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3117 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3118 if ('rl' != this.pageProgression) {
3119 // LTR - flipping backward
3120 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3122 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3123 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3127 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3128 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3133 // jumpIndexForRightEdgePageX
3134 //______________________________________________________________________________
3135 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3136 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3137 if ('rl' != this.pageProgression) {
3139 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3140 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3143 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3144 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3149 BookReader.prototype.initToolbar = function(mode, ui) {
3151 $("#BookReader").append("<div id='BRtoolbar'>"
3152 + "<span id='BRtoolbarbuttons' style='float: right'>"
3153 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3154 + "<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>"
3155 + "<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>"
3156 + "<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>"
3157 + "<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>"
3158 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3162 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3163 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3164 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3165 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3166 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3167 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3168 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3171 + "<span id='#BRbooktitle'>"
3172 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3176 this.updateToolbarZoom(this.reduce); // Pretty format
3178 if (ui == "embed") {
3179 $("#BookReader a.logo").attr("target","_blank");
3182 // $$$ turn this into a member variable
3183 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3185 // We build in mode 2
3188 this.bindToolbarNavHandlers(jToolbar);
3190 // Setup tooltips -- later we could load these from a file for i18n
3191 var titles = { '.logo': 'Go to Archive.org',
3192 '.zoom_in': 'Zoom in',
3193 '.zoom_out': 'Zoom out',
3194 '.one_page_mode': 'One-page view',
3195 '.two_page_mode': 'Two-page view',
3196 '.thumbnail_mode': 'Thumbnail view',
3197 '.print': 'Print this page',
3198 '.embed': 'Embed bookreader',
3199 '.book_left': 'Flip left',
3200 '.book_right': 'Flip right',
3201 '.book_up': 'Page up',
3202 '.book_down': 'Page down',
3205 '.book_top': 'First page',
3206 '.book_bottom': 'Last page'
3208 if ('rl' == this.pageProgression) {
3209 titles['.book_leftmost'] = 'Last page';
3210 titles['.book_rightmost'] = 'First page';
3212 titles['.book_leftmost'] = 'First page';
3213 titles['.book_rightmost'] = 'Last page';
3216 for (var icon in titles) {
3217 jToolbar.find(icon).attr('title', titles[icon]);
3220 // Hide mode buttons and autoplay if 2up is not available
3221 // $$$ if we end up with more than two modes we should show the applicable buttons
3222 if ( !this.canSwitchToMode(this.constMode2up) ) {
3223 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3226 // Switch to requested mode -- binds other click handlers
3227 this.switchToolbarMode(mode);
3232 // switchToolbarMode
3233 //______________________________________________________________________________
3234 // Update the toolbar for the given mode (changes navigation buttons)
3235 // $$$ we should soon split the toolbar out into its own module
3236 BookReader.prototype.switchToolbarMode = function(mode) {
3239 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3240 $('#BRtoolbar .BRtoolbarmode2').hide();
3241 $('#BRtoolbar .BRtoolbarmode3').hide();
3242 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3243 } else if (2 == mode) {
3245 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3246 $('#BRtoolbar .BRtoolbarmode1').hide();
3247 $('#BRtoolbar .BRtoolbarmode3').hide();
3248 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3251 $('#BRtoolbar .BRtoolbarzoom').hide();
3252 $('#BRtoolbar .BRtoolbarmode2').hide();
3253 $('#BRtoolbar .BRtoolbarmode1').hide();
3254 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3258 // bindToolbarNavHandlers
3259 //______________________________________________________________________________
3260 // Binds the toolbar handlers
3261 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3263 var self = this; // closure
3265 jToolbar.find('.book_left').bind('click', function(e) {
3270 jToolbar.find('.book_right').bind('click', function(e) {
3275 jToolbar.find('.book_up').bind('click', function(e) {
3276 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3284 jToolbar.find('.book_down').bind('click', function(e) {
3285 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3293 jToolbar.find('.print').bind('click', function(e) {
3298 jToolbar.find('.embed').bind('click', function(e) {
3299 self.showEmbedCode();
3303 jToolbar.find('.play').bind('click', function(e) {
3308 jToolbar.find('.pause').bind('click', function(e) {
3313 jToolbar.find('.book_top').bind('click', function(e) {
3318 jToolbar.find('.book_bottom').bind('click', function(e) {
3323 jToolbar.find('.book_leftmost').bind('click', function(e) {
3328 jToolbar.find('.book_rightmost').bind('click', function(e) {
3334 // updateToolbarZoom(reduce)
3335 //______________________________________________________________________________
3336 // Update the displayed zoom factor based on reduction factor
3337 BookReader.prototype.updateToolbarZoom = function(reduce) {
3339 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3342 value = (100 / reduce).toFixed(2);
3343 // Strip trailing zeroes and decimal if all zeroes
3344 value = value.replace(/0+$/,'');
3345 value = value.replace(/\.$/,'');
3348 $('#BRzoom').text(value);
3351 // firstDisplayableIndex
3352 //______________________________________________________________________________
3353 // Returns the index of the first visible page, dependent on the mode.
3354 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3355 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3356 BookReader.prototype.firstDisplayableIndex = function() {
3357 if (this.mode != this.constMode2up) {
3361 if ('rl' != this.pageProgression) {
3363 if (this.getPageSide(0) == 'L') {
3370 if (this.getPageSide(0) == 'R') {
3378 // lastDisplayableIndex
3379 //______________________________________________________________________________
3380 // Returns the index of the last visible page, dependent on the mode.
3381 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3382 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3383 BookReader.prototype.lastDisplayableIndex = function() {
3385 var lastIndex = this.numLeafs - 1;
3387 if (this.mode != this.constMode2up) {
3391 if ('rl' != this.pageProgression) {
3393 if (this.getPageSide(lastIndex) == 'R') {
3396 return lastIndex + 1;
3400 if (this.getPageSide(lastIndex) == 'L') {
3403 return lastIndex + 1;
3408 // shortTitle(maximumCharacters)
3410 // Returns a shortened version of the title with the maximum number of characters
3411 BookReader.prototype.shortTitle = function(maximumCharacters) {
3412 if (this.bookTitle.length < maximumCharacters) {
3413 return this.bookTitle;
3416 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3421 // Parameter related functions
3423 // updateFromParams(params)
3425 // Update ourselves from the params object.
3427 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3428 BookReader.prototype.updateFromParams = function(params) {
3429 if ('undefined' != typeof(params.mode)) {
3430 this.switchMode(params.mode);
3434 if ('undefined' != typeof(params.searchTerm)) {
3435 if (this.searchTerm != params.searchTerm) {
3436 this.search(params.searchTerm);
3440 // $$$ process /zoom
3442 // We only respect page if index is not set
3443 if ('undefined' != typeof(params.index)) {
3444 if (params.index != this.currentIndex()) {
3445 this.jumpToIndex(params.index);
3447 } else if ('undefined' != typeof(params.page)) {
3448 // $$$ this assumes page numbers are unique
3449 if (params.page != this.getPageNum(this.currentIndex())) {
3450 this.jumpToPage(params.page);
3454 // $$$ process /region
3455 // $$$ process /highlight
3458 // paramsFromFragment(urlFragment)
3460 // Returns a object with configuration parametes from a URL fragment.
3462 // E.g paramsFromFragment(window.location.hash)
3463 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3464 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3468 // For convenience we allow an initial # character (as from window.location.hash)
3469 // but don't require it
3470 if (urlFragment.substr(0,1) == '#') {
3471 urlFragment = urlFragment.substr(1);
3474 // Simple #nn syntax
3475 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3476 if ( !isNaN(oldStyleLeafNum) ) {
3477 params.index = oldStyleLeafNum;
3479 // Done processing if using old-style syntax
3483 // Split into key-value pairs
3484 var urlArray = urlFragment.split('/');
3486 for (var i = 0; i < urlArray.length; i += 2) {
3487 urlHash[urlArray[i]] = urlArray[i+1];
3491 if ('1up' == urlHash['mode']) {
3492 params.mode = this.constMode1up;
3493 } else if ('2up' == urlHash['mode']) {
3494 params.mode = this.constMode2up;
3495 } else if ('thumb' == urlHash['mode']) {
3496 params.mode = this.constModeThumb;
3500 if ('undefined' != typeof(urlHash['page'])) {
3501 // page was set -- may not be int
3502 params.page = urlHash['page'];
3505 // $$$ process /region
3506 // $$$ process /search
3508 if (urlHash['search'] != undefined) {
3509 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3512 // $$$ process /highlight
3517 // paramsFromCurrent()
3519 // Create a params object from the current parameters.
3520 BookReader.prototype.paramsFromCurrent = function() {
3524 var index = this.currentIndex();
3525 var pageNum = this.getPageNum(index);
3526 if ((pageNum === 0) || pageNum) {
3527 params.page = pageNum;
3530 params.index = index;
3531 params.mode = this.mode;
3537 if (this.searchHighlightVisible()) {
3538 params.searchTerm = this.searchTerm;
3544 // fragmentFromParams(params)
3546 // Create a fragment string from the params object.
3547 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3548 BookReader.prototype.fragmentFromParams = function(params) {
3549 var separator = '/';
3553 if ('undefined' != typeof(params.page)) {
3554 fragments.push('page', params.page);
3556 // Don't have page numbering -- use index instead
3557 fragments.push('page', 'n' + params.index);
3564 if ('undefined' != typeof(params.mode)) {
3565 if (params.mode == this.constMode1up) {
3566 fragments.push('mode', '1up');
3567 } else if (params.mode == this.constMode2up) {
3568 fragments.push('mode', '2up');
3569 } else if (params.mode == this.constModeThumb) {
3570 fragments.push('mode', 'thumb');
3572 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3577 if (params.searchTerm) {
3578 fragments.push('search', params.searchTerm);
3581 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3584 // getPageIndex(pageNum)
3586 // Returns the *highest* index the given page number, or undefined
3587 BookReader.prototype.getPageIndex = function(pageNum) {
3588 var pageIndices = this.getPageIndices(pageNum);
3590 if (pageIndices.length > 0) {
3591 return pageIndices[pageIndices.length - 1];
3597 // getPageIndices(pageNum)
3599 // Returns an array (possibly empty) of the indices with the given page number
3600 BookReader.prototype.getPageIndices = function(pageNum) {
3603 // Check for special "nXX" page number
3604 if (pageNum.slice(0,1) == 'n') {
3606 var pageIntStr = pageNum.slice(1, pageNum.length);
3607 var pageIndex = parseInt(pageIntStr);
3608 indices.push(pageIndex);
3611 // Do nothing... will run through page names and see if one matches
3616 for (i=0; i<this.numLeafs; i++) {
3617 if (this.getPageNum(i) == pageNum) {
3625 // getPageName(index)
3627 // Returns the name of the page as it should be displayed in the user interface
3628 BookReader.prototype.getPageName = function(index) {
3629 return 'Page ' + this.getPageNum(index);
3632 // updateLocationHash
3634 // Update the location hash from the current parameters. Call this instead of manually
3635 // using window.location.replace
3636 BookReader.prototype.updateLocationHash = function() {
3637 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3638 window.location.replace(newHash);
3640 // This is the variable checked in the timer. Only user-generated changes
3641 // to the URL will trigger the event.
3642 this.oldLocationHash = newHash;
3645 // startLocationPolling
3647 // Starts polling of window.location to see hash fragment changes
3648 BookReader.prototype.startLocationPolling = function() {
3649 var self = this; // remember who I am
3650 self.oldLocationHash = window.location.hash;
3652 if (this.locationPollId) {
3653 clearInterval(this.locationPollID);
3654 this.locationPollId = null;
3657 this.locationPollId = setInterval(function() {
3658 var newHash = window.location.hash;
3659 if (newHash != self.oldLocationHash) {
3660 if (newHash != self.oldUserHash) { // Only process new user hash once
3661 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3663 // Queue change if animating
3664 if (self.animating) {
3666 self.animationFinishedCallback = function() {
3667 self.updateFromParams(self.paramsFromFragment(newHash));
3669 } else { // update immediately
3670 self.updateFromParams(self.paramsFromFragment(newHash));
3672 self.oldUserHash = newHash;
3680 // Returns true if we can switch to the requested mode
3681 BookReader.prototype.canSwitchToMode = function(mode) {
3682 if (mode == this.constMode2up) {
3683 // check there are enough pages to display
3684 // $$$ this is a workaround for the mis-feature that we can't display
3685 // short books in 2up mode
3686 if (this.numLeafs < 6) {
3694 // searchHighlightVisible
3696 // Returns true if a search highlight is currently being displayed
3697 BookReader.prototype.searchHighlightVisible = function() {
3698 if (this.constMode2up == this.mode) {
3699 if (this.searchResults[this.twoPage.currentIndexL]
3700 || this.searchResults[this.twoPage.currentIndexR]) {
3704 if (this.searchResults[this.currentIndex()]) {
3711 // getPageBackgroundColor
3713 // Returns a CSS property string for the background color for the given page
3714 // $$$ turn into regular CSS?
3715 BookReader.prototype.getPageBackgroundColor = function(index) {
3716 if (index >= 0 && index < this.numLeafs) {
3718 return this.pageDefaultBackgroundColor;
3726 // Returns the page width for the given index, or first or last page if out of range
3727 BookReader.prototype._getPageWidth = function(index) {
3728 // Synthesize a page width for pages not actually present in book.
3729 // May or may not be the best approach.
3730 // If index is out of range we return the width of first or last page
3731 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3732 return this.getPageWidth(index);
3737 // Returns the page height for the given index, or first or last page if out of range
3738 BookReader.prototype._getPageHeight= function(index) {
3739 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3740 return this.getPageHeight(index);
3745 // Returns the page URI or transparent image if out of range
3746 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3747 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3748 return this.imagesBaseURL + "/transparent.png";
3751 if ('undefined' == typeof(reduce)) {
3752 // reduce not passed in
3753 // $$$ this probably won't work for thumbnail mode
3754 var ratio = this.getPageHeight(index) / this.twoPage.height;
3756 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3759 } else if (ratio < 4) {
3761 } else if (ratio < 8) {
3763 } else if (ratio < 16) {
3765 } else if (ratio < 32) {
3773 return this.getPageURI(index, reduce, rotate);
3776 // Library functions
3778 disableSelect: function(jObject) {
3779 // Bind mouse handlers
3780 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3781 jObject.bind('mousedown', function(e) {
3782 // $$$ check here for right-click and don't disable. Also use jQuery style
3783 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3786 // Special hack for IE7
3787 jObject[0].onselectstart = function(e) { return false; };
3790 clamp: function(value, min, max) {
3791 return Math.min(Math.max(value, min), max);
3794 getIFrameDocument: function(iframe) {
3795 // Adapted from http://xkr.us/articles/dom/iframe-document/
3796 var outer = (iframe.contentWindow || iframe.contentDocument);
3797 return (outer.document || outer);
3800 decodeURIComponentPlus: function(value) {
3801 // Decodes a URI component and converts '+' to ' '
3802 return decodeURIComponent(value).replace(/\+/g, ' ');
3805 encodeURIComponentPlus: function(value) {
3806 // Encodes a URI component and converts ' ' to '+'
3807 return encodeURIComponent(value).replace(/%20/g, '+');
3809 // The final property here must NOT have a comma after it - IE7