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());
1792 // flipBackToIndex()
1793 //______________________________________________________________________________
1794 // to flip back one spread, pass index=null
1795 BookReader.prototype.flipBackToIndex = function(index) {
1797 if (1 == this.mode) return;
1799 var leftIndex = this.twoPage.currentIndexL;
1801 if (this.animating) return;
1803 if (null != this.leafEdgeTmp) {
1804 alert('error: leafEdgeTmp should be null!');
1808 if (null == index) {
1809 index = leftIndex-2;
1811 //if (index<0) return;
1813 var previousIndices = this.getSpreadIndices(index);
1815 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1819 this.animating = true;
1821 if ('rl' != this.pageProgression) {
1822 // Assume LTR and we are going backward
1823 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1824 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1826 // RTL and going backward
1827 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1828 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1832 // flipLeftToRight()
1833 //______________________________________________________________________________
1834 // Flips the page on the left towards the page on the right
1835 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1837 var leftLeaf = this.twoPage.currentIndexL;
1839 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1840 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1841 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1843 var currWidthL = this.getPageWidth2UP(leftLeaf);
1844 var newWidthL = this.getPageWidth2UP(newIndexL);
1845 var newWidthR = this.getPageWidth2UP(newIndexR);
1847 var top = this.twoPageTop();
1848 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1850 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1851 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1853 //animation strategy:
1854 // 0. remove search highlight, if any.
1855 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1856 // of the left leaf and where the user clicked in the leaf edge.
1857 // Note that if this function was triggered by left() and not a
1858 // mouse click, the width of leafEdgeTmp is very small (zero px).
1859 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1860 // leftLeaf to width=0.
1861 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1862 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1863 // its new full width.
1864 // 4. After step 3 is finished, do the following:
1865 // - remove leafEdgeTmp from the dom.
1866 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1867 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1868 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1869 // and width=newLeafEdgeWidthL.
1870 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1871 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1872 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1873 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1874 // - prefetch new adjacent leafs.
1875 // - set up click handlers for both new left and right leafs.
1876 // - redraw the search highlight.
1877 // - update the pagenum box and the url.
1880 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1882 this.leafEdgeTmp = document.createElement('div');
1883 $(this.leafEdgeTmp).css({
1884 borderStyle: 'solid none solid solid',
1885 borderColor: 'rgb(51, 51, 34)',
1886 borderWidth: '1px 0px 1px 1px',
1887 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1888 width: leafEdgeTmpW + 'px',
1889 height: this.twoPage.height-1 + 'px',
1890 left: leftEdgeTmpLeft + 'px',
1892 position: 'absolute',
1894 }).appendTo('#BRtwopageview');
1896 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1897 $(this.leafEdgeL).css({
1898 width: newLeafEdgeWidthL+'px',
1899 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1902 // Left gets the offset of the current left leaf from the document
1903 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1904 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1905 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1907 // We change the left leaf to right positioning
1908 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1909 $(this.prefetchedImgs[leftLeaf]).css({
1914 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1915 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1919 this.removeSearchHilites();
1921 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1922 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1924 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1925 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1927 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1928 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1929 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1931 $(self.leafEdgeR).css({
1932 // Moves the right leaf edge
1933 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1934 left: gutter+newWidthR+'px'
1937 $(self.leafEdgeL).css({
1938 // Moves and resizes the left leaf edge
1939 width: newLeafEdgeWidthL+'px',
1940 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1943 // Resizes the brown border div
1944 $(self.twoPage.coverDiv).css({
1945 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1946 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1949 $(self.leafEdgeTmp).remove();
1950 self.leafEdgeTmp = null;
1952 // $$$ TODO refactor with opposite direction flip
1954 self.twoPage.currentIndexL = newIndexL;
1955 self.twoPage.currentIndexR = newIndexR;
1956 self.twoPage.scaledWL = newWidthL;
1957 self.twoPage.scaledWR = newWidthR;
1958 self.twoPage.gutter = gutter;
1960 self.firstIndex = self.twoPage.currentIndexL;
1961 self.displayedIndices = [newIndexL, newIndexR];
1962 self.pruneUnusedImgs();
1964 self.animating = false;
1966 self.updateSearchHilites2UP();
1967 self.updatePageNumBox2UP();
1969 // self.twoPagePlaceFlipAreas(); // No longer used
1970 self.setMouseHandlers2UP();
1971 self.twoPageSetCursor();
1973 if (self.animationFinishedCallback) {
1974 self.animationFinishedCallback();
1975 self.animationFinishedCallback = null;
1983 //______________________________________________________________________________
1984 // Whether we flip left or right is dependent on the page progression
1985 // to flip forward one spread, pass index=null
1986 BookReader.prototype.flipFwdToIndex = function(index) {
1988 if (this.animating) return;
1990 if (null != this.leafEdgeTmp) {
1991 alert('error: leafEdgeTmp should be null!');
1995 if (null == index) {
1996 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1998 if (index > this.lastDisplayableIndex()) return;
2000 this.animating = true;
2002 var nextIndices = this.getSpreadIndices(index);
2004 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2006 if ('rl' != this.pageProgression) {
2007 // We did not specify RTL
2008 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2009 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2012 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2013 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2017 // flipRightToLeft(nextL, nextR, gutter)
2018 // $$$ better not to have to pass gutter in
2019 //______________________________________________________________________________
2020 // Flip from left to right and show the nextL and nextR indices on those sides
2021 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2022 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2023 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2024 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2025 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2027 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2029 var top = this.twoPageTop();
2030 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2032 var middle = this.twoPage.middle;
2033 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2035 this.leafEdgeTmp = document.createElement('div');
2036 $(this.leafEdgeTmp).css({
2037 borderStyle: 'solid none solid solid',
2038 borderColor: 'rgb(51, 51, 34)',
2039 borderWidth: '1px 0px 1px 1px',
2040 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2041 width: leafEdgeTmpW + 'px',
2042 height: this.twoPage.height-1 + 'px',
2043 left: gutter+scaledW+'px',
2045 position: 'absolute',
2047 }).appendTo('#BRtwopageview');
2049 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2050 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2052 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2053 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2054 var newWidthL = this.getPageWidth2UP(newIndexL);
2055 var newWidthR = this.getPageWidth2UP(newIndexR);
2057 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2059 var self = this; // closure-tastic!
2061 var speed = this.flipSpeed;
2063 this.removeSearchHilites();
2065 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2066 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2067 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2068 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2069 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2071 $(self.leafEdgeL).css({
2072 width: newLeafEdgeWidthL+'px',
2073 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2076 // Resizes the book cover
2077 $(self.twoPage.coverDiv).css({
2078 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2079 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2082 $(self.leafEdgeTmp).remove();
2083 self.leafEdgeTmp = null;
2085 self.twoPage.currentIndexL = newIndexL;
2086 self.twoPage.currentIndexR = newIndexR;
2087 self.twoPage.scaledWL = newWidthL;
2088 self.twoPage.scaledWR = newWidthR;
2089 self.twoPage.gutter = gutter;
2091 self.firstIndex = self.twoPage.currentIndexL;
2092 self.displayedIndices = [newIndexL, newIndexR];
2093 self.pruneUnusedImgs();
2095 self.animating = false;
2098 self.updateSearchHilites2UP();
2099 self.updatePageNumBox2UP();
2101 // self.twoPagePlaceFlipAreas(); // No longer used
2102 self.setMouseHandlers2UP();
2103 self.twoPageSetCursor();
2105 if (self.animationFinishedCallback) {
2106 self.animationFinishedCallback();
2107 self.animationFinishedCallback = null;
2113 // setMouseHandlers2UP
2114 //______________________________________________________________________________
2115 BookReader.prototype.setMouseHandlers2UP = function() {
2117 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2122 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2129 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2130 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2137 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2138 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2141 e.data.self.right();
2147 //______________________________________________________________________________
2148 BookReader.prototype.prefetchImg = function(index) {
2149 var pageURI = this._getPageURI(index);
2151 // Load image if not loaded or URI has changed (e.g. due to scaling)
2152 var loadImage = false;
2153 if (undefined == this.prefetchedImgs[index]) {
2154 //console.log('no image for ' + index);
2156 } else if (pageURI != this.prefetchedImgs[index].uri) {
2157 //console.log('uri changed for ' + index);
2162 //console.log('prefetching ' + index);
2163 var img = document.createElement("img");
2165 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2166 this.prefetchedImgs[index] = img;
2171 // prepareFlipLeftToRight()
2173 //______________________________________________________________________________
2175 // Prepare to flip the left page towards the right. This corresponds to moving
2176 // backward when the page progression is left to right.
2177 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2179 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2181 this.prefetchImg(prevL);
2182 this.prefetchImg(prevR);
2184 var height = this._getPageHeight(prevL);
2185 var width = this._getPageWidth(prevL);
2186 var middle = this.twoPage.middle;
2187 var top = this.twoPageTop();
2188 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2190 // The gutter is the dividing line between the left and right pages.
2191 // It is offset from the middle to create the illusion of thickness to the pages
2192 var gutter = middle + this.gutterOffsetForIndex(prevL);
2194 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2195 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2196 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2199 position: 'absolute',
2200 left: gutter-scaledW+'px',
2201 right: '', // clear right property
2203 height: this.twoPage.height,
2204 width: scaledW+'px',
2205 backgroundColor: this.getPageBackgroundColor(prevL),
2206 borderRight: '1px solid black',
2210 $(this.prefetchedImgs[prevL]).css(leftCSS);
2212 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2214 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2217 position: 'absolute',
2221 height: this.twoPage.height,
2223 backgroundColor: this.getPageBackgroundColor(prevR),
2224 borderLeft: '1px solid black',
2228 $(this.prefetchedImgs[prevR]).css(rightCSS);
2230 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2234 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2235 // prepareFlipRightToLeft()
2236 //______________________________________________________________________________
2237 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2239 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2242 this.prefetchImg(nextL);
2243 this.prefetchImg(nextR);
2245 var height = this._getPageHeight(nextR);
2246 var width = this._getPageWidth(nextR);
2247 var middle = this.twoPage.middle;
2248 var top = this.twoPageTop();
2249 var scaledW = this.twoPage.height*width/height;
2251 var gutter = middle + this.gutterOffsetForIndex(nextL);
2253 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2254 $(this.prefetchedImgs[nextR]).css({
2255 position: 'absolute',
2258 backgroundColor: this.getPageBackgroundColor(nextR),
2259 height: this.twoPage.height,
2260 width: scaledW+'px',
2261 borderLeft: '1px solid black',
2265 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2267 height = this._getPageHeight(nextL);
2268 width = this._getPageWidth(nextL);
2269 scaledW = this.twoPage.height*width/height;
2271 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2272 $(this.prefetchedImgs[nextL]).css({
2273 position: 'absolute',
2274 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2276 backgroundColor: this.getPageBackgroundColor(nextL),
2277 height: this.twoPage.height,
2278 width: 0+'px', // Start at 0 width, then grow to the left
2279 borderRight: '1px solid black',
2283 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2287 // getNextLeafs() -- NOT RTL AWARE
2288 //______________________________________________________________________________
2289 // BookReader.prototype.getNextLeafs = function(o) {
2290 // //TODO: we might have two left or two right leafs in a row (damaged book)
2291 // //For now, assume that leafs are contiguous.
2293 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2294 // o.L = this.twoPage.currentIndexL+2;
2295 // o.R = this.twoPage.currentIndexL+3;
2298 // getprevLeafs() -- NOT RTL AWARE
2299 //______________________________________________________________________________
2300 // BookReader.prototype.getPrevLeafs = function(o) {
2301 // //TODO: we might have two left or two right leafs in a row (damaged book)
2302 // //For now, assume that leafs are contiguous.
2304 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2305 // o.L = this.twoPage.currentIndexL-2;
2306 // o.R = this.twoPage.currentIndexL-1;
2309 // pruneUnusedImgs()
2310 //______________________________________________________________________________
2311 BookReader.prototype.pruneUnusedImgs = function() {
2312 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2313 for (var key in this.prefetchedImgs) {
2314 //console.log('key is ' + key);
2315 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2316 //console.log('removing key '+ key);
2317 $(this.prefetchedImgs[key]).remove();
2319 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2320 //console.log('deleting key '+ key);
2321 delete this.prefetchedImgs[key];
2327 //______________________________________________________________________________
2328 BookReader.prototype.prefetch = function() {
2330 // prefetch visible pages first
2331 this.prefetchImg(this.twoPage.currentIndexL);
2332 this.prefetchImg(this.twoPage.currentIndexR);
2334 var adjacentPagesToLoad = 3;
2336 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2337 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2339 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2340 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2342 // Load images spreading out from current
2343 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2344 var goingDown = lowCurrent - i;
2345 if (goingDown >= start) {
2346 this.prefetchImg(goingDown);
2348 var goingUp = highCurrent + i;
2349 if (goingUp <= end) {
2350 this.prefetchImg(goingUp);
2355 var lim = this.twoPage.currentIndexL-4;
2357 lim = Math.max(lim, 0);
2358 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2359 this.prefetchImg(i);
2362 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2363 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2364 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2365 this.prefetchImg(i);
2371 // getPageWidth2UP()
2372 //______________________________________________________________________________
2373 BookReader.prototype.getPageWidth2UP = function(index) {
2374 // We return the width based on the dominant height
2375 var height = this._getPageHeight(index);
2376 var width = this._getPageWidth(index);
2377 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2381 //______________________________________________________________________________
2382 BookReader.prototype.search = function(term) {
2383 term = term.replace(/\//g, ' '); // strip slashes
2384 this.searchTerm = term;
2385 $('#BookReaderSearchScript').remove();
2386 var script = document.createElement("script");
2387 script.setAttribute('id', 'BookReaderSearchScript');
2388 script.setAttribute("type", "text/javascript");
2389 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2390 document.getElementsByTagName('head')[0].appendChild(script);
2391 $('#BookReaderSearchBox').val(term);
2392 $('#BookReaderSearchResults').html('Searching...');
2395 // BRSearchCallback()
2396 //______________________________________________________________________________
2397 BookReader.prototype.BRSearchCallback = function(txt) {
2399 if (jQuery.browser.msie) {
2400 var dom=new ActiveXObject("Microsoft.XMLDOM");
2404 var parser = new DOMParser();
2405 var dom = parser.parseFromString(txt, "text/xml");
2408 $('#BookReaderSearchResults').empty();
2409 $('#BookReaderSearchResults').append('<ul>');
2411 for (var key in this.searchResults) {
2412 if (null != this.searchResults[key].div) {
2413 $(this.searchResults[key].div).remove();
2415 delete this.searchResults[key];
2418 var pages = dom.getElementsByTagName('PAGE');
2420 if (0 == pages.length) {
2421 // $$$ it would be nice to echo the (sanitized) search result here
2422 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2424 for (var i = 0; i < pages.length; i++){
2425 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2428 var re = new RegExp (/_(\d{4})/);
2429 var reMatch = re.exec(pages[i].getAttribute('file'));
2430 var index = parseInt(reMatch[1], 10);
2431 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2433 var children = pages[i].childNodes;
2435 for (var j=0; j<children.length; j++) {
2436 //console.log(j + ' - ' + children[j].nodeName);
2437 //console.log(children[j].firstChild.nodeValue);
2438 if ('CONTEXT' == children[j].nodeName) {
2439 context += children[j].firstChild.nodeValue;
2440 } else if ('WORD' == children[j].nodeName) {
2441 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2443 var index = this.leafNumToIndex(index);
2444 if (null != index) {
2445 //coordinates are [left, bottom, right, top, [baseline]]
2446 //we'll skip baseline for now...
2447 var coords = children[j].getAttribute('coords').split(',',4);
2448 if (4 == coords.length) {
2449 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2454 var pageName = this.getPageName(index);
2455 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2456 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2457 //TODO: remove hardcoded instance name
2458 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2461 $('#BookReaderSearchResults').append('</ul>');
2463 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2464 $('#BookReaderSearchBox').val(this.searchTerm);
2466 this.updateSearchHilites();
2469 // updateSearchHilites()
2470 //______________________________________________________________________________
2471 BookReader.prototype.updateSearchHilites = function() {
2472 if (2 == this.mode) {
2473 this.updateSearchHilites2UP();
2475 this.updateSearchHilites1UP();
2479 // showSearchHilites1UP()
2480 //______________________________________________________________________________
2481 BookReader.prototype.updateSearchHilites1UP = function() {
2483 for (var key in this.searchResults) {
2485 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2486 var result = this.searchResults[key];
2487 if(null == result.div) {
2488 result.div = document.createElement('div');
2489 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2490 //console.log('appending ' + key);
2493 width: (result.r-result.l)/this.reduce + 'px',
2494 height: (result.b-result.t)/this.reduce + 'px',
2495 left: (result.l)/this.reduce + 'px',
2496 top: (result.t)/this.reduce +'px'
2500 //console.log(key + ' not displayed');
2501 this.searchResults[key].div=null;
2507 //______________________________________________________________________________
2508 // Returns the position of the gutter (line between the page images)
2509 BookReader.prototype.twoPageGutter = function() {
2510 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2514 //______________________________________________________________________________
2515 // Returns the offset for the top of the page images
2516 BookReader.prototype.twoPageTop = function() {
2517 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2520 // twoPageCoverWidth()
2521 //______________________________________________________________________________
2522 // Returns the width of the cover div given the total page width
2523 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2524 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2527 // twoPageGetViewCenter()
2528 //______________________________________________________________________________
2529 // Returns the percentage offset into twopageview div at the center of container div
2530 // { percentageX: float, percentageY: float }
2531 BookReader.prototype.twoPageGetViewCenter = function() {
2534 var containerOffset = $('#BRcontainer').offset();
2535 var viewOffset = $('#BRtwopageview').offset();
2536 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2537 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2542 // twoPageCenterView(percentageX, percentageY)
2543 //______________________________________________________________________________
2544 // Centers the point given by percentage from left,top of twopageview
2545 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2546 if ('undefined' == typeof(percentageX)) {
2549 if ('undefined' == typeof(percentageY)) {
2553 var viewWidth = $('#BRtwopageview').width();
2554 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2555 var intoViewX = percentageX * viewWidth;
2557 var viewHeight = $('#BRtwopageview').height();
2558 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2559 var intoViewY = percentageY * viewHeight;
2561 if (viewWidth < containerClientWidth) {
2562 // Can fit width without scrollbars - center by adjusting offset
2563 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2565 // Need to scroll to center
2566 $('#BRtwopageview').css('left', 0);
2567 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2570 if (viewHeight < containerClientHeight) {
2571 // Fits with scrollbars - add offset
2572 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2574 $('#BRtwopageview').css('top', 0);
2575 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2579 // twoPageFlipAreaHeight
2580 //______________________________________________________________________________
2581 // Returns the integer height of the click-to-flip areas at the edges of the book
2582 BookReader.prototype.twoPageFlipAreaHeight = function() {
2583 return parseInt(this.twoPage.height);
2586 // twoPageFlipAreaWidth
2587 //______________________________________________________________________________
2588 // Returns the integer width of the flip areas
2589 BookReader.prototype.twoPageFlipAreaWidth = function() {
2590 var max = 100; // $$$ TODO base on view width?
2593 var width = this.twoPage.width * 0.15;
2594 return parseInt(BookReader.util.clamp(width, min, max));
2597 // twoPageFlipAreaTop
2598 //______________________________________________________________________________
2599 // Returns integer top offset for flip areas
2600 BookReader.prototype.twoPageFlipAreaTop = function() {
2601 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2604 // twoPageLeftFlipAreaLeft
2605 //______________________________________________________________________________
2606 // Left offset for left flip area
2607 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2608 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2611 // twoPageRightFlipAreaLeft
2612 //______________________________________________________________________________
2613 // Left offset for right flip area
2614 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2615 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2618 // twoPagePlaceFlipAreas
2619 //______________________________________________________________________________
2620 // Readjusts position of flip areas based on current layout
2621 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2622 // We don't set top since it shouldn't change relative to view
2623 $(this.twoPage.leftFlipArea).css({
2624 left: this.twoPageLeftFlipAreaLeft() + 'px',
2625 width: this.twoPageFlipAreaWidth() + 'px'
2627 $(this.twoPage.rightFlipArea).css({
2628 left: this.twoPageRightFlipAreaLeft() + 'px',
2629 width: this.twoPageFlipAreaWidth() + 'px'
2633 // showSearchHilites2UP()
2634 //______________________________________________________________________________
2635 BookReader.prototype.updateSearchHilites2UP = function() {
2637 for (var key in this.searchResults) {
2638 key = parseInt(key, 10);
2639 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2640 var result = this.searchResults[key];
2641 if(null == result.div) {
2642 result.div = document.createElement('div');
2643 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2644 //console.log('appending ' + key);
2647 // We calculate the reduction factor for the specific page because it can be different
2648 // for each page in the spread
2649 var height = this._getPageHeight(key);
2650 var width = this._getPageWidth(key)
2651 var reduce = this.twoPage.height/height;
2652 var scaledW = parseInt(width*reduce);
2654 var gutter = this.twoPageGutter();
2656 if ('L' == this.getPageSide(key)) {
2657 pageL = gutter-scaledW;
2661 var pageT = this.twoPageTop();
2664 width: (result.r-result.l)*reduce + 'px',
2665 height: (result.b-result.t)*reduce + 'px',
2666 left: pageL+(result.l)*reduce + 'px',
2667 top: pageT+(result.t)*reduce +'px'
2671 //console.log(key + ' not displayed');
2672 if (null != this.searchResults[key].div) {
2673 //console.log('removing ' + key);
2674 $(this.searchResults[key].div).remove();
2676 this.searchResults[key].div=null;
2681 // removeSearchHilites()
2682 //______________________________________________________________________________
2683 BookReader.prototype.removeSearchHilites = function() {
2684 for (var key in this.searchResults) {
2685 if (null != this.searchResults[key].div) {
2686 $(this.searchResults[key].div).remove();
2687 this.searchResults[key].div=null;
2693 //______________________________________________________________________________
2694 BookReader.prototype.printPage = function() {
2695 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2697 /* iframe implementation
2699 if (null != this.printPopup) { // check if already showing
2702 this.printPopup = document.createElement("div");
2703 $(this.printPopup).css({
2704 position: 'absolute',
2706 left: ($('#BRcontainer').width()-400)/2 + 'px',
2709 border: "3px double #999999",
2711 backgroundColor: "#fff"
2712 }).appendTo('#BookReader');
2715 if (this.constMode1up == this.mode) {
2716 indexToPrint = this.firstIndex;
2718 indexToPrint = this.twoPage.currentIndexL;
2721 this.indexToPrint = indexToPrint;
2723 var htmlStr = '<div style="text-align: center;">';
2724 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>';
2725 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2726 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2727 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2728 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2729 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2731 htmlStr += '</div>';
2732 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2733 htmlStr += '</div>';
2735 this.printPopup.innerHTML = htmlStr;
2737 var iframe = document.createElement('iframe');
2738 iframe.id = 'printFrame';
2739 iframe.name = 'printFrame';
2740 iframe.width = '233px'; // 8.5 x 11 aspect
2741 iframe.height = '300px';
2743 var self = this; // closure
2745 $(iframe).load(function() {
2746 var doc = BookReader.util.getIFrameDocument(this);
2747 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2750 $('#printDiv').prepend(iframe);
2754 // Get print URI from current indices and mode
2755 BookReader.prototype.getPrintURI = function() {
2757 if (this.constMode2up == this.mode) {
2758 indexToPrint = this.twoPage.currentIndexL;
2760 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2763 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2764 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2765 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2767 if (this.constMode2up == this.mode) {
2768 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2769 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2770 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2772 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2775 return '/bookreader/print.php?' + options;
2778 /* iframe implementation
2779 BookReader.prototype.getPrintFrameContent = function(index) {
2780 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2781 // 8.5x11 so we should end up not overflowing on either paper size.
2782 var paperAspect = 8.5 / 11;
2783 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2787 // Rotate if possible and appropriate, to get larger image size on printed page
2788 if (this.canRotatePage(index)) {
2789 if (imageAspect > 1 && imageAspect > paperAspect) {
2790 // more wide than square, and more wide than paper
2792 imageAspect = 1/imageAspect;
2797 if (imageAspect > paperAspect) {
2798 // wider than paper, fit width
2799 fitAttrs = 'width="95%"';
2801 // taller than paper, fit height
2802 fitAttrs = 'height="95%"';
2805 var imageURL = this._getPageURI(index, 1, rotate);
2806 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2807 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2808 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2809 iframeStr += '</div>';
2810 iframeStr += '</body></html>';
2815 BookReader.prototype.updatePrintFrame = function(delta) {
2816 var newIndex = this.indexToPrint + delta;
2817 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2818 if (newIndex == this.indexToPrint) {
2821 this.indexToPrint = newIndex;
2822 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2823 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2828 //______________________________________________________________________________
2829 BookReader.prototype.showEmbedCode = function() {
2830 if (null != this.embedPopup) { // check if already showing
2834 this.embedPopup = document.createElement("div");
2835 $(this.embedPopup).css({
2836 position: 'absolute',
2838 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2841 border: "3px double #999999",
2843 backgroundColor: "#fff"
2844 }).appendTo('#BookReader');
2846 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2847 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>';
2848 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2849 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2851 this.embedPopup.innerHTML = htmlStr;
2852 $(this.embedPopup).find('input').bind('click', function() {
2858 //______________________________________________________________________________
2859 BookReader.prototype.autoToggle = function() {
2861 var bComingFrom1up = false;
2862 if (2 != this.mode) {
2863 bComingFrom1up = true;
2867 // Change to autofit if book is too large
2868 if (this.reduce < this.twoPageGetAutofitReduce()) {
2873 if (null == this.autoTimer) {
2874 this.flipSpeed = 2000;
2876 // $$$ Draw events currently cause layout problems when they occur during animation.
2877 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2878 // we workaround for now by not triggering immediate animation in that case.
2879 // See https://bugs.launchpad.net/gnubook/+bug/328327
2880 if (('rl' == this.pageProgression) && bComingFrom1up) {
2881 // don't flip immediately -- wait until timer fires
2884 this.flipFwdToIndex();
2887 $('#BRtoolbar .play').hide();
2888 $('#BRtoolbar .pause').show();
2889 this.autoTimer=setInterval(function(){
2890 if (self.animating) {return;}
2892 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2893 self.flipBackToIndex(1); // $$$ really what we want?
2895 self.flipFwdToIndex();
2904 //______________________________________________________________________________
2905 // Stop autoplay mode, allowing animations to finish
2906 BookReader.prototype.autoStop = function() {
2907 if (null != this.autoTimer) {
2908 clearInterval(this.autoTimer);
2909 this.flipSpeed = 'fast';
2910 $('#BRtoolbar .pause').hide();
2911 $('#BRtoolbar .play').show();
2912 this.autoTimer = null;
2916 // stopFlipAnimations
2917 //______________________________________________________________________________
2918 // Immediately stop flip animations. Callbacks are triggered.
2919 BookReader.prototype.stopFlipAnimations = function() {
2921 this.autoStop(); // Clear timers
2923 // Stop animation, clear queue, trigger callbacks
2924 if (this.leafEdgeTmp) {
2925 $(this.leafEdgeTmp).stop(false, true);
2927 jQuery.each(this.prefetchedImgs, function() {
2928 $(this).stop(false, true);
2931 // And again since animations also queued in callbacks
2932 if (this.leafEdgeTmp) {
2933 $(this.leafEdgeTmp).stop(false, true);
2935 jQuery.each(this.prefetchedImgs, function() {
2936 $(this).stop(false, true);
2941 // keyboardNavigationIsDisabled(event)
2942 // - returns true if keyboard navigation should be disabled for the event
2943 //______________________________________________________________________________
2944 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2945 if (event.target.tagName == "INPUT") {
2951 // gutterOffsetForIndex
2952 //______________________________________________________________________________
2954 // Returns the gutter offset for the spread containing the given index.
2955 // This function supports RTL
2956 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2958 // To find the offset of the gutter from the middle we calculate our percentage distance
2959 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2960 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2962 // But then again for RTL it's the opposite
2963 if ('rl' == this.pageProgression) {
2971 //______________________________________________________________________________
2972 // Returns the width of the leaf edge div for the page with index given
2973 BookReader.prototype.leafEdgeWidth = function(pindex) {
2974 // $$$ could there be single pixel rounding errors for L vs R?
2975 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2976 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2978 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2982 // jumpIndexForLeftEdgePageX
2983 //______________________________________________________________________________
2984 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2985 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2986 if ('rl' != this.pageProgression) {
2987 // LTR - flipping backward
2988 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2990 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2991 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2995 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2996 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3001 // jumpIndexForRightEdgePageX
3002 //______________________________________________________________________________
3003 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3004 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3005 if ('rl' != this.pageProgression) {
3007 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3008 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3011 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3012 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3017 BookReader.prototype.initToolbar = function(mode, ui) {
3019 $("#BookReader").append("<div id='BRtoolbar'>"
3020 + "<span id='BRtoolbarbuttons' style='float: right'>"
3021 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3022 + "<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>"
3023 + "<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>"
3024 + "<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>"
3025 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3029 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3030 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3031 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3032 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3033 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3034 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3035 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3038 + "<span id='#BRbooktitle'>"
3039 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3043 this.updateToolbarZoom(this.reduce); // Pretty format
3045 if (ui == "embed") {
3046 $("#BookReader a.logo").attr("target","_blank");
3049 // $$$ turn this into a member variable
3050 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3052 // We build in mode 2
3055 this.bindToolbarNavHandlers(jToolbar);
3057 // Setup tooltips -- later we could load these from a file for i18n
3058 var titles = { '.logo': 'Go to Archive.org',
3059 '.zoom_in': 'Zoom in',
3060 '.zoom_out': 'Zoom out',
3061 '.one_page_mode': 'One-page view',
3062 '.two_page_mode': 'Two-page view',
3063 '.thumbnail_mode': 'Thumbnail view',
3064 '.print': 'Print this page',
3065 '.embed': 'Embed bookreader',
3066 '.book_left': 'Flip left',
3067 '.book_right': 'Flip right',
3068 '.book_up': 'Page up',
3069 '.book_down': 'Page down',
3072 '.book_top': 'First page',
3073 '.book_bottom': 'Last page'
3075 if ('rl' == this.pageProgression) {
3076 titles['.book_leftmost'] = 'Last page';
3077 titles['.book_rightmost'] = 'First page';
3079 titles['.book_leftmost'] = 'First page';
3080 titles['.book_rightmost'] = 'Last page';
3083 for (var icon in titles) {
3084 jToolbar.find(icon).attr('title', titles[icon]);
3087 // Hide mode buttons and autoplay if 2up is not available
3088 // $$$ if we end up with more than two modes we should show the applicable buttons
3089 if ( !this.canSwitchToMode(this.constMode2up) ) {
3090 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3093 // Switch to requested mode -- binds other click handlers
3094 this.switchToolbarMode(mode);
3099 // switchToolbarMode
3100 //______________________________________________________________________________
3101 // Update the toolbar for the given mode (changes navigation buttons)
3102 // $$$ we should soon split the toolbar out into its own module
3103 BookReader.prototype.switchToolbarMode = function(mode) {
3106 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3107 $('#BRtoolbar .BRtoolbarmode2').hide();
3108 $('#BRtoolbar .BRtoolbarmode3').hide();
3109 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3110 } else if (2 == mode) {
3112 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3113 $('#BRtoolbar .BRtoolbarmode1').hide();
3114 $('#BRtoolbar .BRtoolbarmode3').hide();
3115 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3118 $('#BRtoolbar .BRtoolbarzoom').hide();
3119 $('#BRtoolbar .BRtoolbarmode2').hide();
3120 $('#BRtoolbar .BRtoolbarmode1').hide();
3121 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3125 // bindToolbarNavHandlers
3126 //______________________________________________________________________________
3127 // Binds the toolbar handlers
3128 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3130 var self = this; // closure
3132 jToolbar.find('.book_left').bind('click', function(e) {
3137 jToolbar.find('.book_right').bind('click', function(e) {
3142 jToolbar.find('.book_up').bind('click', function(e) {
3147 jToolbar.find('.book_down').bind('click', function(e) {
3152 jToolbar.find('.print').bind('click', function(e) {
3157 jToolbar.find('.embed').bind('click', function(e) {
3158 self.showEmbedCode();
3162 jToolbar.find('.play').bind('click', function(e) {
3167 jToolbar.find('.pause').bind('click', function(e) {
3172 jToolbar.find('.book_top').bind('click', function(e) {
3177 jToolbar.find('.book_bottom').bind('click', function(e) {
3182 jToolbar.find('.book_leftmost').bind('click', function(e) {
3187 jToolbar.find('.book_rightmost').bind('click', function(e) {
3193 // updateToolbarZoom(reduce)
3194 //______________________________________________________________________________
3195 // Update the displayed zoom factor based on reduction factor
3196 BookReader.prototype.updateToolbarZoom = function(reduce) {
3198 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3201 value = (100 / reduce).toFixed(2);
3202 // Strip trailing zeroes and decimal if all zeroes
3203 value = value.replace(/0+$/,'');
3204 value = value.replace(/\.$/,'');
3207 $('#BRzoom').text(value);
3210 // firstDisplayableIndex
3211 //______________________________________________________________________________
3212 // Returns the index of the first visible page, dependent on the mode.
3213 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3214 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3215 BookReader.prototype.firstDisplayableIndex = function() {
3216 if (this.mode != this.constMode2up) {
3220 if ('rl' != this.pageProgression) {
3222 if (this.getPageSide(0) == 'L') {
3229 if (this.getPageSide(0) == 'R') {
3237 // lastDisplayableIndex
3238 //______________________________________________________________________________
3239 // Returns the index of the last visible page, dependent on the mode.
3240 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3241 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3242 BookReader.prototype.lastDisplayableIndex = function() {
3244 var lastIndex = this.numLeafs - 1;
3246 if (this.mode != this.constMode2up) {
3250 if ('rl' != this.pageProgression) {
3252 if (this.getPageSide(lastIndex) == 'R') {
3255 return lastIndex + 1;
3259 if (this.getPageSide(lastIndex) == 'L') {
3262 return lastIndex + 1;
3267 // shortTitle(maximumCharacters)
3269 // Returns a shortened version of the title with the maximum number of characters
3270 BookReader.prototype.shortTitle = function(maximumCharacters) {
3271 if (this.bookTitle.length < maximumCharacters) {
3272 return this.bookTitle;
3275 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3280 // Parameter related functions
3282 // updateFromParams(params)
3284 // Update ourselves from the params object.
3286 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3287 BookReader.prototype.updateFromParams = function(params) {
3288 if ('undefined' != typeof(params.mode)) {
3289 this.switchMode(params.mode);
3293 if ('undefined' != typeof(params.searchTerm)) {
3294 if (this.searchTerm != params.searchTerm) {
3295 this.search(params.searchTerm);
3299 // $$$ process /zoom
3301 // We only respect page if index is not set
3302 if ('undefined' != typeof(params.index)) {
3303 if (params.index != this.currentIndex()) {
3304 this.jumpToIndex(params.index);
3306 } else if ('undefined' != typeof(params.page)) {
3307 // $$$ this assumes page numbers are unique
3308 if (params.page != this.getPageNum(this.currentIndex())) {
3309 this.jumpToPage(params.page);
3313 // $$$ process /region
3314 // $$$ process /highlight
3317 // paramsFromFragment(urlFragment)
3319 // Returns a object with configuration parametes from a URL fragment.
3321 // E.g paramsFromFragment(window.location.hash)
3322 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3323 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3327 // For convenience we allow an initial # character (as from window.location.hash)
3328 // but don't require it
3329 if (urlFragment.substr(0,1) == '#') {
3330 urlFragment = urlFragment.substr(1);
3333 // Simple #nn syntax
3334 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3335 if ( !isNaN(oldStyleLeafNum) ) {
3336 params.index = oldStyleLeafNum;
3338 // Done processing if using old-style syntax
3342 // Split into key-value pairs
3343 var urlArray = urlFragment.split('/');
3345 for (var i = 0; i < urlArray.length; i += 2) {
3346 urlHash[urlArray[i]] = urlArray[i+1];
3350 if ('1up' == urlHash['mode']) {
3351 params.mode = this.constMode1up;
3352 } else if ('2up' == urlHash['mode']) {
3353 params.mode = this.constMode2up;
3354 } else if ('thumb' == urlHash['mode']) {
3355 params.mode = this.constModeThumb;
3359 if ('undefined' != typeof(urlHash['page'])) {
3360 // page was set -- may not be int
3361 params.page = urlHash['page'];
3364 // $$$ process /region
3365 // $$$ process /search
3367 if (urlHash['search'] != undefined) {
3368 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3371 // $$$ process /highlight
3376 // paramsFromCurrent()
3378 // Create a params object from the current parameters.
3379 BookReader.prototype.paramsFromCurrent = function() {
3383 var index = this.currentIndex();
3384 var pageNum = this.getPageNum(index);
3385 if ((pageNum === 0) || pageNum) {
3386 params.page = pageNum;
3389 params.index = index;
3390 params.mode = this.mode;
3396 if (this.searchHighlightVisible()) {
3397 params.searchTerm = this.searchTerm;
3403 // fragmentFromParams(params)
3405 // Create a fragment string from the params object.
3406 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3407 BookReader.prototype.fragmentFromParams = function(params) {
3408 var separator = '/';
3412 if ('undefined' != typeof(params.page)) {
3413 fragments.push('page', params.page);
3415 // Don't have page numbering -- use index instead
3416 fragments.push('page', 'n' + params.index);
3423 if ('undefined' != typeof(params.mode)) {
3424 if (params.mode == this.constMode1up) {
3425 fragments.push('mode', '1up');
3426 } else if (params.mode == this.constMode2up) {
3427 fragments.push('mode', '2up');
3428 } else if (params.mode == this.constModeThumb) {
3429 fragments.push('mode', 'thumb');
3431 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3436 if (params.searchTerm) {
3437 fragments.push('search', params.searchTerm);
3440 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3443 // getPageIndex(pageNum)
3445 // Returns the *highest* index the given page number, or undefined
3446 BookReader.prototype.getPageIndex = function(pageNum) {
3447 var pageIndices = this.getPageIndices(pageNum);
3449 if (pageIndices.length > 0) {
3450 return pageIndices[pageIndices.length - 1];
3456 // getPageIndices(pageNum)
3458 // Returns an array (possibly empty) of the indices with the given page number
3459 BookReader.prototype.getPageIndices = function(pageNum) {
3462 // Check for special "nXX" page number
3463 if (pageNum.slice(0,1) == 'n') {
3465 var pageIntStr = pageNum.slice(1, pageNum.length);
3466 var pageIndex = parseInt(pageIntStr);
3467 indices.push(pageIndex);
3470 // Do nothing... will run through page names and see if one matches
3475 for (i=0; i<this.numLeafs; i++) {
3476 if (this.getPageNum(i) == pageNum) {
3484 // getPageName(index)
3486 // Returns the name of the page as it should be displayed in the user interface
3487 BookReader.prototype.getPageName = function(index) {
3488 return 'Page ' + this.getPageNum(index);
3491 // updateLocationHash
3493 // Update the location hash from the current parameters. Call this instead of manually
3494 // using window.location.replace
3495 BookReader.prototype.updateLocationHash = function() {
3496 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3497 window.location.replace(newHash);
3499 // This is the variable checked in the timer. Only user-generated changes
3500 // to the URL will trigger the event.
3501 this.oldLocationHash = newHash;
3504 // startLocationPolling
3506 // Starts polling of window.location to see hash fragment changes
3507 BookReader.prototype.startLocationPolling = function() {
3508 var self = this; // remember who I am
3509 self.oldLocationHash = window.location.hash;
3511 if (this.locationPollId) {
3512 clearInterval(this.locationPollID);
3513 this.locationPollId = null;
3516 this.locationPollId = setInterval(function() {
3517 var newHash = window.location.hash;
3518 if (newHash != self.oldLocationHash) {
3519 if (newHash != self.oldUserHash) { // Only process new user hash once
3520 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3522 // Queue change if animating
3523 if (self.animating) {
3525 self.animationFinishedCallback = function() {
3526 self.updateFromParams(self.paramsFromFragment(newHash));
3528 } else { // update immediately
3529 self.updateFromParams(self.paramsFromFragment(newHash));
3531 self.oldUserHash = newHash;
3539 // Returns true if we can switch to the requested mode
3540 BookReader.prototype.canSwitchToMode = function(mode) {
3541 if (mode == this.constMode2up) {
3542 // check there are enough pages to display
3543 // $$$ this is a workaround for the mis-feature that we can't display
3544 // short books in 2up mode
3545 if (this.numLeafs < 6) {
3553 // searchHighlightVisible
3555 // Returns true if a search highlight is currently being displayed
3556 BookReader.prototype.searchHighlightVisible = function() {
3557 if (this.constMode2up == this.mode) {
3558 if (this.searchResults[this.twoPage.currentIndexL]
3559 || this.searchResults[this.twoPage.currentIndexR]) {
3563 if (this.searchResults[this.currentIndex()]) {
3570 // getPageBackgroundColor
3572 // Returns a CSS property string for the background color for the given page
3573 // $$$ turn into regular CSS?
3574 BookReader.prototype.getPageBackgroundColor = function(index) {
3575 if (index >= 0 && index < this.numLeafs) {
3577 return this.pageDefaultBackgroundColor;
3585 // Returns the page width for the given index, or first or last page if out of range
3586 BookReader.prototype._getPageWidth = function(index) {
3587 // Synthesize a page width for pages not actually present in book.
3588 // May or may not be the best approach.
3589 // If index is out of range we return the width of first or last page
3590 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3591 return this.getPageWidth(index);
3596 // Returns the page height for the given index, or first or last page if out of range
3597 BookReader.prototype._getPageHeight= function(index) {
3598 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3599 return this.getPageHeight(index);
3604 // Returns the page URI or transparent image if out of range
3605 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3606 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3607 return this.imagesBaseURL + "/transparent.png";
3610 if ('undefined' == typeof(reduce)) {
3611 // reduce not passed in
3612 // $$$ this probably won't work for thumbnail mode
3613 var ratio = this.getPageHeight(index) / this.twoPage.height;
3615 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3618 } else if (ratio < 4) {
3620 } else if (ratio < 8) {
3622 } else if (ratio < 16) {
3624 } else if (ratio < 32) {
3632 return this.getPageURI(index, reduce, rotate);
3635 // Library functions
3637 clamp: function(value, min, max) {
3638 return Math.min(Math.max(value, min), max);
3641 getIFrameDocument: function(iframe) {
3642 // Adapted from http://xkr.us/articles/dom/iframe-document/
3643 var outer = (iframe.contentWindow || iframe.contentDocument);
3644 return (outer.document || outer);
3647 decodeURIComponentPlus: function(value) {
3648 // Decodes a URI component and converts '+' to ' '
3649 return decodeURIComponent(value).replace(/\+/g, ' ');
3652 encodeURIComponentPlus: function(value) {
3653 // Encodes a URI component and converts ' ' to '+'
3654 return encodeURIComponent(value).replace(/%20/g, '+');
3656 // The final property here must NOT have a comma after it - IE7