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;
46 this.thumbRowBuffer = 3; // number of rows to pre-cache out a view
47 this.displayedRows=[];
49 this.displayedIndices = [];
50 //this.indicesToDisplay = [];
52 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
55 this.animating = false;
57 this.autoTimer = null;
58 this.flipSpeed = 'fast';
60 this.twoPagePopUp = null;
61 this.leafEdgeTmp = null;
62 this.embedPopup = null;
63 this.printPopup = null;
66 this.searchResults = {};
68 this.firstIndex = null;
70 this.lastDisplayableIndex2up = null;
72 // We link to index.php to avoid redirect which breaks back button
73 this.logoURL = 'http://www.archive.org/index.php';
75 // Base URL for images
76 this.imagesBaseURL = '/bookreader/images/';
79 this.constMode1up = 1;
80 this.constMode2up = 2;
81 this.constModeThumb = 3;
84 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
86 // Object to hold parameters related to 2up mode
88 coverInternalPadding: 10, // Width of cover
89 coverExternalPadding: 10, // Padding outside of cover
90 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
94 // Background color for pages (e.g. when loading page image)
95 // $$$ TODO dynamically calculate based on page images
96 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
100 //______________________________________________________________________________
101 BookReader.prototype.init = function() {
103 var startIndex = undefined;
104 this.pageScale = this.reduce; // preserve current reduce
106 // Find start index and mode if set in location hash
107 var params = this.paramsFromFragment(window.location.hash);
109 if ('undefined' != typeof(params.index)) {
110 startIndex = params.index;
111 } else if ('undefined' != typeof(params.page)) {
112 startIndex = this.getPageIndex(params.page);
115 if ('undefined' == typeof(startIndex)) {
116 if ('undefined' != typeof(this.titleLeaf)) {
117 startIndex = this.leafNumToIndex(this.titleLeaf);
121 if ('undefined' == typeof(startIndex)) {
125 if ('undefined' != typeof(params.mode)) {
126 this.mode = params.mode;
129 // Set document title -- may have already been set in enclosing html for
130 // search engine visibility
131 document.title = this.shortTitle(50);
133 // Sanitize parameters
134 if ( !this.canSwitchToMode( this.mode ) ) {
135 this.mode = this.constMode1up;
138 $("#BookReader").empty();
139 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
140 $("#BookReader").append("<div id='BRcontainer'></div>");
141 $("#BRcontainer").append("<div id='BRpageview'></div>");
143 $("#BRcontainer").bind('scroll', this, function(e) {
147 this.setupKeyListeners();
148 this.startLocationPolling();
150 $(window).bind('resize', this, function(e) {
151 //console.log('resize!');
152 if (1 == e.data.mode) {
153 //console.log('centering 1page view');
154 e.data.centerPageView();
155 $('#BRpageview').empty()
156 e.data.displayedIndices = [];
157 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
159 } else if (3 == e.data.mode){
160 e.data.prepareThumbnailView();
162 //console.log('drawing 2 page view');
164 // We only need to prepare again in autofit (size of spread changes)
165 if (e.data.twoPage.autofit) {
166 e.data.prepareTwoPageView();
168 // Re-center if the scrollbars have disappeared
169 var center = e.data.twoPageGetViewCenter();
170 var doRecenter = false;
171 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
172 center.percentageX = 0.5;
175 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
176 center.percentageY = 0.5;
180 e.data.twoPageCenterView(center.percentageX, center.percentageY);
186 $('.BRpagediv1up').bind('mousedown', this, function(e) {
187 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
188 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
191 if (1 == this.mode) {
192 this.resizePageView();
193 this.firstIndex = startIndex;
194 this.jumpToIndex(startIndex);
195 } else if (3 == this.mode) {
196 this.firstIndex = startIndex;
197 this.prepareThumbnailView();
198 this.jumpToIndex(startIndex);
200 //this.resizePageView();
202 this.displayedIndices=[0];
203 this.firstIndex = startIndex;
204 this.displayedIndices = [this.firstIndex];
205 //console.log('titleLeaf: %d', this.titleLeaf);
206 //console.log('displayedIndices: %s', this.displayedIndices);
207 this.prepareTwoPageView();
210 // Enact other parts of initial params
211 this.updateFromParams(params);
214 BookReader.prototype.setupKeyListeners = function() {
227 // We use document here instead of window to avoid a bug in jQuery on IE7
228 $(document).keydown(function(e) {
230 // Keyboard navigation
231 if (!self.keyboardNavigationIsDisabled(e)) {
235 // In 1up mode page scrolling is handled by browser
236 if (2 == self.mode) {
243 if (2 == self.mode) {
257 if (2 == self.mode) {
263 if (2 == self.mode) {
274 //______________________________________________________________________________
275 BookReader.prototype.drawLeafs = function() {
276 if (1 == this.mode) {
277 this.drawLeafsOnePage();
278 } else if(3 == this.mode) {
279 this.drawLeafsThumbnail();
281 this.drawLeafsTwoPage();
286 //______________________________________________________________________________
287 BookReader.prototype.setDragHandler = function(div) {
288 div.dragging = false;
290 $(div).unbind('mousedown').bind('mousedown', function(e) {
293 //console.log('mousedown at ' + e.pageY);
295 this.dragging = true;
296 this.prevMouseX = e.pageX;
297 this.prevMouseY = e.pageY;
299 var startX = e.pageX;
300 var startY = e.pageY;
301 var startTop = $('#BRcontainer').attr('scrollTop');
302 var startLeft = $('#BRcontainer').attr('scrollLeft');
306 $(div).unbind('mousemove').bind('mousemove', function(ee) {
309 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
311 var offsetX = ee.pageX - this.prevMouseX;
312 var offsetY = ee.pageY - this.prevMouseY;
315 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
316 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
319 this.prevMouseX = ee.pageX;
320 this.prevMouseY = ee.pageY;
324 $(div).unbind('mouseup').bind('mouseup', function(ee) {
326 //console.log('mouseup');
328 this.dragging = false;
331 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
333 //console.log('mouseleave');
335 this.dragging = false;
338 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
340 //console.log('mouseenter');
342 this.dragging = false;
346 // setDragHandler2UP()
347 //______________________________________________________________________________
348 BookReader.prototype.setDragHandler2UP = function(div) {
349 div.dragging = false;
351 $(div).unbind('mousedown').bind('mousedown', function(e) {
354 //console.log('mousedown at ' + e.pageY);
356 this.dragStart = {x: e.pageX, y: e.pageY };
357 this.mouseDown = true;
358 this.dragging = false; // wait until drag distance
359 this.prevMouseX = e.pageX;
360 this.prevMouseY = e.pageY;
362 var startX = e.pageX;
363 var startY = e.pageY;
364 var startTop = $('#BRcontainer').attr('scrollTop');
365 var startLeft = $('#BRcontainer').attr('scrollLeft');
369 $(div).unbind('mousemove').bind('mousemove', function(ee) {
372 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
374 var offsetX = ee.pageX - this.prevMouseX;
375 var offsetY = ee.pageY - this.prevMouseY;
377 var minDragDistance = 5; // $$$ constant
379 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
381 if (this.mouseDown && (distance > minDragDistance)) {
382 //console.log('drag start!');
384 this.dragging = true;
388 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
389 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
390 this.prevMouseX = ee.pageX;
391 this.prevMouseY = ee.pageY;
398 $(div).unbind('mouseup').bind('mouseup', function(ee) {
400 //console.log('mouseup');
402 this.dragging = false;
403 this.mouseDown = false;
408 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
410 //console.log('mouseleave');
412 this.dragging = false;
413 this.mouseDown = false;
416 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
418 //console.log('mouseenter');
420 this.dragging = false;
421 this.mouseDown = false;
425 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
426 //console.log('setting handler');
427 //console.log(element.tagName);
429 $(element).unbind('click').bind('click', data, function(e) {
432 //console.log('click!');
434 if (this.mouseDown && (!this.dragging)) {
435 //console.log('click not dragging!');
439 this.dragging = false;
440 this.mouseDown = false;
444 // drawLeafsOnePage()
445 //______________________________________________________________________________
446 BookReader.prototype.drawLeafsOnePage = function() {
447 //alert('drawing leafs!');
451 var scrollTop = $('#BRcontainer').attr('scrollTop');
452 var scrollBottom = scrollTop + $('#BRcontainer').height();
453 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
455 var indicesToDisplay = [];
460 for (i=0; i<this.numLeafs; i++) {
461 var height = parseInt(this._getPageHeight(i)/this.reduce);
463 leafBottom += height;
464 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
465 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
466 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
467 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
468 if (topInView | bottomInView | middleInView) {
469 //console.log('displayed: ' + this.displayedIndices);
470 //console.log('to display: ' + i);
471 indicesToDisplay.push(i);
473 leafTop += height +10;
477 var firstIndexToDraw = indicesToDisplay[0];
478 this.firstIndex = firstIndexToDraw;
480 // Update hash, but only if we're currently displaying a leaf
481 // Hack that fixes #365790
482 if (this.displayedIndices.length > 0) {
483 this.updateLocationHash();
486 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
488 indicesToDisplay.unshift(firstIndexToDraw);
491 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
492 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
493 indicesToDisplay.push(lastIndexToDraw+1);
498 for (i=0; i<firstIndexToDraw; i++) {
499 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
502 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
503 var viewWidth = $('#BRcontainer').attr('scrollWidth');
506 for (i=0; i<indicesToDisplay.length; i++) {
507 var index = indicesToDisplay[i];
508 var height = parseInt(this._getPageHeight(index)/this.reduce);
510 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
511 var width = parseInt(this._getPageWidth(index)/this.reduce);
512 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
513 var div = document.createElement("div");
514 div.className = 'BRpagediv1up';
515 div.id = 'pagediv'+index;
516 div.style.position = "absolute";
517 $(div).css('top', leafTop + 'px');
518 var left = (viewWidth-width)>>1;
519 if (left<0) left = 0;
520 $(div).css('left', left+'px');
521 $(div).css('width', width+'px');
522 $(div).css('height', height+'px');
523 //$(div).text('loading...');
525 this.setDragHandler(div);
527 $('#BRpageview').append(div);
529 var img = document.createElement("img");
530 img.src = this._getPageURI(index, this.reduce, 0);
531 $(img).css('width', width+'px');
532 $(img).css('height', height+'px');
536 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
539 leafTop += height +10;
543 for (i=0; i<this.displayedIndices.length; i++) {
544 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
545 var index = this.displayedIndices[i];
546 //console.log('Removing leaf ' + index);
547 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
548 $('#pagediv'+index).remove();
550 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
554 this.displayedIndices = indicesToDisplay.slice();
555 this.updateSearchHilites();
557 if (null != this.getPageNum(firstIndexToDraw)) {
558 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
560 $("#BRpagenum").val('');
563 this.updateToolbarZoom(this.reduce);
567 // drawLeafsThumbnail()
568 //______________________________________________________________________________
569 BookReader.prototype.drawLeafsThumbnail = function() {
570 //alert('drawing leafs!');
573 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
575 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
587 for (i=0; i<this.numLeafs; i++) {
588 leafWidth = this.thumbWidth;
589 if (rightPos + (leafWidth + this.padding) > viewWidth){
595 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
596 if (leafMap[currentRow].leafs===undefined) {
597 leafMap[currentRow].leafs = [];
598 leafMap[currentRow].height = 0;
599 leafMap[currentRow].top = 0;
601 leafMap[currentRow].leafs[leafIndex] = {};
602 leafMap[currentRow].leafs[leafIndex].num = i;
603 leafMap[currentRow].leafs[leafIndex].left = rightPos;
605 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
606 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
607 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
608 rightPos += leafWidth + this.padding;
609 if (rightPos > maxRight) { maxRight = rightPos; }
613 // reset the bottom position based on thumbnails
614 $('#BRpageview').height(bottomPos);
616 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
617 var scrollTop = $('#BRcontainer').attr('scrollTop');
618 var scrollBottom = scrollTop + $('#BRcontainer').height();
622 var rowsToDisplay = [];
624 for (i=0; i<leafMap.length; i++) {
625 leafBottom += this.padding + leafMap[i].height;
626 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
627 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
628 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
629 if (topInView | bottomInView | middleInView) {
630 //console.log('row to display: ' + j);
631 rowsToDisplay.push(i);
633 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
634 leafTop = leafBottom;
637 // create a buffer of preloaded rows before and after the visible rows
638 var firstRow = rowsToDisplay[0];
639 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
640 for (i=1; i<this.thumbRowBuffer+1; i++) {
641 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
643 for (i=1; i<this.thumbRowBuffer+1; i++) {
644 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
647 // Update hash, but only if we're currently displaying a leaf
648 // Hack that fixes #365790
649 if (this.displayedRows.length > 0) {
650 this.updateLocationHash();
661 for (i=0; i<rowsToDisplay.length; i++) {
662 if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {
663 row = rowsToDisplay[i];
665 for (j=0; j<leafMap[row].leafs.length; j++) {
667 leaf = leafMap[row].leafs[j].num;
669 leafWidth = this.thumbWidth;
670 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
671 leafTop = leafMap[row].top;
672 left = leafMap[row].leafs[index].left + pageViewBuffer;
673 if ('rl' == this.pageProgression){
674 left = viewWidth - leafWidth - left;
677 div = document.createElement("div");
678 div.id = 'pagediv'+leaf;
679 div.style.position = "absolute";
680 div.className = "BRpagedivthumb";
682 left += this.padding;
683 $(div).css('top', leafTop + 'px');
684 $(div).css('left', left+'px');
685 $(div).css('width', leafWidth+'px');
686 $(div).css('height', leafHeight+'px');
687 //$(div).text('loading...');
689 // link to page in single page mode
690 // $$$ direct JS calls instead should reduce visual disruption
691 link = document.createElement("a");
692 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
695 $('#BRpageview').append(div);
697 img = document.createElement("img");
698 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
699 img.src = this._getPageURI(leaf, thumbReduce);
700 $(img).css('width', leafWidth+'px');
701 $(img).css('height', leafHeight+'px');
702 img.style.border = "0";
704 //console.log('displaying thumbnail: ' + leafMap[j]);
709 // remove previous highlights
710 if ($('.BRpagedivthumb_highlight').length>0) {
711 div = $('.BRpagedivthumb_highlight')
712 div.attr({className: 'BRpagedivthumb' });
714 // highlight current page
715 $('#pagediv'+this.currentIndex()).attr({className: 'BRpagedivthumb_highlight' });
718 for (i=0; i<this.displayedRows.length; i++) {
719 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
720 row = this.displayedRows[i];
721 for (k=0; k<leafMap[row].leafs.length; k++) {
722 index = leafMap[row].leafs[k].num;
723 //console.log('Removing leaf ' + index);
724 $('#pagediv'+index).remove();
728 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
732 this.displayedRows = rowsToDisplay.slice();
734 if (null !== this.getPageNum(this.currentIndex())) {
735 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
737 $("#BRpagenum").val('');
740 this.updateToolbarZoom(this.reduce);
743 // drawLeafsTwoPage()
744 //______________________________________________________________________________
745 BookReader.prototype.drawLeafsTwoPage = function() {
746 var scrollTop = $('#BRtwopageview').attr('scrollTop');
747 var scrollBottom = scrollTop + $('#BRtwopageview').height();
749 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
751 var indexL = this.twoPage.currentIndexL;
753 var heightL = this._getPageHeight(indexL);
754 var widthL = this._getPageWidth(indexL);
756 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
757 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
758 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
759 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
760 //console.log(leafEdgeWidthL);
762 var middle = this.twoPage.middle; // $$$ getter instead?
763 var top = this.twoPageTop();
764 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
766 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
767 this.twoPage.gutter = this.twoPageGutter();
769 this.prefetchImg(indexL);
770 $(this.prefetchedImgs[indexL]).css({
771 position: 'absolute',
772 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
775 backgroundColor: this.getPageBackgroundColor(indexL),
776 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
777 width: this.twoPage.scaledWL + 'px',
778 borderRight: '1px solid black',
780 }).appendTo('#BRtwopageview');
782 var indexR = this.twoPage.currentIndexR;
783 var heightR = this._getPageHeight(indexR);
784 var widthR = this._getPageWidth(indexR);
786 // $$$ should use getwidth2up?
787 //var scaledWR = this.twoPage.height*widthR/heightR;
788 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
789 this.prefetchImg(indexR);
790 $(this.prefetchedImgs[indexR]).css({
791 position: 'absolute',
792 left: this.twoPage.gutter+'px',
795 backgroundColor: this.getPageBackgroundColor(indexR),
796 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
797 width: this.twoPage.scaledWR + 'px',
798 borderLeft: '1px solid black',
800 }).appendTo('#BRtwopageview');
803 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
804 this.setMouseHandlers2UP();
805 this.twoPageSetCursor();
807 this.updatePageNumBox2UP();
808 this.updateToolbarZoom(this.reduce);
810 // this.twoPagePlaceFlipAreas(); // No longer used
814 // updatePageNumBox2UP
815 //______________________________________________________________________________
816 BookReader.prototype.updatePageNumBox2UP = function() {
817 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
818 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
820 $("#BRpagenum").val('');
822 this.updateLocationHash();
826 //______________________________________________________________________________
827 BookReader.prototype.loadLeafs = function() {
831 if (null == this.timer) {
832 this.timer=setTimeout(function(){self.drawLeafs()},250);
834 clearTimeout(this.timer);
835 this.timer=setTimeout(function(){self.drawLeafs()},250);
841 // Pass 1 to zoom in, anything else to zoom out
842 //______________________________________________________________________________
843 BookReader.prototype.zoom = function(direction) {
845 case this.constMode1up:
846 return this.zoom1up(direction);
847 case this.constMode2up:
848 return this.zoom2up(direction);
853 //______________________________________________________________________________
854 BookReader.prototype.zoom1up = function(dir) {
856 if (2 == this.mode) { //can only zoom in 1-page mode
861 // $$$ with flexible zoom we could "snap" to /2 page reductions
862 // for better scaling
864 if (this.reduce <= 0.5) return;
865 this.reduce*=0.5; //zoom in
867 if (this.reduce >= 8) return;
868 this.reduce*=2; //zoom out
871 this.pageScale = this.reduce; // preserve current reduce
872 this.resizePageView();
874 $('#BRpageview').empty()
875 this.displayedIndices = [];
878 this.updateToolbarZoom(this.reduce);
880 // Recalculate search hilites
881 this.removeSearchHilites();
882 this.updateSearchHilites();
887 //______________________________________________________________________________
888 BookReader.prototype.resizePageView = function() {
891 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
892 var viewWidth = $('#BRcontainer').attr('clientWidth');
894 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
895 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
896 var oldPageViewHeight = $('#BRpageview').height();
897 var oldPageViewWidth = $('#BRpageview').width();
899 var oldCenterY = this.centerY1up();
900 var oldCenterX = this.centerX1up();
902 if (0 != oldPageViewHeight) {
903 var scrollRatio = oldCenterY / oldPageViewHeight;
908 for (i=0; i<this.numLeafs; i++) {
909 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
910 var width = parseInt(this._getPageWidth(i)/this.reduce);
911 if (width>viewWidth) viewWidth=width;
913 $('#BRpageview').height(viewHeight);
914 $('#BRpageview').width(viewWidth);
916 var newCenterY = scrollRatio*viewHeight;
917 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
918 $('#BRcontainer').attr('scrollTop', newTop);
920 // We use clientWidth here to avoid miscalculating due to scroll bar
921 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
922 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
923 newLeft = Math.max(newLeft, 0);
924 $('#BRcontainer').attr('scrollLeft', newLeft);
925 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
927 //this.centerPageView();
930 // Not really needed until there is 1up autofit
931 this.removeSearchHilites();
932 this.updateSearchHilites();
936 //______________________________________________________________________________
937 // Returns the current offset of the viewport center in scaled document coordinates.
938 BookReader.prototype.centerX1up = function() {
940 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
941 centerX = $('#BRpageview').width();
943 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
945 centerX = Math.floor(centerX);
950 //______________________________________________________________________________
951 // Returns the current offset of the viewport center in scaled document coordinates.
952 BookReader.prototype.centerY1up = function() {
953 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
954 return Math.floor(centerY);
958 //______________________________________________________________________________
959 BookReader.prototype.centerPageView = function() {
961 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
962 var clientWidth = $('#BRcontainer').attr('clientWidth');
963 //console.log('sW='+scrollWidth+' cW='+clientWidth);
964 if (scrollWidth > clientWidth) {
965 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
970 // zoom2up(direction)
971 //______________________________________________________________________________
972 BookReader.prototype.zoom2up = function(direction) {
974 // Hard stop autoplay
975 this.stopFlipAnimations();
977 // Get new zoom state
978 var newZoom = this.twoPageNextReduce(this.reduce, direction);
979 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
982 this.twoPage.autofit = newZoom.autofit;
983 this.reduce = newZoom.reduce;
984 this.pageScale = this.reduce; // preserve current reduce
986 // Preserve view center position
987 var oldCenter = this.twoPageGetViewCenter();
989 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
990 // $$$ An improvement would be to use the low res image until the larger one is loaded.
991 if (1 == direction) {
992 for (var img in this.prefetchedImgs) {
993 delete this.prefetchedImgs[img];
997 // Prepare view with new center to minimize visual glitches
998 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1002 // quantizeReduce(reduce)
1003 //______________________________________________________________________________
1004 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1005 BookReader.prototype.quantizeReduce = function(reduce) {
1006 var quantized = this.reductionFactors[0];
1007 var distance = Math.abs(reduce - quantized);
1008 for (var i = 1; i < this.reductionFactors.length; i++) {
1009 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1010 if (newDistance < distance) {
1011 distance = newDistance;
1012 quantized = this.reductionFactors[i];
1019 // twoPageNextReduce()
1020 //______________________________________________________________________________
1021 // Returns the next reduction level
1022 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1024 var autofitReduce = this.twoPageGetAutofitReduce();
1026 if (0 == direction) { // autofit
1027 result.autofit = true;
1028 result.reduce = autofitReduce;
1030 } else if (1 == direction) { // zoom in
1031 var newReduce = this.reductionFactors[0];
1033 for (var i = 1; i < this.reductionFactors.length; i++) {
1034 if (this.reductionFactors[i] < reduce) {
1035 newReduce = this.reductionFactors[i];
1039 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1041 result.autofit = true;
1042 result.reduce = autofitReduce;
1044 result.autofit = false;
1045 result.reduce = newReduce;
1048 } else { // zoom out
1049 var lastIndex = this.reductionFactors.length - 1;
1050 var newReduce = this.reductionFactors[lastIndex];
1052 for (var i = lastIndex; i >= 0; i--) {
1053 if (this.reductionFactors[i] > reduce) {
1054 newReduce = this.reductionFactors[i];
1058 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1060 result.autofit = true;
1061 result.reduce = autofitReduce;
1063 result.autofit = false;
1064 result.reduce = newReduce;
1072 //______________________________________________________________________________
1073 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1074 BookReader.prototype.jumpToPage = function(pageNum) {
1076 var pageIndex = this.getPageIndex(pageNum);
1078 if ('undefined' != typeof(pageIndex)) {
1081 this.jumpToIndex(pageIndex);
1082 $('#BRcontainer').attr('scrollTop', leafTop);
1091 //______________________________________________________________________________
1092 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1094 if (2 == this.mode) {
1097 // By checking against min/max we do nothing if requested index
1099 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1100 this.flipBackToIndex(index);
1101 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1102 this.flipFwdToIndex(index);
1105 } else if (3 == this.mode) {
1106 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1116 for (i=0; i<(index+1); i++) {
1117 leafWidth = this.thumbWidth;
1118 if (rightPos + (leafWidth + this.padding) > viewWidth){
1123 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1124 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1125 if (leafIndex==0) { leafTop = bottomPos; }
1126 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1127 rightPos += leafWidth + this.padding;
1130 this.firstIndex=index;
1131 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1134 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1141 for (i=0; i<index; i++) {
1142 h = parseInt(this._getPageHeight(i)/this.reduce);
1143 leafTop += h + this.padding;
1147 //console.log('pageY ' + pageY);
1148 var offset = parseInt( (pageY) / this.reduce);
1149 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1150 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1155 var offset = parseInt( (pageX) / this.reduce);
1156 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1160 //$('#BRcontainer').attr('scrollTop', leafTop);
1161 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1167 //______________________________________________________________________________
1168 BookReader.prototype.switchMode = function(mode) {
1170 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1172 if (mode == this.mode) return;
1174 if (!this.canSwitchToMode(mode)) {
1179 this.removeSearchHilites();
1182 this.switchToolbarMode(mode);
1184 // reinstate scale if moving from thumbnail view
1185 if (this.pageScale != this.reduce) this.reduce = this.pageScale;
1187 // $$$ TODO preserve center of view when switching between mode
1188 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1191 this.reduce = this.quantizeReduce(this.reduce);
1192 this.prepareOnePageView();
1193 } else if (3 == mode) {
1194 this.reduce = this.quantizeReduce(this.reduce);
1195 this.prepareThumbnailView();
1196 this.jumpToIndex(this.currentIndex());
1198 this.twoPage.autofit = false; // Take zoom level from other mode
1199 this.reduce = this.quantizeReduce(this.reduce);
1200 this.prepareTwoPageView();
1201 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1206 //prepareOnePageView()
1207 //______________________________________________________________________________
1208 BookReader.prototype.prepareOnePageView = function() {
1210 // var startLeaf = this.displayedIndices[0];
1211 var startLeaf = this.currentIndex();
1213 $('#BRcontainer').empty();
1214 $('#BRcontainer').css({
1215 overflowY: 'scroll',
1219 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1221 this.resizePageView();
1223 this.jumpToIndex(startLeaf);
1224 this.displayedIndices = [];
1226 this.drawLeafsOnePage();
1228 // Bind mouse handlers
1229 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1230 brPageView.bind('mousedown', function(e) {
1231 // $$$ check here for right-click and don't disable. Also use jQuery style
1232 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1235 // Special hack for IE7
1236 brPageView[0].onselectstart = function(e) { return false; };
1239 //prepareThumbnailView()
1240 //______________________________________________________________________________
1241 BookReader.prototype.prepareThumbnailView = function() {
1243 // var startLeaf = this.displayedIndices[0];
1244 var startLeaf = this.currentIndex();
1245 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1247 $('#BRcontainer').empty();
1248 $('#BRcontainer').css({
1249 overflowY: 'scroll',
1253 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1255 this.resizePageView();
1257 this.displayedRows = [];
1258 this.drawLeafsThumbnail();
1260 // Bind mouse handlers
1261 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1262 brPageView.bind('mousedown', function(e) {
1263 // $$$ check here for right-click and don't disable. Also use jQuery style
1264 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1267 // Special hack for IE7
1268 brPageView[0].onselectstart = function(e) { return false; };
1271 // prepareTwoPageView()
1272 //______________________________________________________________________________
1273 // Some decisions about two page view:
1275 // Both pages will be displayed at the same height, even if they were different physical/scanned
1276 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1277 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1278 // aspect ratio to determine the height.
1280 // The two page view div is resized to keep the middle of the book in the middle of the div
1281 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1282 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1283 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1284 $('#BRcontainer').empty();
1285 $('#BRcontainer').css('overflow', 'auto');
1287 // We want to display two facing pages. We may be missing
1288 // one side of the spread because it is the first/last leaf,
1289 // foldouts, missing pages, etc
1291 //var targetLeaf = this.displayedIndices[0];
1292 var targetLeaf = this.firstIndex;
1294 if (targetLeaf < this.firstDisplayableIndex()) {
1295 targetLeaf = this.firstDisplayableIndex();
1298 if (targetLeaf > this.lastDisplayableIndex()) {
1299 targetLeaf = this.lastDisplayableIndex();
1302 //this.twoPage.currentIndexL = null;
1303 //this.twoPage.currentIndexR = null;
1304 //this.pruneUnusedImgs();
1306 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1307 this.twoPage.currentIndexL = currentSpreadIndices[0];
1308 this.twoPage.currentIndexR = currentSpreadIndices[1];
1309 this.firstIndex = this.twoPage.currentIndexL;
1311 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1313 this.pruneUnusedImgs();
1314 this.prefetch(); // Preload images or reload if scaling has changed
1316 //console.dir(this.twoPage);
1318 // Add the two page view
1319 // $$$ Can we get everything set up and then append?
1320 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1322 // $$$ calculate first then set
1323 $('#BRtwopageview').css( {
1324 height: this.twoPage.totalHeight + 'px',
1325 width: this.twoPage.totalWidth + 'px',
1326 position: 'absolute'
1329 // If there will not be scrollbars (e.g. when zooming out) we center the book
1330 // since otherwise the book will be stuck off-center
1331 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1332 centerPercentageX = 0.5;
1334 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1335 centerPercentageY = 0.5;
1338 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1340 this.twoPage.coverDiv = document.createElement('div');
1341 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1342 border: '1px solid rgb(68, 25, 17)',
1343 width: this.twoPage.bookCoverDivWidth + 'px',
1344 height: this.twoPage.bookCoverDivHeight+'px',
1345 visibility: 'visible',
1346 position: 'absolute',
1347 backgroundColor: '#663929',
1348 left: this.twoPage.bookCoverDivLeft + 'px',
1349 top: this.twoPage.bookCoverDivTop+'px',
1350 MozBorderRadiusTopleft: '7px',
1351 MozBorderRadiusTopright: '7px',
1352 MozBorderRadiusBottomright: '7px',
1353 MozBorderRadiusBottomleft: '7px'
1354 }).appendTo('#BRtwopageview');
1356 this.leafEdgeR = document.createElement('div');
1357 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1358 $(this.leafEdgeR).css({
1359 borderStyle: 'solid solid solid none',
1360 borderColor: 'rgb(51, 51, 34)',
1361 borderWidth: '1px 1px 1px 0px',
1362 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1363 width: this.twoPage.leafEdgeWidthR + 'px',
1364 height: this.twoPage.height-1 + 'px',
1366 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1367 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1368 position: 'absolute'
1369 }).appendTo('#BRtwopageview');
1371 this.leafEdgeL = document.createElement('div');
1372 this.leafEdgeL.className = 'leafEdgeL';
1373 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1374 borderStyle: 'solid none solid solid',
1375 borderColor: 'rgb(51, 51, 34)',
1376 borderWidth: '1px 0px 1px 1px',
1377 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1378 width: this.twoPage.leafEdgeWidthL + 'px',
1379 height: this.twoPage.height-1 + 'px',
1380 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1381 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1382 position: 'absolute'
1383 }).appendTo('#BRtwopageview');
1385 div = document.createElement('div');
1386 $(div).attr('id', 'BRbookspine').css({
1387 border: '1px solid rgb(68, 25, 17)',
1388 width: this.twoPage.bookSpineDivWidth+'px',
1389 height: this.twoPage.bookSpineDivHeight+'px',
1390 position: 'absolute',
1391 backgroundColor: 'rgb(68, 25, 17)',
1392 left: this.twoPage.bookSpineDivLeft+'px',
1393 top: this.twoPage.bookSpineDivTop+'px'
1394 }).appendTo('#BRtwopageview');
1396 var self = this; // for closure
1398 /* Flip areas no longer used
1399 this.twoPage.leftFlipArea = document.createElement('div');
1400 this.twoPage.leftFlipArea.className = 'BRfliparea';
1401 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1403 width: this.twoPageFlipAreaWidth() + 'px',
1404 height: this.twoPageFlipAreaHeight() + 'px',
1405 position: 'absolute',
1406 left: this.twoPageLeftFlipAreaLeft() + 'px',
1407 top: this.twoPageFlipAreaTop() + 'px',
1410 }).bind('click', function(e) {
1412 }).bind('mousedown', function(e) {
1414 }).appendTo('#BRtwopageview');
1416 this.twoPage.rightFlipArea = document.createElement('div');
1417 this.twoPage.rightFlipArea.className = 'BRfliparea';
1418 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1420 width: this.twoPageFlipAreaWidth() + 'px',
1421 height: this.twoPageFlipAreaHeight() + 'px',
1422 position: 'absolute',
1423 left: this.twoPageRightFlipAreaLeft() + 'px',
1424 top: this.twoPageFlipAreaTop() + 'px',
1427 }).bind('click', function(e) {
1429 }).bind('mousedown', function(e) {
1431 }).appendTo('#BRtwopageview');
1434 this.prepareTwoPagePopUp();
1436 this.displayedIndices = [];
1438 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1439 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1441 this.drawLeafsTwoPage();
1442 this.updateToolbarZoom(this.reduce);
1446 this.removeSearchHilites();
1447 this.updateSearchHilites();
1451 // prepareTwoPagePopUp()
1453 // This function prepares the "View Page n" popup that shows while the mouse is
1454 // over the left/right "stack of sheets" edges. It also binds the mouse
1455 // events for these divs.
1456 //______________________________________________________________________________
1457 BookReader.prototype.prepareTwoPagePopUp = function() {
1459 this.twoPagePopUp = document.createElement('div');
1460 $(this.twoPagePopUp).css({
1461 border: '1px solid black',
1463 position: 'absolute',
1464 fontFamily: 'sans-serif',
1467 backgroundColor: 'rgb(255, 255, 238)',
1469 }).appendTo('#BRcontainer');
1470 $(this.twoPagePopUp).hide();
1472 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1473 $(e.data.twoPagePopUp).show();
1476 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1477 $(e.data.twoPagePopUp).hide();
1480 $(this.leafEdgeL).bind('click', this, function(e) {
1482 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1483 e.data.jumpToIndex(jumpIndex);
1486 $(this.leafEdgeR).bind('click', this, function(e) {
1488 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1489 e.data.jumpToIndex(jumpIndex);
1492 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1494 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1495 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1497 // $$$ TODO: Make sure popup is positioned so that it is in view
1498 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1499 $(e.data.twoPagePopUp).css({
1500 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1501 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1505 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1507 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1508 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1510 // $$$ TODO: Make sure popup is positioned so that it is in view
1511 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1512 $(e.data.twoPagePopUp).css({
1513 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1514 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1519 // calculateSpreadSize()
1520 //______________________________________________________________________________
1521 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1522 // this.twoPage.currentIndexR
1523 // This function sets this.twoPage.height, twoPage.width
1525 BookReader.prototype.calculateSpreadSize = function() {
1527 var firstIndex = this.twoPage.currentIndexL;
1528 var secondIndex = this.twoPage.currentIndexR;
1529 //console.log('first page is ' + firstIndex);
1531 // Calculate page sizes and total leaf width
1533 if ( this.twoPage.autofit) {
1534 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1536 // set based on reduction factor
1537 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1540 // Both pages together
1541 this.twoPage.height = spreadSize.height;
1542 this.twoPage.width = spreadSize.width;
1545 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1546 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1549 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1550 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1551 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1555 // The width of the book cover div. The combined width of both pages, twice the width
1556 // of the book cover internal padding (2*10) and the page edges
1557 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1558 // The height of the book cover div
1559 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1562 // We calculate the total width and height for the div so that we can make the book
1564 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1565 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1566 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1567 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1568 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1569 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1571 // We want to minimize the unused space in two-up mode (maximize the amount of page
1572 // shown). We give width to the leaf edges and these widths change (though the sum
1573 // of the two remains constant) as we flip through the book. With the book
1574 // cover centered and fixed in the BRcontainer div the page images will meet
1575 // at the "gutter" which is generally offset from the center.
1576 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1577 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1579 // The left edge of the book cover moves depending on the width of the pages
1580 // $$$ change to getter
1581 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1582 // The top edge of the book cover stays a fixed distance from the top
1583 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1586 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1587 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1588 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1591 this.reduce = spreadSize.reduce; // $$$ really set this here?
1594 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1597 // We check which page is closest to a "normal" page and use that to set the height
1598 // for both pages. This means that foldouts and other odd size pages will be displayed
1599 // smaller than the nominal zoom amount.
1600 var canon5Dratio = 1.5;
1603 height: this._getPageHeight(firstIndex),
1604 width: this._getPageWidth(firstIndex)
1608 height: this._getPageHeight(secondIndex),
1609 width: this._getPageWidth(secondIndex)
1612 var firstIndexRatio = first.height / first.width;
1613 var secondIndexRatio = second.height / second.width;
1614 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1617 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1618 ratio = firstIndexRatio;
1619 //console.log('using firstIndexRatio ' + ratio);
1621 ratio = secondIndexRatio;
1622 //console.log('using secondIndexRatio ' + ratio);
1625 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1626 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1627 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1629 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1630 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1632 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1633 ideal.width -= 10; // $$$ fudge factor
1634 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1635 ideal.height -= 20; // fudge factor
1636 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1638 if (ideal.height/ratio <= ideal.width) {
1640 ideal.width = parseInt(ideal.height/ratio);
1643 ideal.height = parseInt(ideal.width*ratio);
1646 // $$$ check this logic with large spreads
1647 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1652 // getSpreadSizeFromReduce()
1653 //______________________________________________________________________________
1654 // Returns the spread size calculated from the reduction factor for the given pages
1655 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1656 var spreadSize = {};
1657 // $$$ Scale this based on reduce?
1658 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1659 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1660 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1662 // $$$ Possibly incorrect -- we should make height "dominant"
1663 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1664 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1665 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1666 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1667 spreadSize.reduce = reduce;
1672 // twoPageGetAutofitReduce()
1673 //______________________________________________________________________________
1674 // Returns the current ideal reduction factor
1675 BookReader.prototype.twoPageGetAutofitReduce = function() {
1676 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1677 return spreadSize.reduce;
1680 // twoPageSetCursor()
1681 //______________________________________________________________________________
1682 // Set the cursor for two page view
1683 BookReader.prototype.twoPageSetCursor = function() {
1684 // console.log('setting cursor');
1685 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1686 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1687 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1688 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1690 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1691 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1696 //______________________________________________________________________________
1697 // Returns the currently active index.
1698 BookReader.prototype.currentIndex = function() {
1699 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1700 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1701 return this.firstIndex; // $$$ TODO page in center of view would be better
1702 } else if (this.mode == this.constMode2up) {
1703 // Only allow indices that are actually present in book
1704 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1706 throw 'currentIndex called for unimplemented mode ' + this.mode;
1711 //______________________________________________________________________________
1712 // Flip the right page over onto the left
1713 BookReader.prototype.right = function() {
1714 if ('rl' != this.pageProgression) {
1724 //______________________________________________________________________________
1725 // Flip to the rightmost page
1726 BookReader.prototype.rightmost = function() {
1727 if ('rl' != this.pageProgression) {
1735 //______________________________________________________________________________
1736 // Flip the left page over onto the right.
1737 BookReader.prototype.left = function() {
1738 if ('rl' != this.pageProgression) {
1748 //______________________________________________________________________________
1749 // Flip to the leftmost page
1750 BookReader.prototype.leftmost = function() {
1751 if ('rl' != this.pageProgression) {
1759 //______________________________________________________________________________
1760 BookReader.prototype.next = function() {
1761 if (2 == this.mode) {
1763 this.flipFwdToIndex(null);
1765 if (this.firstIndex < this.lastDisplayableIndex()) {
1766 this.jumpToIndex(this.firstIndex+1);
1772 //______________________________________________________________________________
1773 BookReader.prototype.prev = function() {
1774 if (2 == this.mode) {
1776 this.flipBackToIndex(null);
1778 if (this.firstIndex >= 1) {
1779 this.jumpToIndex(this.firstIndex-1);
1784 BookReader.prototype.first = function() {
1785 this.jumpToIndex(this.firstDisplayableIndex());
1788 BookReader.prototype.last = function() {
1789 this.jumpToIndex(this.lastDisplayableIndex());
1793 //______________________________________________________________________________
1794 // Scrolls down one screen view
1795 BookReader.prototype.scrollDown = function() {
1796 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1797 $('#BRcontainer').animate(
1798 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1799 450, 'easeInOutQuint'
1808 //______________________________________________________________________________
1809 // Scrolls up one screen view
1810 BookReader.prototype.scrollUp = function() {
1811 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1812 $('#BRcontainer').animate(
1813 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1814 450, 'easeInOutQuint'
1823 // flipBackToIndex()
1824 //______________________________________________________________________________
1825 // to flip back one spread, pass index=null
1826 BookReader.prototype.flipBackToIndex = function(index) {
1828 if (1 == this.mode) return;
1830 var leftIndex = this.twoPage.currentIndexL;
1832 if (this.animating) return;
1834 if (null != this.leafEdgeTmp) {
1835 alert('error: leafEdgeTmp should be null!');
1839 if (null == index) {
1840 index = leftIndex-2;
1842 //if (index<0) return;
1844 var previousIndices = this.getSpreadIndices(index);
1846 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1850 this.animating = true;
1852 if ('rl' != this.pageProgression) {
1853 // Assume LTR and we are going backward
1854 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1855 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1857 // RTL and going backward
1858 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1859 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1863 // flipLeftToRight()
1864 //______________________________________________________________________________
1865 // Flips the page on the left towards the page on the right
1866 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1868 var leftLeaf = this.twoPage.currentIndexL;
1870 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1871 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1872 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1874 var currWidthL = this.getPageWidth2UP(leftLeaf);
1875 var newWidthL = this.getPageWidth2UP(newIndexL);
1876 var newWidthR = this.getPageWidth2UP(newIndexR);
1878 var top = this.twoPageTop();
1879 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1881 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1882 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1884 //animation strategy:
1885 // 0. remove search highlight, if any.
1886 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1887 // of the left leaf and where the user clicked in the leaf edge.
1888 // Note that if this function was triggered by left() and not a
1889 // mouse click, the width of leafEdgeTmp is very small (zero px).
1890 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1891 // leftLeaf to width=0.
1892 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1893 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1894 // its new full width.
1895 // 4. After step 3 is finished, do the following:
1896 // - remove leafEdgeTmp from the dom.
1897 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1898 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1899 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1900 // and width=newLeafEdgeWidthL.
1901 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1902 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1903 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1904 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1905 // - prefetch new adjacent leafs.
1906 // - set up click handlers for both new left and right leafs.
1907 // - redraw the search highlight.
1908 // - update the pagenum box and the url.
1911 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1913 this.leafEdgeTmp = document.createElement('div');
1914 $(this.leafEdgeTmp).css({
1915 borderStyle: 'solid none solid solid',
1916 borderColor: 'rgb(51, 51, 34)',
1917 borderWidth: '1px 0px 1px 1px',
1918 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1919 width: leafEdgeTmpW + 'px',
1920 height: this.twoPage.height-1 + 'px',
1921 left: leftEdgeTmpLeft + 'px',
1923 position: 'absolute',
1925 }).appendTo('#BRtwopageview');
1927 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1928 $(this.leafEdgeL).css({
1929 width: newLeafEdgeWidthL+'px',
1930 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1933 // Left gets the offset of the current left leaf from the document
1934 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1935 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1936 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1938 // We change the left leaf to right positioning
1939 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1940 $(this.prefetchedImgs[leftLeaf]).css({
1945 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1946 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1950 this.removeSearchHilites();
1952 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1953 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1955 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1956 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1958 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1959 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1960 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1962 $(self.leafEdgeR).css({
1963 // Moves the right leaf edge
1964 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1965 left: gutter+newWidthR+'px'
1968 $(self.leafEdgeL).css({
1969 // Moves and resizes the left leaf edge
1970 width: newLeafEdgeWidthL+'px',
1971 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1974 // Resizes the brown border div
1975 $(self.twoPage.coverDiv).css({
1976 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1977 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1980 $(self.leafEdgeTmp).remove();
1981 self.leafEdgeTmp = null;
1983 // $$$ TODO refactor with opposite direction flip
1985 self.twoPage.currentIndexL = newIndexL;
1986 self.twoPage.currentIndexR = newIndexR;
1987 self.twoPage.scaledWL = newWidthL;
1988 self.twoPage.scaledWR = newWidthR;
1989 self.twoPage.gutter = gutter;
1991 self.firstIndex = self.twoPage.currentIndexL;
1992 self.displayedIndices = [newIndexL, newIndexR];
1993 self.pruneUnusedImgs();
1995 self.animating = false;
1997 self.updateSearchHilites2UP();
1998 self.updatePageNumBox2UP();
2000 // self.twoPagePlaceFlipAreas(); // No longer used
2001 self.setMouseHandlers2UP();
2002 self.twoPageSetCursor();
2004 if (self.animationFinishedCallback) {
2005 self.animationFinishedCallback();
2006 self.animationFinishedCallback = null;
2014 //______________________________________________________________________________
2015 // Whether we flip left or right is dependent on the page progression
2016 // to flip forward one spread, pass index=null
2017 BookReader.prototype.flipFwdToIndex = function(index) {
2019 if (this.animating) return;
2021 if (null != this.leafEdgeTmp) {
2022 alert('error: leafEdgeTmp should be null!');
2026 if (null == index) {
2027 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2029 if (index > this.lastDisplayableIndex()) return;
2031 this.animating = true;
2033 var nextIndices = this.getSpreadIndices(index);
2035 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2037 if ('rl' != this.pageProgression) {
2038 // We did not specify RTL
2039 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2040 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2043 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2044 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2048 // flipRightToLeft(nextL, nextR, gutter)
2049 // $$$ better not to have to pass gutter in
2050 //______________________________________________________________________________
2051 // Flip from left to right and show the nextL and nextR indices on those sides
2052 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2053 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2054 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2055 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2056 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2058 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2060 var top = this.twoPageTop();
2061 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2063 var middle = this.twoPage.middle;
2064 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2066 this.leafEdgeTmp = document.createElement('div');
2067 $(this.leafEdgeTmp).css({
2068 borderStyle: 'solid none solid solid',
2069 borderColor: 'rgb(51, 51, 34)',
2070 borderWidth: '1px 0px 1px 1px',
2071 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2072 width: leafEdgeTmpW + 'px',
2073 height: this.twoPage.height-1 + 'px',
2074 left: gutter+scaledW+'px',
2076 position: 'absolute',
2078 }).appendTo('#BRtwopageview');
2080 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2081 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2083 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2084 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2085 var newWidthL = this.getPageWidth2UP(newIndexL);
2086 var newWidthR = this.getPageWidth2UP(newIndexR);
2088 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2090 var self = this; // closure-tastic!
2092 var speed = this.flipSpeed;
2094 this.removeSearchHilites();
2096 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2097 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2098 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2099 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2100 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2102 $(self.leafEdgeL).css({
2103 width: newLeafEdgeWidthL+'px',
2104 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2107 // Resizes the book cover
2108 $(self.twoPage.coverDiv).css({
2109 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2110 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2113 $(self.leafEdgeTmp).remove();
2114 self.leafEdgeTmp = null;
2116 self.twoPage.currentIndexL = newIndexL;
2117 self.twoPage.currentIndexR = newIndexR;
2118 self.twoPage.scaledWL = newWidthL;
2119 self.twoPage.scaledWR = newWidthR;
2120 self.twoPage.gutter = gutter;
2122 self.firstIndex = self.twoPage.currentIndexL;
2123 self.displayedIndices = [newIndexL, newIndexR];
2124 self.pruneUnusedImgs();
2126 self.animating = false;
2129 self.updateSearchHilites2UP();
2130 self.updatePageNumBox2UP();
2132 // self.twoPagePlaceFlipAreas(); // No longer used
2133 self.setMouseHandlers2UP();
2134 self.twoPageSetCursor();
2136 if (self.animationFinishedCallback) {
2137 self.animationFinishedCallback();
2138 self.animationFinishedCallback = null;
2144 // setMouseHandlers2UP
2145 //______________________________________________________________________________
2146 BookReader.prototype.setMouseHandlers2UP = function() {
2148 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2153 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2160 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2161 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2168 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2169 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2172 e.data.self.right();
2178 //______________________________________________________________________________
2179 BookReader.prototype.prefetchImg = function(index) {
2180 var pageURI = this._getPageURI(index);
2182 // Load image if not loaded or URI has changed (e.g. due to scaling)
2183 var loadImage = false;
2184 if (undefined == this.prefetchedImgs[index]) {
2185 //console.log('no image for ' + index);
2187 } else if (pageURI != this.prefetchedImgs[index].uri) {
2188 //console.log('uri changed for ' + index);
2193 //console.log('prefetching ' + index);
2194 var img = document.createElement("img");
2196 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2197 this.prefetchedImgs[index] = img;
2202 // prepareFlipLeftToRight()
2204 //______________________________________________________________________________
2206 // Prepare to flip the left page towards the right. This corresponds to moving
2207 // backward when the page progression is left to right.
2208 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2210 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2212 this.prefetchImg(prevL);
2213 this.prefetchImg(prevR);
2215 var height = this._getPageHeight(prevL);
2216 var width = this._getPageWidth(prevL);
2217 var middle = this.twoPage.middle;
2218 var top = this.twoPageTop();
2219 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2221 // The gutter is the dividing line between the left and right pages.
2222 // It is offset from the middle to create the illusion of thickness to the pages
2223 var gutter = middle + this.gutterOffsetForIndex(prevL);
2225 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2226 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2227 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2230 position: 'absolute',
2231 left: gutter-scaledW+'px',
2232 right: '', // clear right property
2234 height: this.twoPage.height,
2235 width: scaledW+'px',
2236 backgroundColor: this.getPageBackgroundColor(prevL),
2237 borderRight: '1px solid black',
2241 $(this.prefetchedImgs[prevL]).css(leftCSS);
2243 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2245 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2248 position: 'absolute',
2252 height: this.twoPage.height,
2254 backgroundColor: this.getPageBackgroundColor(prevR),
2255 borderLeft: '1px solid black',
2259 $(this.prefetchedImgs[prevR]).css(rightCSS);
2261 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2265 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2266 // prepareFlipRightToLeft()
2267 //______________________________________________________________________________
2268 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2270 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2273 this.prefetchImg(nextL);
2274 this.prefetchImg(nextR);
2276 var height = this._getPageHeight(nextR);
2277 var width = this._getPageWidth(nextR);
2278 var middle = this.twoPage.middle;
2279 var top = this.twoPageTop();
2280 var scaledW = this.twoPage.height*width/height;
2282 var gutter = middle + this.gutterOffsetForIndex(nextL);
2284 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2285 $(this.prefetchedImgs[nextR]).css({
2286 position: 'absolute',
2289 backgroundColor: this.getPageBackgroundColor(nextR),
2290 height: this.twoPage.height,
2291 width: scaledW+'px',
2292 borderLeft: '1px solid black',
2296 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2298 height = this._getPageHeight(nextL);
2299 width = this._getPageWidth(nextL);
2300 scaledW = this.twoPage.height*width/height;
2302 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2303 $(this.prefetchedImgs[nextL]).css({
2304 position: 'absolute',
2305 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2307 backgroundColor: this.getPageBackgroundColor(nextL),
2308 height: this.twoPage.height,
2309 width: 0+'px', // Start at 0 width, then grow to the left
2310 borderRight: '1px solid black',
2314 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2318 // getNextLeafs() -- NOT RTL AWARE
2319 //______________________________________________________________________________
2320 // BookReader.prototype.getNextLeafs = function(o) {
2321 // //TODO: we might have two left or two right leafs in a row (damaged book)
2322 // //For now, assume that leafs are contiguous.
2324 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2325 // o.L = this.twoPage.currentIndexL+2;
2326 // o.R = this.twoPage.currentIndexL+3;
2329 // getprevLeafs() -- NOT RTL AWARE
2330 //______________________________________________________________________________
2331 // BookReader.prototype.getPrevLeafs = function(o) {
2332 // //TODO: we might have two left or two right leafs in a row (damaged book)
2333 // //For now, assume that leafs are contiguous.
2335 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2336 // o.L = this.twoPage.currentIndexL-2;
2337 // o.R = this.twoPage.currentIndexL-1;
2340 // pruneUnusedImgs()
2341 //______________________________________________________________________________
2342 BookReader.prototype.pruneUnusedImgs = function() {
2343 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2344 for (var key in this.prefetchedImgs) {
2345 //console.log('key is ' + key);
2346 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2347 //console.log('removing key '+ key);
2348 $(this.prefetchedImgs[key]).remove();
2350 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2351 //console.log('deleting key '+ key);
2352 delete this.prefetchedImgs[key];
2358 //______________________________________________________________________________
2359 BookReader.prototype.prefetch = function() {
2361 // prefetch visible pages first
2362 this.prefetchImg(this.twoPage.currentIndexL);
2363 this.prefetchImg(this.twoPage.currentIndexR);
2365 var adjacentPagesToLoad = 3;
2367 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2368 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2370 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2371 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2373 // Load images spreading out from current
2374 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2375 var goingDown = lowCurrent - i;
2376 if (goingDown >= start) {
2377 this.prefetchImg(goingDown);
2379 var goingUp = highCurrent + i;
2380 if (goingUp <= end) {
2381 this.prefetchImg(goingUp);
2386 var lim = this.twoPage.currentIndexL-4;
2388 lim = Math.max(lim, 0);
2389 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2390 this.prefetchImg(i);
2393 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2394 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2395 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2396 this.prefetchImg(i);
2402 // getPageWidth2UP()
2403 //______________________________________________________________________________
2404 BookReader.prototype.getPageWidth2UP = function(index) {
2405 // We return the width based on the dominant height
2406 var height = this._getPageHeight(index);
2407 var width = this._getPageWidth(index);
2408 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2412 //______________________________________________________________________________
2413 BookReader.prototype.search = function(term) {
2414 term = term.replace(/\//g, ' '); // strip slashes
2415 this.searchTerm = term;
2416 $('#BookReaderSearchScript').remove();
2417 var script = document.createElement("script");
2418 script.setAttribute('id', 'BookReaderSearchScript');
2419 script.setAttribute("type", "text/javascript");
2420 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2421 document.getElementsByTagName('head')[0].appendChild(script);
2422 $('#BookReaderSearchBox').val(term);
2423 $('#BookReaderSearchResults').html('Searching...');
2426 // BRSearchCallback()
2427 //______________________________________________________________________________
2428 BookReader.prototype.BRSearchCallback = function(txt) {
2430 if (jQuery.browser.msie) {
2431 var dom=new ActiveXObject("Microsoft.XMLDOM");
2435 var parser = new DOMParser();
2436 var dom = parser.parseFromString(txt, "text/xml");
2439 $('#BookReaderSearchResults').empty();
2440 $('#BookReaderSearchResults').append('<ul>');
2442 for (var key in this.searchResults) {
2443 if (null != this.searchResults[key].div) {
2444 $(this.searchResults[key].div).remove();
2446 delete this.searchResults[key];
2449 var pages = dom.getElementsByTagName('PAGE');
2451 if (0 == pages.length) {
2452 // $$$ it would be nice to echo the (sanitized) search result here
2453 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2455 for (var i = 0; i < pages.length; i++){
2456 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2459 var re = new RegExp (/_(\d{4})\.djvu/);
2460 var reMatch = re.exec(pages[i].getAttribute('file'));
2461 var index = parseInt(reMatch[1], 10);
2462 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2464 var children = pages[i].childNodes;
2466 for (var j=0; j<children.length; j++) {
2467 //console.log(j + ' - ' + children[j].nodeName);
2468 //console.log(children[j].firstChild.nodeValue);
2469 if ('CONTEXT' == children[j].nodeName) {
2470 context += children[j].firstChild.nodeValue;
2471 } else if ('WORD' == children[j].nodeName) {
2472 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2474 var index = this.leafNumToIndex(index);
2475 if (null != index) {
2476 //coordinates are [left, bottom, right, top, [baseline]]
2477 //we'll skip baseline for now...
2478 var coords = children[j].getAttribute('coords').split(',',4);
2479 if (4 == coords.length) {
2480 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2485 var pageName = this.getPageName(index);
2486 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2487 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2488 //TODO: remove hardcoded instance name
2489 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2492 $('#BookReaderSearchResults').append('</ul>');
2494 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2495 $('#BookReaderSearchBox').val(this.searchTerm);
2497 this.updateSearchHilites();
2500 // updateSearchHilites()
2501 //______________________________________________________________________________
2502 BookReader.prototype.updateSearchHilites = function() {
2503 if (2 == this.mode) {
2504 this.updateSearchHilites2UP();
2506 this.updateSearchHilites1UP();
2510 // showSearchHilites1UP()
2511 //______________________________________________________________________________
2512 BookReader.prototype.updateSearchHilites1UP = function() {
2514 for (var key in this.searchResults) {
2516 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2517 var result = this.searchResults[key];
2518 if(null == result.div) {
2519 result.div = document.createElement('div');
2520 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2521 //console.log('appending ' + key);
2524 width: (result.r-result.l)/this.reduce + 'px',
2525 height: (result.b-result.t)/this.reduce + 'px',
2526 left: (result.l)/this.reduce + 'px',
2527 top: (result.t)/this.reduce +'px'
2531 //console.log(key + ' not displayed');
2532 this.searchResults[key].div=null;
2538 //______________________________________________________________________________
2539 // Returns the position of the gutter (line between the page images)
2540 BookReader.prototype.twoPageGutter = function() {
2541 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2545 //______________________________________________________________________________
2546 // Returns the offset for the top of the page images
2547 BookReader.prototype.twoPageTop = function() {
2548 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2551 // twoPageCoverWidth()
2552 //______________________________________________________________________________
2553 // Returns the width of the cover div given the total page width
2554 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2555 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2558 // twoPageGetViewCenter()
2559 //______________________________________________________________________________
2560 // Returns the percentage offset into twopageview div at the center of container div
2561 // { percentageX: float, percentageY: float }
2562 BookReader.prototype.twoPageGetViewCenter = function() {
2565 var containerOffset = $('#BRcontainer').offset();
2566 var viewOffset = $('#BRtwopageview').offset();
2567 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2568 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2573 // twoPageCenterView(percentageX, percentageY)
2574 //______________________________________________________________________________
2575 // Centers the point given by percentage from left,top of twopageview
2576 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2577 if ('undefined' == typeof(percentageX)) {
2580 if ('undefined' == typeof(percentageY)) {
2584 var viewWidth = $('#BRtwopageview').width();
2585 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2586 var intoViewX = percentageX * viewWidth;
2588 var viewHeight = $('#BRtwopageview').height();
2589 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2590 var intoViewY = percentageY * viewHeight;
2592 if (viewWidth < containerClientWidth) {
2593 // Can fit width without scrollbars - center by adjusting offset
2594 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2596 // Need to scroll to center
2597 $('#BRtwopageview').css('left', 0);
2598 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2601 if (viewHeight < containerClientHeight) {
2602 // Fits with scrollbars - add offset
2603 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2605 $('#BRtwopageview').css('top', 0);
2606 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2610 // twoPageFlipAreaHeight
2611 //______________________________________________________________________________
2612 // Returns the integer height of the click-to-flip areas at the edges of the book
2613 BookReader.prototype.twoPageFlipAreaHeight = function() {
2614 return parseInt(this.twoPage.height);
2617 // twoPageFlipAreaWidth
2618 //______________________________________________________________________________
2619 // Returns the integer width of the flip areas
2620 BookReader.prototype.twoPageFlipAreaWidth = function() {
2621 var max = 100; // $$$ TODO base on view width?
2624 var width = this.twoPage.width * 0.15;
2625 return parseInt(BookReader.util.clamp(width, min, max));
2628 // twoPageFlipAreaTop
2629 //______________________________________________________________________________
2630 // Returns integer top offset for flip areas
2631 BookReader.prototype.twoPageFlipAreaTop = function() {
2632 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2635 // twoPageLeftFlipAreaLeft
2636 //______________________________________________________________________________
2637 // Left offset for left flip area
2638 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2639 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2642 // twoPageRightFlipAreaLeft
2643 //______________________________________________________________________________
2644 // Left offset for right flip area
2645 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2646 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2649 // twoPagePlaceFlipAreas
2650 //______________________________________________________________________________
2651 // Readjusts position of flip areas based on current layout
2652 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2653 // We don't set top since it shouldn't change relative to view
2654 $(this.twoPage.leftFlipArea).css({
2655 left: this.twoPageLeftFlipAreaLeft() + 'px',
2656 width: this.twoPageFlipAreaWidth() + 'px'
2658 $(this.twoPage.rightFlipArea).css({
2659 left: this.twoPageRightFlipAreaLeft() + 'px',
2660 width: this.twoPageFlipAreaWidth() + 'px'
2664 // showSearchHilites2UP()
2665 //______________________________________________________________________________
2666 BookReader.prototype.updateSearchHilites2UP = function() {
2668 for (var key in this.searchResults) {
2669 key = parseInt(key, 10);
2670 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2671 var result = this.searchResults[key];
2672 if(null == result.div) {
2673 result.div = document.createElement('div');
2674 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2675 //console.log('appending ' + key);
2678 // We calculate the reduction factor for the specific page because it can be different
2679 // for each page in the spread
2680 var height = this._getPageHeight(key);
2681 var width = this._getPageWidth(key)
2682 var reduce = this.twoPage.height/height;
2683 var scaledW = parseInt(width*reduce);
2685 var gutter = this.twoPageGutter();
2687 if ('L' == this.getPageSide(key)) {
2688 pageL = gutter-scaledW;
2692 var pageT = this.twoPageTop();
2695 width: (result.r-result.l)*reduce + 'px',
2696 height: (result.b-result.t)*reduce + 'px',
2697 left: pageL+(result.l)*reduce + 'px',
2698 top: pageT+(result.t)*reduce +'px'
2702 //console.log(key + ' not displayed');
2703 if (null != this.searchResults[key].div) {
2704 //console.log('removing ' + key);
2705 $(this.searchResults[key].div).remove();
2707 this.searchResults[key].div=null;
2712 // removeSearchHilites()
2713 //______________________________________________________________________________
2714 BookReader.prototype.removeSearchHilites = function() {
2715 for (var key in this.searchResults) {
2716 if (null != this.searchResults[key].div) {
2717 $(this.searchResults[key].div).remove();
2718 this.searchResults[key].div=null;
2724 //______________________________________________________________________________
2725 BookReader.prototype.printPage = function() {
2726 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2728 /* iframe implementation
2730 if (null != this.printPopup) { // check if already showing
2733 this.printPopup = document.createElement("div");
2734 $(this.printPopup).css({
2735 position: 'absolute',
2737 left: ($('#BRcontainer').width()-400)/2 + 'px',
2740 border: "3px double #999999",
2742 backgroundColor: "#fff"
2743 }).appendTo('#BookReader');
2746 if (this.constMode1up == this.mode) {
2747 indexToPrint = this.firstIndex;
2749 indexToPrint = this.twoPage.currentIndexL;
2752 this.indexToPrint = indexToPrint;
2754 var htmlStr = '<div style="text-align: center;">';
2755 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>';
2756 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2757 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2758 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2759 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2760 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2762 htmlStr += '</div>';
2763 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2764 htmlStr += '</div>';
2766 this.printPopup.innerHTML = htmlStr;
2768 var iframe = document.createElement('iframe');
2769 iframe.id = 'printFrame';
2770 iframe.name = 'printFrame';
2771 iframe.width = '233px'; // 8.5 x 11 aspect
2772 iframe.height = '300px';
2774 var self = this; // closure
2776 $(iframe).load(function() {
2777 var doc = BookReader.util.getIFrameDocument(this);
2778 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2781 $('#printDiv').prepend(iframe);
2785 // Get print URI from current indices and mode
2786 BookReader.prototype.getPrintURI = function() {
2788 if (this.constMode2up == this.mode) {
2789 indexToPrint = this.twoPage.currentIndexL;
2791 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2794 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2795 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2796 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2798 if (this.constMode2up == this.mode) {
2799 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2800 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2801 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2803 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2806 return '/bookreader/print.php?' + options;
2809 /* iframe implementation
2810 BookReader.prototype.getPrintFrameContent = function(index) {
2811 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2812 // 8.5x11 so we should end up not overflowing on either paper size.
2813 var paperAspect = 8.5 / 11;
2814 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2818 // Rotate if possible and appropriate, to get larger image size on printed page
2819 if (this.canRotatePage(index)) {
2820 if (imageAspect > 1 && imageAspect > paperAspect) {
2821 // more wide than square, and more wide than paper
2823 imageAspect = 1/imageAspect;
2828 if (imageAspect > paperAspect) {
2829 // wider than paper, fit width
2830 fitAttrs = 'width="95%"';
2832 // taller than paper, fit height
2833 fitAttrs = 'height="95%"';
2836 var imageURL = this._getPageURI(index, 1, rotate);
2837 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2838 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2839 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2840 iframeStr += '</div>';
2841 iframeStr += '</body></html>';
2846 BookReader.prototype.updatePrintFrame = function(delta) {
2847 var newIndex = this.indexToPrint + delta;
2848 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2849 if (newIndex == this.indexToPrint) {
2852 this.indexToPrint = newIndex;
2853 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2854 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2859 //______________________________________________________________________________
2860 BookReader.prototype.showEmbedCode = function() {
2861 if (null != this.embedPopup) { // check if already showing
2865 this.embedPopup = document.createElement("div");
2866 $(this.embedPopup).css({
2867 position: 'absolute',
2869 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2872 border: "3px double #999999",
2874 backgroundColor: "#fff"
2875 }).appendTo('#BookReader');
2877 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2878 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>';
2879 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2880 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2882 this.embedPopup.innerHTML = htmlStr;
2883 $(this.embedPopup).find('input').bind('click', function() {
2889 //______________________________________________________________________________
2890 BookReader.prototype.autoToggle = function() {
2892 var bComingFrom1up = false;
2893 if (2 != this.mode) {
2894 bComingFrom1up = true;
2898 // Change to autofit if book is too large
2899 if (this.reduce < this.twoPageGetAutofitReduce()) {
2904 if (null == this.autoTimer) {
2905 this.flipSpeed = 2000;
2907 // $$$ Draw events currently cause layout problems when they occur during animation.
2908 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2909 // we workaround for now by not triggering immediate animation in that case.
2910 // See https://bugs.launchpad.net/gnubook/+bug/328327
2911 if (('rl' == this.pageProgression) && bComingFrom1up) {
2912 // don't flip immediately -- wait until timer fires
2915 this.flipFwdToIndex();
2918 $('#BRtoolbar .play').hide();
2919 $('#BRtoolbar .pause').show();
2920 this.autoTimer=setInterval(function(){
2921 if (self.animating) {return;}
2923 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2924 self.flipBackToIndex(1); // $$$ really what we want?
2926 self.flipFwdToIndex();
2935 //______________________________________________________________________________
2936 // Stop autoplay mode, allowing animations to finish
2937 BookReader.prototype.autoStop = function() {
2938 if (null != this.autoTimer) {
2939 clearInterval(this.autoTimer);
2940 this.flipSpeed = 'fast';
2941 $('#BRtoolbar .pause').hide();
2942 $('#BRtoolbar .play').show();
2943 this.autoTimer = null;
2947 // stopFlipAnimations
2948 //______________________________________________________________________________
2949 // Immediately stop flip animations. Callbacks are triggered.
2950 BookReader.prototype.stopFlipAnimations = function() {
2952 this.autoStop(); // Clear timers
2954 // Stop animation, clear queue, trigger callbacks
2955 if (this.leafEdgeTmp) {
2956 $(this.leafEdgeTmp).stop(false, true);
2958 jQuery.each(this.prefetchedImgs, function() {
2959 $(this).stop(false, true);
2962 // And again since animations also queued in callbacks
2963 if (this.leafEdgeTmp) {
2964 $(this.leafEdgeTmp).stop(false, true);
2966 jQuery.each(this.prefetchedImgs, function() {
2967 $(this).stop(false, true);
2972 // keyboardNavigationIsDisabled(event)
2973 // - returns true if keyboard navigation should be disabled for the event
2974 //______________________________________________________________________________
2975 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2976 if (event.target.tagName == "INPUT") {
2982 // gutterOffsetForIndex
2983 //______________________________________________________________________________
2985 // Returns the gutter offset for the spread containing the given index.
2986 // This function supports RTL
2987 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2989 // To find the offset of the gutter from the middle we calculate our percentage distance
2990 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2991 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2993 // But then again for RTL it's the opposite
2994 if ('rl' == this.pageProgression) {
3002 //______________________________________________________________________________
3003 // Returns the width of the leaf edge div for the page with index given
3004 BookReader.prototype.leafEdgeWidth = function(pindex) {
3005 // $$$ could there be single pixel rounding errors for L vs R?
3006 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3007 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3009 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3013 // jumpIndexForLeftEdgePageX
3014 //______________________________________________________________________________
3015 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3016 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3017 if ('rl' != this.pageProgression) {
3018 // LTR - flipping backward
3019 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3021 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3022 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3026 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3027 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3032 // jumpIndexForRightEdgePageX
3033 //______________________________________________________________________________
3034 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3035 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3036 if ('rl' != this.pageProgression) {
3038 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3039 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3042 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3043 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3048 BookReader.prototype.initToolbar = function(mode, ui) {
3050 $("#BookReader").append("<div id='BRtoolbar'>"
3051 + "<span id='BRtoolbarbuttons' style='float: right'>"
3052 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3053 + "<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>"
3054 + "<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>"
3055 + "<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>"
3056 + "<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>"
3057 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3061 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3062 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3063 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3064 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3065 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3066 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3067 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3070 + "<span id='#BRbooktitle'>"
3071 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3075 this.updateToolbarZoom(this.reduce); // Pretty format
3077 if (ui == "embed") {
3078 $("#BookReader a.logo").attr("target","_blank");
3081 // $$$ turn this into a member variable
3082 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3084 // We build in mode 2
3087 this.bindToolbarNavHandlers(jToolbar);
3089 // Setup tooltips -- later we could load these from a file for i18n
3090 var titles = { '.logo': 'Go to Archive.org',
3091 '.zoom_in': 'Zoom in',
3092 '.zoom_out': 'Zoom out',
3093 '.one_page_mode': 'One-page view',
3094 '.two_page_mode': 'Two-page view',
3095 '.thumbnail_mode': 'Thumbnail view',
3096 '.print': 'Print this page',
3097 '.embed': 'Embed bookreader',
3098 '.book_left': 'Flip left',
3099 '.book_right': 'Flip right',
3100 '.book_up': 'Page up',
3101 '.book_down': 'Page down',
3104 '.book_top': 'First page',
3105 '.book_bottom': 'Last page'
3107 if ('rl' == this.pageProgression) {
3108 titles['.book_leftmost'] = 'Last page';
3109 titles['.book_rightmost'] = 'First page';
3111 titles['.book_leftmost'] = 'First page';
3112 titles['.book_rightmost'] = 'Last page';
3115 for (var icon in titles) {
3116 jToolbar.find(icon).attr('title', titles[icon]);
3119 // Hide mode buttons and autoplay if 2up is not available
3120 // $$$ if we end up with more than two modes we should show the applicable buttons
3121 if ( !this.canSwitchToMode(this.constMode2up) ) {
3122 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3125 // Switch to requested mode -- binds other click handlers
3126 this.switchToolbarMode(mode);
3131 // switchToolbarMode
3132 //______________________________________________________________________________
3133 // Update the toolbar for the given mode (changes navigation buttons)
3134 // $$$ we should soon split the toolbar out into its own module
3135 BookReader.prototype.switchToolbarMode = function(mode) {
3138 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3139 $('#BRtoolbar .BRtoolbarmode2').hide();
3140 $('#BRtoolbar .BRtoolbarmode3').hide();
3141 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3142 } else if (2 == mode) {
3144 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3145 $('#BRtoolbar .BRtoolbarmode1').hide();
3146 $('#BRtoolbar .BRtoolbarmode3').hide();
3147 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3150 $('#BRtoolbar .BRtoolbarzoom').hide();
3151 $('#BRtoolbar .BRtoolbarmode2').hide();
3152 $('#BRtoolbar .BRtoolbarmode1').hide();
3153 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3157 // bindToolbarNavHandlers
3158 //______________________________________________________________________________
3159 // Binds the toolbar handlers
3160 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3162 var self = this; // closure
3164 jToolbar.find('.book_left').bind('click', function(e) {
3169 jToolbar.find('.book_right').bind('click', function(e) {
3174 jToolbar.find('.book_up').bind('click', function(e) {
3175 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3183 jToolbar.find('.book_down').bind('click', function(e) {
3184 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3192 jToolbar.find('.print').bind('click', function(e) {
3197 jToolbar.find('.embed').bind('click', function(e) {
3198 self.showEmbedCode();
3202 jToolbar.find('.play').bind('click', function(e) {
3207 jToolbar.find('.pause').bind('click', function(e) {
3212 jToolbar.find('.book_top').bind('click', function(e) {
3217 jToolbar.find('.book_bottom').bind('click', function(e) {
3222 jToolbar.find('.book_leftmost').bind('click', function(e) {
3227 jToolbar.find('.book_rightmost').bind('click', function(e) {
3233 // updateToolbarZoom(reduce)
3234 //______________________________________________________________________________
3235 // Update the displayed zoom factor based on reduction factor
3236 BookReader.prototype.updateToolbarZoom = function(reduce) {
3238 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3241 value = (100 / reduce).toFixed(2);
3242 // Strip trailing zeroes and decimal if all zeroes
3243 value = value.replace(/0+$/,'');
3244 value = value.replace(/\.$/,'');
3247 $('#BRzoom').text(value);
3250 // firstDisplayableIndex
3251 //______________________________________________________________________________
3252 // Returns the index of the first visible page, dependent on the mode.
3253 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3254 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3255 BookReader.prototype.firstDisplayableIndex = function() {
3256 if (this.mode != this.constMode2up) {
3260 if ('rl' != this.pageProgression) {
3262 if (this.getPageSide(0) == 'L') {
3269 if (this.getPageSide(0) == 'R') {
3277 // lastDisplayableIndex
3278 //______________________________________________________________________________
3279 // Returns the index of the last visible page, dependent on the mode.
3280 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3281 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3282 BookReader.prototype.lastDisplayableIndex = function() {
3284 var lastIndex = this.numLeafs - 1;
3286 if (this.mode != this.constMode2up) {
3290 if ('rl' != this.pageProgression) {
3292 if (this.getPageSide(lastIndex) == 'R') {
3295 return lastIndex + 1;
3299 if (this.getPageSide(lastIndex) == 'L') {
3302 return lastIndex + 1;
3307 // shortTitle(maximumCharacters)
3309 // Returns a shortened version of the title with the maximum number of characters
3310 BookReader.prototype.shortTitle = function(maximumCharacters) {
3311 if (this.bookTitle.length < maximumCharacters) {
3312 return this.bookTitle;
3315 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3320 // Parameter related functions
3322 // updateFromParams(params)
3324 // Update ourselves from the params object.
3326 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3327 BookReader.prototype.updateFromParams = function(params) {
3328 if ('undefined' != typeof(params.mode)) {
3329 this.switchMode(params.mode);
3333 if ('undefined' != typeof(params.searchTerm)) {
3334 if (this.searchTerm != params.searchTerm) {
3335 this.search(params.searchTerm);
3339 // $$$ process /zoom
3341 // We only respect page if index is not set
3342 if ('undefined' != typeof(params.index)) {
3343 if (params.index != this.currentIndex()) {
3344 this.jumpToIndex(params.index);
3346 } else if ('undefined' != typeof(params.page)) {
3347 // $$$ this assumes page numbers are unique
3348 if (params.page != this.getPageNum(this.currentIndex())) {
3349 this.jumpToPage(params.page);
3353 // $$$ process /region
3354 // $$$ process /highlight
3357 // paramsFromFragment(urlFragment)
3359 // Returns a object with configuration parametes from a URL fragment.
3361 // E.g paramsFromFragment(window.location.hash)
3362 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3363 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3367 // For convenience we allow an initial # character (as from window.location.hash)
3368 // but don't require it
3369 if (urlFragment.substr(0,1) == '#') {
3370 urlFragment = urlFragment.substr(1);
3373 // Simple #nn syntax
3374 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3375 if ( !isNaN(oldStyleLeafNum) ) {
3376 params.index = oldStyleLeafNum;
3378 // Done processing if using old-style syntax
3382 // Split into key-value pairs
3383 var urlArray = urlFragment.split('/');
3385 for (var i = 0; i < urlArray.length; i += 2) {
3386 urlHash[urlArray[i]] = urlArray[i+1];
3390 if ('1up' == urlHash['mode']) {
3391 params.mode = this.constMode1up;
3392 } else if ('2up' == urlHash['mode']) {
3393 params.mode = this.constMode2up;
3394 } else if ('thumb' == urlHash['mode']) {
3395 params.mode = this.constModeThumb;
3399 if ('undefined' != typeof(urlHash['page'])) {
3400 // page was set -- may not be int
3401 params.page = urlHash['page'];
3404 // $$$ process /region
3405 // $$$ process /search
3407 if (urlHash['search'] != undefined) {
3408 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3411 // $$$ process /highlight
3416 // paramsFromCurrent()
3418 // Create a params object from the current parameters.
3419 BookReader.prototype.paramsFromCurrent = function() {
3423 var index = this.currentIndex();
3424 var pageNum = this.getPageNum(index);
3425 if ((pageNum === 0) || pageNum) {
3426 params.page = pageNum;
3429 params.index = index;
3430 params.mode = this.mode;
3436 if (this.searchHighlightVisible()) {
3437 params.searchTerm = this.searchTerm;
3443 // fragmentFromParams(params)
3445 // Create a fragment string from the params object.
3446 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3447 BookReader.prototype.fragmentFromParams = function(params) {
3448 var separator = '/';
3452 if ('undefined' != typeof(params.page)) {
3453 fragments.push('page', params.page);
3455 // Don't have page numbering -- use index instead
3456 fragments.push('page', 'n' + params.index);
3463 if ('undefined' != typeof(params.mode)) {
3464 if (params.mode == this.constMode1up) {
3465 fragments.push('mode', '1up');
3466 } else if (params.mode == this.constMode2up) {
3467 fragments.push('mode', '2up');
3468 } else if (params.mode == this.constModeThumb) {
3469 fragments.push('mode', 'thumb');
3471 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3476 if (params.searchTerm) {
3477 fragments.push('search', params.searchTerm);
3480 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3483 // getPageIndex(pageNum)
3485 // Returns the *highest* index the given page number, or undefined
3486 BookReader.prototype.getPageIndex = function(pageNum) {
3487 var pageIndices = this.getPageIndices(pageNum);
3489 if (pageIndices.length > 0) {
3490 return pageIndices[pageIndices.length - 1];
3496 // getPageIndices(pageNum)
3498 // Returns an array (possibly empty) of the indices with the given page number
3499 BookReader.prototype.getPageIndices = function(pageNum) {
3502 // Check for special "nXX" page number
3503 if (pageNum.slice(0,1) == 'n') {
3505 var pageIntStr = pageNum.slice(1, pageNum.length);
3506 var pageIndex = parseInt(pageIntStr);
3507 indices.push(pageIndex);
3510 // Do nothing... will run through page names and see if one matches
3515 for (i=0; i<this.numLeafs; i++) {
3516 if (this.getPageNum(i) == pageNum) {
3524 // getPageName(index)
3526 // Returns the name of the page as it should be displayed in the user interface
3527 BookReader.prototype.getPageName = function(index) {
3528 return 'Page ' + this.getPageNum(index);
3531 // updateLocationHash
3533 // Update the location hash from the current parameters. Call this instead of manually
3534 // using window.location.replace
3535 BookReader.prototype.updateLocationHash = function() {
3536 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3537 window.location.replace(newHash);
3539 // This is the variable checked in the timer. Only user-generated changes
3540 // to the URL will trigger the event.
3541 this.oldLocationHash = newHash;
3544 // startLocationPolling
3546 // Starts polling of window.location to see hash fragment changes
3547 BookReader.prototype.startLocationPolling = function() {
3548 var self = this; // remember who I am
3549 self.oldLocationHash = window.location.hash;
3551 if (this.locationPollId) {
3552 clearInterval(this.locationPollID);
3553 this.locationPollId = null;
3556 this.locationPollId = setInterval(function() {
3557 var newHash = window.location.hash;
3558 if (newHash != self.oldLocationHash) {
3559 if (newHash != self.oldUserHash) { // Only process new user hash once
3560 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3562 // Queue change if animating
3563 if (self.animating) {
3565 self.animationFinishedCallback = function() {
3566 self.updateFromParams(self.paramsFromFragment(newHash));
3568 } else { // update immediately
3569 self.updateFromParams(self.paramsFromFragment(newHash));
3571 self.oldUserHash = newHash;
3579 // Returns true if we can switch to the requested mode
3580 BookReader.prototype.canSwitchToMode = function(mode) {
3581 if (mode == this.constMode2up) {
3582 // check there are enough pages to display
3583 // $$$ this is a workaround for the mis-feature that we can't display
3584 // short books in 2up mode
3585 if (this.numLeafs < 6) {
3593 // searchHighlightVisible
3595 // Returns true if a search highlight is currently being displayed
3596 BookReader.prototype.searchHighlightVisible = function() {
3597 if (this.constMode2up == this.mode) {
3598 if (this.searchResults[this.twoPage.currentIndexL]
3599 || this.searchResults[this.twoPage.currentIndexR]) {
3603 if (this.searchResults[this.currentIndex()]) {
3610 // getPageBackgroundColor
3612 // Returns a CSS property string for the background color for the given page
3613 // $$$ turn into regular CSS?
3614 BookReader.prototype.getPageBackgroundColor = function(index) {
3615 if (index >= 0 && index < this.numLeafs) {
3617 return this.pageDefaultBackgroundColor;
3625 // Returns the page width for the given index, or first or last page if out of range
3626 BookReader.prototype._getPageWidth = function(index) {
3627 // Synthesize a page width for pages not actually present in book.
3628 // May or may not be the best approach.
3629 // If index is out of range we return the width of first or last page
3630 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3631 return this.getPageWidth(index);
3636 // Returns the page height for the given index, or first or last page if out of range
3637 BookReader.prototype._getPageHeight= function(index) {
3638 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3639 return this.getPageHeight(index);
3644 // Returns the page URI or transparent image if out of range
3645 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3646 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3647 return this.imagesBaseURL + "/transparent.png";
3650 if ('undefined' == typeof(reduce)) {
3651 // reduce not passed in
3652 // $$$ this probably won't work for thumbnail mode
3653 var ratio = this.getPageHeight(index) / this.twoPage.height;
3655 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3658 } else if (ratio < 4) {
3660 } else if (ratio < 8) {
3662 } else if (ratio < 16) {
3664 } else if (ratio < 32) {
3672 return this.getPageURI(index, reduce, rotate);
3675 // Library functions
3677 clamp: function(value, min, max) {
3678 return Math.min(Math.max(value, min), max);
3681 getIFrameDocument: function(iframe) {
3682 // Adapted from http://xkr.us/articles/dom/iframe-document/
3683 var outer = (iframe.contentWindow || iframe.contentDocument);
3684 return (outer.document || outer);
3687 decodeURIComponentPlus: function(value) {
3688 // Decodes a URI component and converts '+' to ' '
3689 return decodeURIComponent(value).replace(/\+/g, ' ');
3692 encodeURIComponentPlus: function(value) {
3693 // Encodes a URI component and converts ' ' to '+'
3694 return encodeURIComponent(value).replace(/%20/g, '+');
3696 // The final property here must NOT have a comma after it - IE7