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 link = document.createElement("a");
691 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
694 $('#BRpageview').append(div);
696 img = document.createElement("img");
697 img.src = this.getPageURI(leaf);
698 $(img).css('width', leafWidth+'px');
699 $(img).css('height', leafHeight+'px');
700 img.style.border = "0";
702 //console.log('displaying thumbnail: ' + leafMap[j]);
707 // remove previous highlights
708 if ($('.BRpagedivthumb_highlight').length>0) {
709 div = $('.BRpagedivthumb_highlight')
710 div.attr({className: 'BRpagedivthumb' });
712 // highlight current page
713 $('#pagediv'+this.currentIndex()).attr({className: 'BRpagedivthumb_highlight' });
716 for (i=0; i<this.displayedRows.length; i++) {
717 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
718 row = this.displayedRows[i];
719 for (k=0; k<leafMap[row].leafs.length; k++) {
720 index = leafMap[row].leafs[k].num;
721 //console.log('Removing leaf ' + index);
722 $('#pagediv'+index).remove();
726 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
730 this.displayedRows = rowsToDisplay.slice();
732 if (null !== this.getPageNum(this.currentIndex())) {
733 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
735 $("#BRpagenum").val('');
738 this.updateToolbarZoom(this.reduce);
741 // drawLeafsTwoPage()
742 //______________________________________________________________________________
743 BookReader.prototype.drawLeafsTwoPage = function() {
744 var scrollTop = $('#BRtwopageview').attr('scrollTop');
745 var scrollBottom = scrollTop + $('#BRtwopageview').height();
747 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
749 var indexL = this.twoPage.currentIndexL;
751 var heightL = this._getPageHeight(indexL);
752 var widthL = this._getPageWidth(indexL);
754 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
755 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
756 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
757 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
758 //console.log(leafEdgeWidthL);
760 var middle = this.twoPage.middle; // $$$ getter instead?
761 var top = this.twoPageTop();
762 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
764 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
765 this.twoPage.gutter = this.twoPageGutter();
767 this.prefetchImg(indexL);
768 $(this.prefetchedImgs[indexL]).css({
769 position: 'absolute',
770 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
773 backgroundColor: this.getPageBackgroundColor(indexL),
774 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
775 width: this.twoPage.scaledWL + 'px',
776 borderRight: '1px solid black',
778 }).appendTo('#BRtwopageview');
780 var indexR = this.twoPage.currentIndexR;
781 var heightR = this._getPageHeight(indexR);
782 var widthR = this._getPageWidth(indexR);
784 // $$$ should use getwidth2up?
785 //var scaledWR = this.twoPage.height*widthR/heightR;
786 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
787 this.prefetchImg(indexR);
788 $(this.prefetchedImgs[indexR]).css({
789 position: 'absolute',
790 left: this.twoPage.gutter+'px',
793 backgroundColor: this.getPageBackgroundColor(indexR),
794 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
795 width: this.twoPage.scaledWR + 'px',
796 borderLeft: '1px solid black',
798 }).appendTo('#BRtwopageview');
801 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
802 this.setMouseHandlers2UP();
803 this.twoPageSetCursor();
805 this.updatePageNumBox2UP();
806 this.updateToolbarZoom(this.reduce);
808 // this.twoPagePlaceFlipAreas(); // No longer used
812 // updatePageNumBox2UP
813 //______________________________________________________________________________
814 BookReader.prototype.updatePageNumBox2UP = function() {
815 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
816 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
818 $("#BRpagenum").val('');
820 this.updateLocationHash();
824 //______________________________________________________________________________
825 BookReader.prototype.loadLeafs = function() {
829 if (null == this.timer) {
830 this.timer=setTimeout(function(){self.drawLeafs()},250);
832 clearTimeout(this.timer);
833 this.timer=setTimeout(function(){self.drawLeafs()},250);
839 // Pass 1 to zoom in, anything else to zoom out
840 //______________________________________________________________________________
841 BookReader.prototype.zoom = function(direction) {
843 case this.constMode1up:
844 return this.zoom1up(direction);
845 case this.constMode2up:
846 return this.zoom2up(direction);
851 //______________________________________________________________________________
852 BookReader.prototype.zoom1up = function(dir) {
854 if (2 == this.mode) { //can only zoom in 1-page mode
859 // $$$ with flexible zoom we could "snap" to /2 page reductions
860 // for better scaling
862 if (this.reduce <= 0.5) return;
863 this.reduce*=0.5; //zoom in
865 if (this.reduce >= 8) return;
866 this.reduce*=2; //zoom out
869 this.pageScale = this.reduce; // preserve current reduce
870 this.resizePageView();
872 $('#BRpageview').empty()
873 this.displayedIndices = [];
876 this.updateToolbarZoom(this.reduce);
878 // Recalculate search hilites
879 this.removeSearchHilites();
880 this.updateSearchHilites();
885 //______________________________________________________________________________
886 BookReader.prototype.resizePageView = function() {
889 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
890 var viewWidth = $('#BRcontainer').attr('clientWidth');
892 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
893 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
894 var oldPageViewHeight = $('#BRpageview').height();
895 var oldPageViewWidth = $('#BRpageview').width();
897 var oldCenterY = this.centerY1up();
898 var oldCenterX = this.centerX1up();
900 if (0 != oldPageViewHeight) {
901 var scrollRatio = oldCenterY / oldPageViewHeight;
906 for (i=0; i<this.numLeafs; i++) {
907 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
908 var width = parseInt(this._getPageWidth(i)/this.reduce);
909 if (width>viewWidth) viewWidth=width;
911 $('#BRpageview').height(viewHeight);
912 $('#BRpageview').width(viewWidth);
914 var newCenterY = scrollRatio*viewHeight;
915 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
916 $('#BRcontainer').attr('scrollTop', newTop);
918 // We use clientWidth here to avoid miscalculating due to scroll bar
919 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
920 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
921 newLeft = Math.max(newLeft, 0);
922 $('#BRcontainer').attr('scrollLeft', newLeft);
923 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
925 //this.centerPageView();
928 // Not really needed until there is 1up autofit
929 this.removeSearchHilites();
930 this.updateSearchHilites();
934 //______________________________________________________________________________
935 // Returns the current offset of the viewport center in scaled document coordinates.
936 BookReader.prototype.centerX1up = function() {
938 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
939 centerX = $('#BRpageview').width();
941 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
943 centerX = Math.floor(centerX);
948 //______________________________________________________________________________
949 // Returns the current offset of the viewport center in scaled document coordinates.
950 BookReader.prototype.centerY1up = function() {
951 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
952 return Math.floor(centerY);
956 //______________________________________________________________________________
957 BookReader.prototype.centerPageView = function() {
959 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
960 var clientWidth = $('#BRcontainer').attr('clientWidth');
961 //console.log('sW='+scrollWidth+' cW='+clientWidth);
962 if (scrollWidth > clientWidth) {
963 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
968 // zoom2up(direction)
969 //______________________________________________________________________________
970 BookReader.prototype.zoom2up = function(direction) {
972 // Hard stop autoplay
973 this.stopFlipAnimations();
975 // Get new zoom state
976 var newZoom = this.twoPageNextReduce(this.reduce, direction);
977 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
980 this.twoPage.autofit = newZoom.autofit;
981 this.reduce = newZoom.reduce;
982 this.pageScale = this.reduce; // preserve current reduce
984 // Preserve view center position
985 var oldCenter = this.twoPageGetViewCenter();
987 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
988 // $$$ An improvement would be to use the low res image until the larger one is loaded.
989 if (1 == direction) {
990 for (var img in this.prefetchedImgs) {
991 delete this.prefetchedImgs[img];
995 // Prepare view with new center to minimize visual glitches
996 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1000 // quantizeReduce(reduce)
1001 //______________________________________________________________________________
1002 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1003 BookReader.prototype.quantizeReduce = function(reduce) {
1004 var quantized = this.reductionFactors[0];
1005 var distance = Math.abs(reduce - quantized);
1006 for (var i = 1; i < this.reductionFactors.length; i++) {
1007 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1008 if (newDistance < distance) {
1009 distance = newDistance;
1010 quantized = this.reductionFactors[i];
1017 // twoPageNextReduce()
1018 //______________________________________________________________________________
1019 // Returns the next reduction level
1020 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1022 var autofitReduce = this.twoPageGetAutofitReduce();
1024 if (0 == direction) { // autofit
1025 result.autofit = true;
1026 result.reduce = autofitReduce;
1028 } else if (1 == direction) { // zoom in
1029 var newReduce = this.reductionFactors[0];
1031 for (var i = 1; i < this.reductionFactors.length; i++) {
1032 if (this.reductionFactors[i] < reduce) {
1033 newReduce = this.reductionFactors[i];
1037 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1039 result.autofit = true;
1040 result.reduce = autofitReduce;
1042 result.autofit = false;
1043 result.reduce = newReduce;
1046 } else { // zoom out
1047 var lastIndex = this.reductionFactors.length - 1;
1048 var newReduce = this.reductionFactors[lastIndex];
1050 for (var i = lastIndex; i >= 0; i--) {
1051 if (this.reductionFactors[i] > reduce) {
1052 newReduce = this.reductionFactors[i];
1056 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1058 result.autofit = true;
1059 result.reduce = autofitReduce;
1061 result.autofit = false;
1062 result.reduce = newReduce;
1070 //______________________________________________________________________________
1071 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1072 BookReader.prototype.jumpToPage = function(pageNum) {
1074 var pageIndex = this.getPageIndex(pageNum);
1076 if ('undefined' != typeof(pageIndex)) {
1079 this.jumpToIndex(pageIndex);
1080 $('#BRcontainer').attr('scrollTop', leafTop);
1089 //______________________________________________________________________________
1090 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1092 if (2 == this.mode) {
1095 // By checking against min/max we do nothing if requested index
1097 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1098 this.flipBackToIndex(index);
1099 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1100 this.flipFwdToIndex(index);
1103 } else if (3 == this.mode){
1104 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1114 for (i=0; i<(index+1); i++) {
1115 leafWidth = this.thumbWidth;
1116 if (rightPos + (leafWidth + this.padding) > viewWidth){
1121 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1122 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1123 if (leafIndex==0) { leafTop = bottomPos; }
1124 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1125 rightPos += leafWidth + this.padding;
1128 this.firstIndex=index;
1129 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1132 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1139 for (i=0; i<index; i++) {
1140 h = parseInt(this._getPageHeight(i)/this.reduce);
1141 leafTop += h + this.padding;
1145 //console.log('pageY ' + pageY);
1146 var offset = parseInt( (pageY) / this.reduce);
1147 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1148 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1153 var offset = parseInt( (pageX) / this.reduce);
1154 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1158 //$('#BRcontainer').attr('scrollTop', leafTop);
1159 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1165 //______________________________________________________________________________
1166 BookReader.prototype.switchMode = function(mode) {
1168 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1170 if (mode == this.mode) return;
1172 if (!this.canSwitchToMode(mode)) {
1177 this.removeSearchHilites();
1180 this.switchToolbarMode(mode);
1182 // reinstate scale if moving from thumbnail view
1183 if (this.pageScale != this.reduce) this.reduce = this.pageScale;
1185 // $$$ TODO preserve center of view when switching between mode
1186 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1189 this.reduce = this.quantizeReduce(this.reduce);
1190 this.prepareOnePageView();
1191 } else if (3 == mode) {
1192 this.reduce = this.quantizeReduce(this.reduce);
1193 this.prepareThumbnailView();
1194 this.jumpToIndex(this.currentIndex());
1196 this.twoPage.autofit = false; // Take zoom level from other mode
1197 this.reduce = this.quantizeReduce(this.reduce);
1198 this.prepareTwoPageView();
1199 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1204 //prepareOnePageView()
1205 //______________________________________________________________________________
1206 BookReader.prototype.prepareOnePageView = function() {
1208 // var startLeaf = this.displayedIndices[0];
1209 var startLeaf = this.currentIndex();
1211 $('#BRcontainer').empty();
1212 $('#BRcontainer').css({
1213 overflowY: 'scroll',
1217 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1219 this.resizePageView();
1221 this.jumpToIndex(startLeaf);
1222 this.displayedIndices = [];
1224 this.drawLeafsOnePage();
1226 // Bind mouse handlers
1227 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1228 brPageView.bind('mousedown', function(e) {
1229 // $$$ check here for right-click and don't disable. Also use jQuery style
1230 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1233 // Special hack for IE7
1234 brPageView[0].onselectstart = function(e) { return false; };
1237 //prepareThumbnailView()
1238 //______________________________________________________________________________
1239 BookReader.prototype.prepareThumbnailView = function() {
1241 // var startLeaf = this.displayedIndices[0];
1242 var startLeaf = this.currentIndex();
1243 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1245 $('#BRcontainer').empty();
1246 $('#BRcontainer').css({
1247 overflowY: 'scroll',
1251 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1253 this.resizePageView();
1255 this.displayedRows = [];
1256 this.drawLeafsThumbnail();
1258 // Bind mouse handlers
1259 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1260 brPageView.bind('mousedown', function(e) {
1261 // $$$ check here for right-click and don't disable. Also use jQuery style
1262 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1265 // Special hack for IE7
1266 brPageView[0].onselectstart = function(e) { return false; };
1269 // prepareTwoPageView()
1270 //______________________________________________________________________________
1271 // Some decisions about two page view:
1273 // Both pages will be displayed at the same height, even if they were different physical/scanned
1274 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1275 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1276 // aspect ratio to determine the height.
1278 // The two page view div is resized to keep the middle of the book in the middle of the div
1279 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1280 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1281 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1282 $('#BRcontainer').empty();
1283 $('#BRcontainer').css('overflow', 'auto');
1285 // We want to display two facing pages. We may be missing
1286 // one side of the spread because it is the first/last leaf,
1287 // foldouts, missing pages, etc
1289 //var targetLeaf = this.displayedIndices[0];
1290 var targetLeaf = this.firstIndex;
1292 if (targetLeaf < this.firstDisplayableIndex()) {
1293 targetLeaf = this.firstDisplayableIndex();
1296 if (targetLeaf > this.lastDisplayableIndex()) {
1297 targetLeaf = this.lastDisplayableIndex();
1300 //this.twoPage.currentIndexL = null;
1301 //this.twoPage.currentIndexR = null;
1302 //this.pruneUnusedImgs();
1304 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1305 this.twoPage.currentIndexL = currentSpreadIndices[0];
1306 this.twoPage.currentIndexR = currentSpreadIndices[1];
1307 this.firstIndex = this.twoPage.currentIndexL;
1309 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1311 this.pruneUnusedImgs();
1312 this.prefetch(); // Preload images or reload if scaling has changed
1314 //console.dir(this.twoPage);
1316 // Add the two page view
1317 // $$$ Can we get everything set up and then append?
1318 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1320 // $$$ calculate first then set
1321 $('#BRtwopageview').css( {
1322 height: this.twoPage.totalHeight + 'px',
1323 width: this.twoPage.totalWidth + 'px',
1324 position: 'absolute'
1327 // If there will not be scrollbars (e.g. when zooming out) we center the book
1328 // since otherwise the book will be stuck off-center
1329 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1330 centerPercentageX = 0.5;
1332 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1333 centerPercentageY = 0.5;
1336 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1338 this.twoPage.coverDiv = document.createElement('div');
1339 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1340 border: '1px solid rgb(68, 25, 17)',
1341 width: this.twoPage.bookCoverDivWidth + 'px',
1342 height: this.twoPage.bookCoverDivHeight+'px',
1343 visibility: 'visible',
1344 position: 'absolute',
1345 backgroundColor: '#663929',
1346 left: this.twoPage.bookCoverDivLeft + 'px',
1347 top: this.twoPage.bookCoverDivTop+'px',
1348 MozBorderRadiusTopleft: '7px',
1349 MozBorderRadiusTopright: '7px',
1350 MozBorderRadiusBottomright: '7px',
1351 MozBorderRadiusBottomleft: '7px'
1352 }).appendTo('#BRtwopageview');
1354 this.leafEdgeR = document.createElement('div');
1355 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1356 $(this.leafEdgeR).css({
1357 borderStyle: 'solid solid solid none',
1358 borderColor: 'rgb(51, 51, 34)',
1359 borderWidth: '1px 1px 1px 0px',
1360 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1361 width: this.twoPage.leafEdgeWidthR + 'px',
1362 height: this.twoPage.height-1 + 'px',
1364 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1365 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1366 position: 'absolute'
1367 }).appendTo('#BRtwopageview');
1369 this.leafEdgeL = document.createElement('div');
1370 this.leafEdgeL.className = 'leafEdgeL';
1371 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1372 borderStyle: 'solid none solid solid',
1373 borderColor: 'rgb(51, 51, 34)',
1374 borderWidth: '1px 0px 1px 1px',
1375 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1376 width: this.twoPage.leafEdgeWidthL + 'px',
1377 height: this.twoPage.height-1 + 'px',
1378 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1379 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1380 position: 'absolute'
1381 }).appendTo('#BRtwopageview');
1383 div = document.createElement('div');
1384 $(div).attr('id', 'BRbookspine').css({
1385 border: '1px solid rgb(68, 25, 17)',
1386 width: this.twoPage.bookSpineDivWidth+'px',
1387 height: this.twoPage.bookSpineDivHeight+'px',
1388 position: 'absolute',
1389 backgroundColor: 'rgb(68, 25, 17)',
1390 left: this.twoPage.bookSpineDivLeft+'px',
1391 top: this.twoPage.bookSpineDivTop+'px'
1392 }).appendTo('#BRtwopageview');
1394 var self = this; // for closure
1396 /* Flip areas no longer used
1397 this.twoPage.leftFlipArea = document.createElement('div');
1398 this.twoPage.leftFlipArea.className = 'BRfliparea';
1399 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1401 width: this.twoPageFlipAreaWidth() + 'px',
1402 height: this.twoPageFlipAreaHeight() + 'px',
1403 position: 'absolute',
1404 left: this.twoPageLeftFlipAreaLeft() + 'px',
1405 top: this.twoPageFlipAreaTop() + 'px',
1408 }).bind('click', function(e) {
1410 }).bind('mousedown', function(e) {
1412 }).appendTo('#BRtwopageview');
1414 this.twoPage.rightFlipArea = document.createElement('div');
1415 this.twoPage.rightFlipArea.className = 'BRfliparea';
1416 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1418 width: this.twoPageFlipAreaWidth() + 'px',
1419 height: this.twoPageFlipAreaHeight() + 'px',
1420 position: 'absolute',
1421 left: this.twoPageRightFlipAreaLeft() + 'px',
1422 top: this.twoPageFlipAreaTop() + 'px',
1425 }).bind('click', function(e) {
1427 }).bind('mousedown', function(e) {
1429 }).appendTo('#BRtwopageview');
1432 this.prepareTwoPagePopUp();
1434 this.displayedIndices = [];
1436 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1437 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1439 this.drawLeafsTwoPage();
1440 this.updateToolbarZoom(this.reduce);
1444 this.removeSearchHilites();
1445 this.updateSearchHilites();
1449 // prepareTwoPagePopUp()
1451 // This function prepares the "View Page n" popup that shows while the mouse is
1452 // over the left/right "stack of sheets" edges. It also binds the mouse
1453 // events for these divs.
1454 //______________________________________________________________________________
1455 BookReader.prototype.prepareTwoPagePopUp = function() {
1457 this.twoPagePopUp = document.createElement('div');
1458 $(this.twoPagePopUp).css({
1459 border: '1px solid black',
1461 position: 'absolute',
1462 fontFamily: 'sans-serif',
1465 backgroundColor: 'rgb(255, 255, 238)',
1467 }).appendTo('#BRcontainer');
1468 $(this.twoPagePopUp).hide();
1470 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1471 $(e.data.twoPagePopUp).show();
1474 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1475 $(e.data.twoPagePopUp).hide();
1478 $(this.leafEdgeL).bind('click', this, function(e) {
1480 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1481 e.data.jumpToIndex(jumpIndex);
1484 $(this.leafEdgeR).bind('click', this, function(e) {
1486 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1487 e.data.jumpToIndex(jumpIndex);
1490 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1492 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1493 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1495 // $$$ TODO: Make sure popup is positioned so that it is in view
1496 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1497 $(e.data.twoPagePopUp).css({
1498 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1499 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1503 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1505 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1506 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1508 // $$$ TODO: Make sure popup is positioned so that it is in view
1509 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1510 $(e.data.twoPagePopUp).css({
1511 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1512 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1517 // calculateSpreadSize()
1518 //______________________________________________________________________________
1519 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1520 // this.twoPage.currentIndexR
1521 // This function sets this.twoPage.height, twoPage.width
1523 BookReader.prototype.calculateSpreadSize = function() {
1525 var firstIndex = this.twoPage.currentIndexL;
1526 var secondIndex = this.twoPage.currentIndexR;
1527 //console.log('first page is ' + firstIndex);
1529 // Calculate page sizes and total leaf width
1531 if ( this.twoPage.autofit) {
1532 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1534 // set based on reduction factor
1535 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1538 // Both pages together
1539 this.twoPage.height = spreadSize.height;
1540 this.twoPage.width = spreadSize.width;
1543 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1544 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1547 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1548 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1549 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1553 // The width of the book cover div. The combined width of both pages, twice the width
1554 // of the book cover internal padding (2*10) and the page edges
1555 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1556 // The height of the book cover div
1557 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1560 // We calculate the total width and height for the div so that we can make the book
1562 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1563 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1564 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1565 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1566 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1567 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1569 // We want to minimize the unused space in two-up mode (maximize the amount of page
1570 // shown). We give width to the leaf edges and these widths change (though the sum
1571 // of the two remains constant) as we flip through the book. With the book
1572 // cover centered and fixed in the BRcontainer div the page images will meet
1573 // at the "gutter" which is generally offset from the center.
1574 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1575 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1577 // The left edge of the book cover moves depending on the width of the pages
1578 // $$$ change to getter
1579 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1580 // The top edge of the book cover stays a fixed distance from the top
1581 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1584 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1585 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1586 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1589 this.reduce = spreadSize.reduce; // $$$ really set this here?
1592 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1595 // We check which page is closest to a "normal" page and use that to set the height
1596 // for both pages. This means that foldouts and other odd size pages will be displayed
1597 // smaller than the nominal zoom amount.
1598 var canon5Dratio = 1.5;
1601 height: this._getPageHeight(firstIndex),
1602 width: this._getPageWidth(firstIndex)
1606 height: this._getPageHeight(secondIndex),
1607 width: this._getPageWidth(secondIndex)
1610 var firstIndexRatio = first.height / first.width;
1611 var secondIndexRatio = second.height / second.width;
1612 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1615 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1616 ratio = firstIndexRatio;
1617 //console.log('using firstIndexRatio ' + ratio);
1619 ratio = secondIndexRatio;
1620 //console.log('using secondIndexRatio ' + ratio);
1623 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1624 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1625 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1627 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1628 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1630 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1631 ideal.width -= 10; // $$$ fudge factor
1632 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1633 ideal.height -= 20; // fudge factor
1634 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1636 if (ideal.height/ratio <= ideal.width) {
1638 ideal.width = parseInt(ideal.height/ratio);
1641 ideal.height = parseInt(ideal.width*ratio);
1644 // $$$ check this logic with large spreads
1645 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1650 // getSpreadSizeFromReduce()
1651 //______________________________________________________________________________
1652 // Returns the spread size calculated from the reduction factor for the given pages
1653 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1654 var spreadSize = {};
1655 // $$$ Scale this based on reduce?
1656 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1657 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1658 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1660 // $$$ Possibly incorrect -- we should make height "dominant"
1661 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1662 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1663 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1664 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1665 spreadSize.reduce = reduce;
1670 // twoPageGetAutofitReduce()
1671 //______________________________________________________________________________
1672 // Returns the current ideal reduction factor
1673 BookReader.prototype.twoPageGetAutofitReduce = function() {
1674 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1675 return spreadSize.reduce;
1678 // twoPageSetCursor()
1679 //______________________________________________________________________________
1680 // Set the cursor for two page view
1681 BookReader.prototype.twoPageSetCursor = function() {
1682 // console.log('setting cursor');
1683 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1684 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1685 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1686 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1688 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1689 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1694 //______________________________________________________________________________
1695 // Returns the currently active index.
1696 BookReader.prototype.currentIndex = function() {
1697 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1698 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1699 return this.firstIndex; // $$$ TODO page in center of view would be better
1700 } else if (this.mode == this.constMode2up) {
1701 // Only allow indices that are actually present in book
1702 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1704 throw 'currentIndex called for unimplemented mode ' + this.mode;
1709 //______________________________________________________________________________
1710 // Flip the right page over onto the left
1711 BookReader.prototype.right = function() {
1712 if ('rl' != this.pageProgression) {
1722 //______________________________________________________________________________
1723 // Flip to the rightmost page
1724 BookReader.prototype.rightmost = function() {
1725 if ('rl' != this.pageProgression) {
1733 //______________________________________________________________________________
1734 // Flip the left page over onto the right.
1735 BookReader.prototype.left = function() {
1736 if ('rl' != this.pageProgression) {
1746 //______________________________________________________________________________
1747 // Flip to the leftmost page
1748 BookReader.prototype.leftmost = function() {
1749 if ('rl' != this.pageProgression) {
1757 //______________________________________________________________________________
1758 BookReader.prototype.next = function() {
1759 if (2 == this.mode) {
1761 this.flipFwdToIndex(null);
1763 if (this.firstIndex < this.lastDisplayableIndex()) {
1764 this.jumpToIndex(this.firstIndex+1);
1770 //______________________________________________________________________________
1771 BookReader.prototype.prev = function() {
1772 if (2 == this.mode) {
1774 this.flipBackToIndex(null);
1776 if (this.firstIndex >= 1) {
1777 this.jumpToIndex(this.firstIndex-1);
1782 BookReader.prototype.first = function() {
1783 this.jumpToIndex(this.firstDisplayableIndex());
1786 BookReader.prototype.last = function() {
1787 this.jumpToIndex(this.lastDisplayableIndex());
1790 // flipBackToIndex()
1791 //______________________________________________________________________________
1792 // to flip back one spread, pass index=null
1793 BookReader.prototype.flipBackToIndex = function(index) {
1795 if (1 == this.mode) return;
1797 var leftIndex = this.twoPage.currentIndexL;
1799 if (this.animating) return;
1801 if (null != this.leafEdgeTmp) {
1802 alert('error: leafEdgeTmp should be null!');
1806 if (null == index) {
1807 index = leftIndex-2;
1809 //if (index<0) return;
1811 var previousIndices = this.getSpreadIndices(index);
1813 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1817 this.animating = true;
1819 if ('rl' != this.pageProgression) {
1820 // Assume LTR and we are going backward
1821 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1822 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1824 // RTL and going backward
1825 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1826 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1830 // flipLeftToRight()
1831 //______________________________________________________________________________
1832 // Flips the page on the left towards the page on the right
1833 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1835 var leftLeaf = this.twoPage.currentIndexL;
1837 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1838 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1839 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1841 var currWidthL = this.getPageWidth2UP(leftLeaf);
1842 var newWidthL = this.getPageWidth2UP(newIndexL);
1843 var newWidthR = this.getPageWidth2UP(newIndexR);
1845 var top = this.twoPageTop();
1846 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1848 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1849 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1851 //animation strategy:
1852 // 0. remove search highlight, if any.
1853 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1854 // of the left leaf and where the user clicked in the leaf edge.
1855 // Note that if this function was triggered by left() and not a
1856 // mouse click, the width of leafEdgeTmp is very small (zero px).
1857 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1858 // leftLeaf to width=0.
1859 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1860 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1861 // its new full width.
1862 // 4. After step 3 is finished, do the following:
1863 // - remove leafEdgeTmp from the dom.
1864 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1865 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1866 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1867 // and width=newLeafEdgeWidthL.
1868 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1869 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1870 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1871 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1872 // - prefetch new adjacent leafs.
1873 // - set up click handlers for both new left and right leafs.
1874 // - redraw the search highlight.
1875 // - update the pagenum box and the url.
1878 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1880 this.leafEdgeTmp = document.createElement('div');
1881 $(this.leafEdgeTmp).css({
1882 borderStyle: 'solid none solid solid',
1883 borderColor: 'rgb(51, 51, 34)',
1884 borderWidth: '1px 0px 1px 1px',
1885 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1886 width: leafEdgeTmpW + 'px',
1887 height: this.twoPage.height-1 + 'px',
1888 left: leftEdgeTmpLeft + 'px',
1890 position: 'absolute',
1892 }).appendTo('#BRtwopageview');
1894 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1895 $(this.leafEdgeL).css({
1896 width: newLeafEdgeWidthL+'px',
1897 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1900 // Left gets the offset of the current left leaf from the document
1901 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1902 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1903 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1905 // We change the left leaf to right positioning
1906 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1907 $(this.prefetchedImgs[leftLeaf]).css({
1912 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1913 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1917 this.removeSearchHilites();
1919 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1920 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1922 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1923 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1925 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1926 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1927 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1929 $(self.leafEdgeR).css({
1930 // Moves the right leaf edge
1931 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1932 left: gutter+newWidthR+'px'
1935 $(self.leafEdgeL).css({
1936 // Moves and resizes the left leaf edge
1937 width: newLeafEdgeWidthL+'px',
1938 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1941 // Resizes the brown border div
1942 $(self.twoPage.coverDiv).css({
1943 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1944 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1947 $(self.leafEdgeTmp).remove();
1948 self.leafEdgeTmp = null;
1950 // $$$ TODO refactor with opposite direction flip
1952 self.twoPage.currentIndexL = newIndexL;
1953 self.twoPage.currentIndexR = newIndexR;
1954 self.twoPage.scaledWL = newWidthL;
1955 self.twoPage.scaledWR = newWidthR;
1956 self.twoPage.gutter = gutter;
1958 self.firstIndex = self.twoPage.currentIndexL;
1959 self.displayedIndices = [newIndexL, newIndexR];
1960 self.pruneUnusedImgs();
1962 self.animating = false;
1964 self.updateSearchHilites2UP();
1965 self.updatePageNumBox2UP();
1967 // self.twoPagePlaceFlipAreas(); // No longer used
1968 self.setMouseHandlers2UP();
1969 self.twoPageSetCursor();
1971 if (self.animationFinishedCallback) {
1972 self.animationFinishedCallback();
1973 self.animationFinishedCallback = null;
1981 //______________________________________________________________________________
1982 // Whether we flip left or right is dependent on the page progression
1983 // to flip forward one spread, pass index=null
1984 BookReader.prototype.flipFwdToIndex = function(index) {
1986 if (this.animating) return;
1988 if (null != this.leafEdgeTmp) {
1989 alert('error: leafEdgeTmp should be null!');
1993 if (null == index) {
1994 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1996 if (index > this.lastDisplayableIndex()) return;
1998 this.animating = true;
2000 var nextIndices = this.getSpreadIndices(index);
2002 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2004 if ('rl' != this.pageProgression) {
2005 // We did not specify RTL
2006 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2007 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2010 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2011 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2015 // flipRightToLeft(nextL, nextR, gutter)
2016 // $$$ better not to have to pass gutter in
2017 //______________________________________________________________________________
2018 // Flip from left to right and show the nextL and nextR indices on those sides
2019 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2020 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2021 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2022 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2023 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2025 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2027 var top = this.twoPageTop();
2028 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2030 var middle = this.twoPage.middle;
2031 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2033 this.leafEdgeTmp = document.createElement('div');
2034 $(this.leafEdgeTmp).css({
2035 borderStyle: 'solid none solid solid',
2036 borderColor: 'rgb(51, 51, 34)',
2037 borderWidth: '1px 0px 1px 1px',
2038 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2039 width: leafEdgeTmpW + 'px',
2040 height: this.twoPage.height-1 + 'px',
2041 left: gutter+scaledW+'px',
2043 position: 'absolute',
2045 }).appendTo('#BRtwopageview');
2047 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2048 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2050 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2051 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2052 var newWidthL = this.getPageWidth2UP(newIndexL);
2053 var newWidthR = this.getPageWidth2UP(newIndexR);
2055 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2057 var self = this; // closure-tastic!
2059 var speed = this.flipSpeed;
2061 this.removeSearchHilites();
2063 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2064 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2065 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2066 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2067 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2069 $(self.leafEdgeL).css({
2070 width: newLeafEdgeWidthL+'px',
2071 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2074 // Resizes the book cover
2075 $(self.twoPage.coverDiv).css({
2076 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2077 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2080 $(self.leafEdgeTmp).remove();
2081 self.leafEdgeTmp = null;
2083 self.twoPage.currentIndexL = newIndexL;
2084 self.twoPage.currentIndexR = newIndexR;
2085 self.twoPage.scaledWL = newWidthL;
2086 self.twoPage.scaledWR = newWidthR;
2087 self.twoPage.gutter = gutter;
2089 self.firstIndex = self.twoPage.currentIndexL;
2090 self.displayedIndices = [newIndexL, newIndexR];
2091 self.pruneUnusedImgs();
2093 self.animating = false;
2096 self.updateSearchHilites2UP();
2097 self.updatePageNumBox2UP();
2099 // self.twoPagePlaceFlipAreas(); // No longer used
2100 self.setMouseHandlers2UP();
2101 self.twoPageSetCursor();
2103 if (self.animationFinishedCallback) {
2104 self.animationFinishedCallback();
2105 self.animationFinishedCallback = null;
2111 // setMouseHandlers2UP
2112 //______________________________________________________________________________
2113 BookReader.prototype.setMouseHandlers2UP = function() {
2115 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2120 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2127 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2128 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2135 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2136 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2139 e.data.self.right();
2145 //______________________________________________________________________________
2146 BookReader.prototype.prefetchImg = function(index) {
2147 var pageURI = this._getPageURI(index);
2149 // Load image if not loaded or URI has changed (e.g. due to scaling)
2150 var loadImage = false;
2151 if (undefined == this.prefetchedImgs[index]) {
2152 //console.log('no image for ' + index);
2154 } else if (pageURI != this.prefetchedImgs[index].uri) {
2155 //console.log('uri changed for ' + index);
2160 //console.log('prefetching ' + index);
2161 var img = document.createElement("img");
2163 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2164 this.prefetchedImgs[index] = img;
2169 // prepareFlipLeftToRight()
2171 //______________________________________________________________________________
2173 // Prepare to flip the left page towards the right. This corresponds to moving
2174 // backward when the page progression is left to right.
2175 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2177 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2179 this.prefetchImg(prevL);
2180 this.prefetchImg(prevR);
2182 var height = this._getPageHeight(prevL);
2183 var width = this._getPageWidth(prevL);
2184 var middle = this.twoPage.middle;
2185 var top = this.twoPageTop();
2186 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2188 // The gutter is the dividing line between the left and right pages.
2189 // It is offset from the middle to create the illusion of thickness to the pages
2190 var gutter = middle + this.gutterOffsetForIndex(prevL);
2192 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2193 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2194 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2197 position: 'absolute',
2198 left: gutter-scaledW+'px',
2199 right: '', // clear right property
2201 height: this.twoPage.height,
2202 width: scaledW+'px',
2203 backgroundColor: this.getPageBackgroundColor(prevL),
2204 borderRight: '1px solid black',
2208 $(this.prefetchedImgs[prevL]).css(leftCSS);
2210 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2212 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2215 position: 'absolute',
2219 height: this.twoPage.height,
2221 backgroundColor: this.getPageBackgroundColor(prevR),
2222 borderLeft: '1px solid black',
2226 $(this.prefetchedImgs[prevR]).css(rightCSS);
2228 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2232 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2233 // prepareFlipRightToLeft()
2234 //______________________________________________________________________________
2235 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2237 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2240 this.prefetchImg(nextL);
2241 this.prefetchImg(nextR);
2243 var height = this._getPageHeight(nextR);
2244 var width = this._getPageWidth(nextR);
2245 var middle = this.twoPage.middle;
2246 var top = this.twoPageTop();
2247 var scaledW = this.twoPage.height*width/height;
2249 var gutter = middle + this.gutterOffsetForIndex(nextL);
2251 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2252 $(this.prefetchedImgs[nextR]).css({
2253 position: 'absolute',
2256 backgroundColor: this.getPageBackgroundColor(nextR),
2257 height: this.twoPage.height,
2258 width: scaledW+'px',
2259 borderLeft: '1px solid black',
2263 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2265 height = this._getPageHeight(nextL);
2266 width = this._getPageWidth(nextL);
2267 scaledW = this.twoPage.height*width/height;
2269 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2270 $(this.prefetchedImgs[nextL]).css({
2271 position: 'absolute',
2272 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2274 backgroundColor: this.getPageBackgroundColor(nextL),
2275 height: this.twoPage.height,
2276 width: 0+'px', // Start at 0 width, then grow to the left
2277 borderRight: '1px solid black',
2281 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2285 // getNextLeafs() -- NOT RTL AWARE
2286 //______________________________________________________________________________
2287 // BookReader.prototype.getNextLeafs = function(o) {
2288 // //TODO: we might have two left or two right leafs in a row (damaged book)
2289 // //For now, assume that leafs are contiguous.
2291 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2292 // o.L = this.twoPage.currentIndexL+2;
2293 // o.R = this.twoPage.currentIndexL+3;
2296 // getprevLeafs() -- NOT RTL AWARE
2297 //______________________________________________________________________________
2298 // BookReader.prototype.getPrevLeafs = function(o) {
2299 // //TODO: we might have two left or two right leafs in a row (damaged book)
2300 // //For now, assume that leafs are contiguous.
2302 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2303 // o.L = this.twoPage.currentIndexL-2;
2304 // o.R = this.twoPage.currentIndexL-1;
2307 // pruneUnusedImgs()
2308 //______________________________________________________________________________
2309 BookReader.prototype.pruneUnusedImgs = function() {
2310 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2311 for (var key in this.prefetchedImgs) {
2312 //console.log('key is ' + key);
2313 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2314 //console.log('removing key '+ key);
2315 $(this.prefetchedImgs[key]).remove();
2317 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2318 //console.log('deleting key '+ key);
2319 delete this.prefetchedImgs[key];
2325 //______________________________________________________________________________
2326 BookReader.prototype.prefetch = function() {
2328 // prefetch visible pages first
2329 this.prefetchImg(this.twoPage.currentIndexL);
2330 this.prefetchImg(this.twoPage.currentIndexR);
2332 var adjacentPagesToLoad = 3;
2334 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2335 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2337 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2338 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2340 // Load images spreading out from current
2341 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2342 var goingDown = lowCurrent - i;
2343 if (goingDown >= start) {
2344 this.prefetchImg(goingDown);
2346 var goingUp = highCurrent + i;
2347 if (goingUp <= end) {
2348 this.prefetchImg(goingUp);
2353 var lim = this.twoPage.currentIndexL-4;
2355 lim = Math.max(lim, 0);
2356 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2357 this.prefetchImg(i);
2360 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2361 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2362 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2363 this.prefetchImg(i);
2369 // getPageWidth2UP()
2370 //______________________________________________________________________________
2371 BookReader.prototype.getPageWidth2UP = function(index) {
2372 // We return the width based on the dominant height
2373 var height = this._getPageHeight(index);
2374 var width = this._getPageWidth(index);
2375 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2379 //______________________________________________________________________________
2380 BookReader.prototype.search = function(term) {
2381 term = term.replace(/\//g, ' '); // strip slashes
2382 this.searchTerm = term;
2383 $('#BookReaderSearchScript').remove();
2384 var script = document.createElement("script");
2385 script.setAttribute('id', 'BookReaderSearchScript');
2386 script.setAttribute("type", "text/javascript");
2387 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2388 document.getElementsByTagName('head')[0].appendChild(script);
2389 $('#BookReaderSearchBox').val(term);
2390 $('#BookReaderSearchResults').html('Searching...');
2393 // BRSearchCallback()
2394 //______________________________________________________________________________
2395 BookReader.prototype.BRSearchCallback = function(txt) {
2397 if (jQuery.browser.msie) {
2398 var dom=new ActiveXObject("Microsoft.XMLDOM");
2402 var parser = new DOMParser();
2403 var dom = parser.parseFromString(txt, "text/xml");
2406 $('#BookReaderSearchResults').empty();
2407 $('#BookReaderSearchResults').append('<ul>');
2409 for (var key in this.searchResults) {
2410 if (null != this.searchResults[key].div) {
2411 $(this.searchResults[key].div).remove();
2413 delete this.searchResults[key];
2416 var pages = dom.getElementsByTagName('PAGE');
2418 if (0 == pages.length) {
2419 // $$$ it would be nice to echo the (sanitized) search result here
2420 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2422 for (var i = 0; i < pages.length; i++){
2423 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2426 var re = new RegExp (/_(\d{4})/);
2427 var reMatch = re.exec(pages[i].getAttribute('file'));
2428 var index = parseInt(reMatch[1], 10);
2429 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2431 var children = pages[i].childNodes;
2433 for (var j=0; j<children.length; j++) {
2434 //console.log(j + ' - ' + children[j].nodeName);
2435 //console.log(children[j].firstChild.nodeValue);
2436 if ('CONTEXT' == children[j].nodeName) {
2437 context += children[j].firstChild.nodeValue;
2438 } else if ('WORD' == children[j].nodeName) {
2439 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2441 var index = this.leafNumToIndex(index);
2442 if (null != index) {
2443 //coordinates are [left, bottom, right, top, [baseline]]
2444 //we'll skip baseline for now...
2445 var coords = children[j].getAttribute('coords').split(',',4);
2446 if (4 == coords.length) {
2447 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2452 var pageName = this.getPageName(index);
2453 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2454 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2455 //TODO: remove hardcoded instance name
2456 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2459 $('#BookReaderSearchResults').append('</ul>');
2461 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2462 $('#BookReaderSearchBox').val(this.searchTerm);
2464 this.updateSearchHilites();
2467 // updateSearchHilites()
2468 //______________________________________________________________________________
2469 BookReader.prototype.updateSearchHilites = function() {
2470 if (2 == this.mode) {
2471 this.updateSearchHilites2UP();
2473 this.updateSearchHilites1UP();
2477 // showSearchHilites1UP()
2478 //______________________________________________________________________________
2479 BookReader.prototype.updateSearchHilites1UP = function() {
2481 for (var key in this.searchResults) {
2483 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2484 var result = this.searchResults[key];
2485 if(null == result.div) {
2486 result.div = document.createElement('div');
2487 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2488 //console.log('appending ' + key);
2491 width: (result.r-result.l)/this.reduce + 'px',
2492 height: (result.b-result.t)/this.reduce + 'px',
2493 left: (result.l)/this.reduce + 'px',
2494 top: (result.t)/this.reduce +'px'
2498 //console.log(key + ' not displayed');
2499 this.searchResults[key].div=null;
2505 //______________________________________________________________________________
2506 // Returns the position of the gutter (line between the page images)
2507 BookReader.prototype.twoPageGutter = function() {
2508 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2512 //______________________________________________________________________________
2513 // Returns the offset for the top of the page images
2514 BookReader.prototype.twoPageTop = function() {
2515 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2518 // twoPageCoverWidth()
2519 //______________________________________________________________________________
2520 // Returns the width of the cover div given the total page width
2521 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2522 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2525 // twoPageGetViewCenter()
2526 //______________________________________________________________________________
2527 // Returns the percentage offset into twopageview div at the center of container div
2528 // { percentageX: float, percentageY: float }
2529 BookReader.prototype.twoPageGetViewCenter = function() {
2532 var containerOffset = $('#BRcontainer').offset();
2533 var viewOffset = $('#BRtwopageview').offset();
2534 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2535 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2540 // twoPageCenterView(percentageX, percentageY)
2541 //______________________________________________________________________________
2542 // Centers the point given by percentage from left,top of twopageview
2543 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2544 if ('undefined' == typeof(percentageX)) {
2547 if ('undefined' == typeof(percentageY)) {
2551 var viewWidth = $('#BRtwopageview').width();
2552 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2553 var intoViewX = percentageX * viewWidth;
2555 var viewHeight = $('#BRtwopageview').height();
2556 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2557 var intoViewY = percentageY * viewHeight;
2559 if (viewWidth < containerClientWidth) {
2560 // Can fit width without scrollbars - center by adjusting offset
2561 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2563 // Need to scroll to center
2564 $('#BRtwopageview').css('left', 0);
2565 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2568 if (viewHeight < containerClientHeight) {
2569 // Fits with scrollbars - add offset
2570 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2572 $('#BRtwopageview').css('top', 0);
2573 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2577 // twoPageFlipAreaHeight
2578 //______________________________________________________________________________
2579 // Returns the integer height of the click-to-flip areas at the edges of the book
2580 BookReader.prototype.twoPageFlipAreaHeight = function() {
2581 return parseInt(this.twoPage.height);
2584 // twoPageFlipAreaWidth
2585 //______________________________________________________________________________
2586 // Returns the integer width of the flip areas
2587 BookReader.prototype.twoPageFlipAreaWidth = function() {
2588 var max = 100; // $$$ TODO base on view width?
2591 var width = this.twoPage.width * 0.15;
2592 return parseInt(BookReader.util.clamp(width, min, max));
2595 // twoPageFlipAreaTop
2596 //______________________________________________________________________________
2597 // Returns integer top offset for flip areas
2598 BookReader.prototype.twoPageFlipAreaTop = function() {
2599 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2602 // twoPageLeftFlipAreaLeft
2603 //______________________________________________________________________________
2604 // Left offset for left flip area
2605 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2606 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2609 // twoPageRightFlipAreaLeft
2610 //______________________________________________________________________________
2611 // Left offset for right flip area
2612 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2613 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2616 // twoPagePlaceFlipAreas
2617 //______________________________________________________________________________
2618 // Readjusts position of flip areas based on current layout
2619 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2620 // We don't set top since it shouldn't change relative to view
2621 $(this.twoPage.leftFlipArea).css({
2622 left: this.twoPageLeftFlipAreaLeft() + 'px',
2623 width: this.twoPageFlipAreaWidth() + 'px'
2625 $(this.twoPage.rightFlipArea).css({
2626 left: this.twoPageRightFlipAreaLeft() + 'px',
2627 width: this.twoPageFlipAreaWidth() + 'px'
2631 // showSearchHilites2UP()
2632 //______________________________________________________________________________
2633 BookReader.prototype.updateSearchHilites2UP = function() {
2635 for (var key in this.searchResults) {
2636 key = parseInt(key, 10);
2637 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2638 var result = this.searchResults[key];
2639 if(null == result.div) {
2640 result.div = document.createElement('div');
2641 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2642 //console.log('appending ' + key);
2645 // We calculate the reduction factor for the specific page because it can be different
2646 // for each page in the spread
2647 var height = this._getPageHeight(key);
2648 var width = this._getPageWidth(key)
2649 var reduce = this.twoPage.height/height;
2650 var scaledW = parseInt(width*reduce);
2652 var gutter = this.twoPageGutter();
2654 if ('L' == this.getPageSide(key)) {
2655 pageL = gutter-scaledW;
2659 var pageT = this.twoPageTop();
2662 width: (result.r-result.l)*reduce + 'px',
2663 height: (result.b-result.t)*reduce + 'px',
2664 left: pageL+(result.l)*reduce + 'px',
2665 top: pageT+(result.t)*reduce +'px'
2669 //console.log(key + ' not displayed');
2670 if (null != this.searchResults[key].div) {
2671 //console.log('removing ' + key);
2672 $(this.searchResults[key].div).remove();
2674 this.searchResults[key].div=null;
2679 // removeSearchHilites()
2680 //______________________________________________________________________________
2681 BookReader.prototype.removeSearchHilites = function() {
2682 for (var key in this.searchResults) {
2683 if (null != this.searchResults[key].div) {
2684 $(this.searchResults[key].div).remove();
2685 this.searchResults[key].div=null;
2691 //______________________________________________________________________________
2692 BookReader.prototype.printPage = function() {
2693 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2695 /* iframe implementation
2697 if (null != this.printPopup) { // check if already showing
2700 this.printPopup = document.createElement("div");
2701 $(this.printPopup).css({
2702 position: 'absolute',
2704 left: ($('#BRcontainer').width()-400)/2 + 'px',
2707 border: "3px double #999999",
2709 backgroundColor: "#fff"
2710 }).appendTo('#BookReader');
2713 if (this.constMode1up == this.mode) {
2714 indexToPrint = this.firstIndex;
2716 indexToPrint = this.twoPage.currentIndexL;
2719 this.indexToPrint = indexToPrint;
2721 var htmlStr = '<div style="text-align: center;">';
2722 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>';
2723 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2724 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2725 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2726 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2727 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2729 htmlStr += '</div>';
2730 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2731 htmlStr += '</div>';
2733 this.printPopup.innerHTML = htmlStr;
2735 var iframe = document.createElement('iframe');
2736 iframe.id = 'printFrame';
2737 iframe.name = 'printFrame';
2738 iframe.width = '233px'; // 8.5 x 11 aspect
2739 iframe.height = '300px';
2741 var self = this; // closure
2743 $(iframe).load(function() {
2744 var doc = BookReader.util.getIFrameDocument(this);
2745 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2748 $('#printDiv').prepend(iframe);
2752 // Get print URI from current indices and mode
2753 BookReader.prototype.getPrintURI = function() {
2755 if (this.constMode2up == this.mode) {
2756 indexToPrint = this.twoPage.currentIndexL;
2758 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2761 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2762 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2763 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2765 if (this.constMode2up == this.mode) {
2766 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2767 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2768 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2770 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2773 return '/bookreader/print.php?' + options;
2776 /* iframe implementation
2777 BookReader.prototype.getPrintFrameContent = function(index) {
2778 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2779 // 8.5x11 so we should end up not overflowing on either paper size.
2780 var paperAspect = 8.5 / 11;
2781 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2785 // Rotate if possible and appropriate, to get larger image size on printed page
2786 if (this.canRotatePage(index)) {
2787 if (imageAspect > 1 && imageAspect > paperAspect) {
2788 // more wide than square, and more wide than paper
2790 imageAspect = 1/imageAspect;
2795 if (imageAspect > paperAspect) {
2796 // wider than paper, fit width
2797 fitAttrs = 'width="95%"';
2799 // taller than paper, fit height
2800 fitAttrs = 'height="95%"';
2803 var imageURL = this._getPageURI(index, 1, rotate);
2804 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2805 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2806 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2807 iframeStr += '</div>';
2808 iframeStr += '</body></html>';
2813 BookReader.prototype.updatePrintFrame = function(delta) {
2814 var newIndex = this.indexToPrint + delta;
2815 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2816 if (newIndex == this.indexToPrint) {
2819 this.indexToPrint = newIndex;
2820 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2821 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2826 //______________________________________________________________________________
2827 BookReader.prototype.showEmbedCode = function() {
2828 if (null != this.embedPopup) { // check if already showing
2832 this.embedPopup = document.createElement("div");
2833 $(this.embedPopup).css({
2834 position: 'absolute',
2836 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2839 border: "3px double #999999",
2841 backgroundColor: "#fff"
2842 }).appendTo('#BookReader');
2844 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2845 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>';
2846 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2847 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2849 this.embedPopup.innerHTML = htmlStr;
2850 $(this.embedPopup).find('input').bind('click', function() {
2856 //______________________________________________________________________________
2857 BookReader.prototype.autoToggle = function() {
2859 var bComingFrom1up = false;
2860 if (2 != this.mode) {
2861 bComingFrom1up = true;
2865 // Change to autofit if book is too large
2866 if (this.reduce < this.twoPageGetAutofitReduce()) {
2871 if (null == this.autoTimer) {
2872 this.flipSpeed = 2000;
2874 // $$$ Draw events currently cause layout problems when they occur during animation.
2875 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2876 // we workaround for now by not triggering immediate animation in that case.
2877 // See https://bugs.launchpad.net/gnubook/+bug/328327
2878 if (('rl' == this.pageProgression) && bComingFrom1up) {
2879 // don't flip immediately -- wait until timer fires
2882 this.flipFwdToIndex();
2885 $('#BRtoolbar .play').hide();
2886 $('#BRtoolbar .pause').show();
2887 this.autoTimer=setInterval(function(){
2888 if (self.animating) {return;}
2890 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2891 self.flipBackToIndex(1); // $$$ really what we want?
2893 self.flipFwdToIndex();
2902 //______________________________________________________________________________
2903 // Stop autoplay mode, allowing animations to finish
2904 BookReader.prototype.autoStop = function() {
2905 if (null != this.autoTimer) {
2906 clearInterval(this.autoTimer);
2907 this.flipSpeed = 'fast';
2908 $('#BRtoolbar .pause').hide();
2909 $('#BRtoolbar .play').show();
2910 this.autoTimer = null;
2914 // stopFlipAnimations
2915 //______________________________________________________________________________
2916 // Immediately stop flip animations. Callbacks are triggered.
2917 BookReader.prototype.stopFlipAnimations = function() {
2919 this.autoStop(); // Clear timers
2921 // Stop animation, clear queue, trigger callbacks
2922 if (this.leafEdgeTmp) {
2923 $(this.leafEdgeTmp).stop(false, true);
2925 jQuery.each(this.prefetchedImgs, function() {
2926 $(this).stop(false, true);
2929 // And again since animations also queued in callbacks
2930 if (this.leafEdgeTmp) {
2931 $(this.leafEdgeTmp).stop(false, true);
2933 jQuery.each(this.prefetchedImgs, function() {
2934 $(this).stop(false, true);
2939 // keyboardNavigationIsDisabled(event)
2940 // - returns true if keyboard navigation should be disabled for the event
2941 //______________________________________________________________________________
2942 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2943 if (event.target.tagName == "INPUT") {
2949 // gutterOffsetForIndex
2950 //______________________________________________________________________________
2952 // Returns the gutter offset for the spread containing the given index.
2953 // This function supports RTL
2954 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2956 // To find the offset of the gutter from the middle we calculate our percentage distance
2957 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2958 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2960 // But then again for RTL it's the opposite
2961 if ('rl' == this.pageProgression) {
2969 //______________________________________________________________________________
2970 // Returns the width of the leaf edge div for the page with index given
2971 BookReader.prototype.leafEdgeWidth = function(pindex) {
2972 // $$$ could there be single pixel rounding errors for L vs R?
2973 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2974 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2976 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2980 // jumpIndexForLeftEdgePageX
2981 //______________________________________________________________________________
2982 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2983 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2984 if ('rl' != this.pageProgression) {
2985 // LTR - flipping backward
2986 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2988 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2989 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2993 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2994 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2999 // jumpIndexForRightEdgePageX
3000 //______________________________________________________________________________
3001 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3002 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3003 if ('rl' != this.pageProgression) {
3005 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3006 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3009 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3010 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3015 BookReader.prototype.initToolbar = function(mode, ui) {
3017 $("#BookReader").append("<div id='BRtoolbar'>"
3018 + "<span id='BRtoolbarbuttons' style='float: right'>"
3019 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3020 + "<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>"
3021 + "<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>"
3022 + "<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>"
3023 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3027 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3028 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3029 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3030 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3031 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3032 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3033 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3036 + "<span id='#BRbooktitle'>"
3037 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3041 this.updateToolbarZoom(this.reduce); // Pretty format
3043 if (ui == "embed") {
3044 $("#BookReader a.logo").attr("target","_blank");
3047 // $$$ turn this into a member variable
3048 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3050 // We build in mode 2
3053 this.bindToolbarNavHandlers(jToolbar);
3055 // Setup tooltips -- later we could load these from a file for i18n
3056 var titles = { '.logo': 'Go to Archive.org',
3057 '.zoom_in': 'Zoom in',
3058 '.zoom_out': 'Zoom out',
3059 '.one_page_mode': 'One-page view',
3060 '.two_page_mode': 'Two-page view',
3061 '.thumbnail_mode': 'Thumbnail view',
3062 '.print': 'Print this page',
3063 '.embed': 'Embed bookreader',
3064 '.book_left': 'Flip left',
3065 '.book_right': 'Flip right',
3066 '.book_up': 'Page up',
3067 '.book_down': 'Page down',
3070 '.book_top': 'First page',
3071 '.book_bottom': 'Last page'
3073 if ('rl' == this.pageProgression) {
3074 titles['.book_leftmost'] = 'Last page';
3075 titles['.book_rightmost'] = 'First page';
3077 titles['.book_leftmost'] = 'First page';
3078 titles['.book_rightmost'] = 'Last page';
3081 for (var icon in titles) {
3082 jToolbar.find(icon).attr('title', titles[icon]);
3085 // Hide mode buttons and autoplay if 2up is not available
3086 // $$$ if we end up with more than two modes we should show the applicable buttons
3087 if ( !this.canSwitchToMode(this.constMode2up) ) {
3088 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3091 // Switch to requested mode -- binds other click handlers
3092 this.switchToolbarMode(mode);
3097 // switchToolbarMode
3098 //______________________________________________________________________________
3099 // Update the toolbar for the given mode (changes navigation buttons)
3100 // $$$ we should soon split the toolbar out into its own module
3101 BookReader.prototype.switchToolbarMode = function(mode) {
3104 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3105 $('#BRtoolbar .BRtoolbarmode2').hide();
3106 $('#BRtoolbar .BRtoolbarmode3').hide();
3107 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3108 } else if (2 == mode) {
3110 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3111 $('#BRtoolbar .BRtoolbarmode1').hide();
3112 $('#BRtoolbar .BRtoolbarmode3').hide();
3113 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3116 $('#BRtoolbar .BRtoolbarzoom').hide();
3117 $('#BRtoolbar .BRtoolbarmode2').hide();
3118 $('#BRtoolbar .BRtoolbarmode1').hide();
3119 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3123 // bindToolbarNavHandlers
3124 //______________________________________________________________________________
3125 // Binds the toolbar handlers
3126 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3128 var self = this; // closure
3130 jToolbar.find('.book_left').bind('click', function(e) {
3135 jToolbar.find('.book_right').bind('click', function(e) {
3140 jToolbar.find('.book_up').bind('click', function(e) {
3145 jToolbar.find('.book_down').bind('click', function(e) {
3150 jToolbar.find('.print').bind('click', function(e) {
3155 jToolbar.find('.embed').bind('click', function(e) {
3156 self.showEmbedCode();
3160 jToolbar.find('.play').bind('click', function(e) {
3165 jToolbar.find('.pause').bind('click', function(e) {
3170 jToolbar.find('.book_top').bind('click', function(e) {
3175 jToolbar.find('.book_bottom').bind('click', function(e) {
3180 jToolbar.find('.book_leftmost').bind('click', function(e) {
3185 jToolbar.find('.book_rightmost').bind('click', function(e) {
3191 // updateToolbarZoom(reduce)
3192 //______________________________________________________________________________
3193 // Update the displayed zoom factor based on reduction factor
3194 BookReader.prototype.updateToolbarZoom = function(reduce) {
3196 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3199 value = (100 / reduce).toFixed(2);
3200 // Strip trailing zeroes and decimal if all zeroes
3201 value = value.replace(/0+$/,'');
3202 value = value.replace(/\.$/,'');
3205 $('#BRzoom').text(value);
3208 // firstDisplayableIndex
3209 //______________________________________________________________________________
3210 // Returns the index of the first visible page, dependent on the mode.
3211 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3212 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3213 BookReader.prototype.firstDisplayableIndex = function() {
3214 if (this.mode != this.constMode2up) {
3218 if ('rl' != this.pageProgression) {
3220 if (this.getPageSide(0) == 'L') {
3227 if (this.getPageSide(0) == 'R') {
3235 // lastDisplayableIndex
3236 //______________________________________________________________________________
3237 // Returns the index of the last visible page, dependent on the mode.
3238 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3239 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3240 BookReader.prototype.lastDisplayableIndex = function() {
3242 var lastIndex = this.numLeafs - 1;
3244 if (this.mode != this.constMode2up) {
3248 if ('rl' != this.pageProgression) {
3250 if (this.getPageSide(lastIndex) == 'R') {
3253 return lastIndex + 1;
3257 if (this.getPageSide(lastIndex) == 'L') {
3260 return lastIndex + 1;
3265 // shortTitle(maximumCharacters)
3267 // Returns a shortened version of the title with the maximum number of characters
3268 BookReader.prototype.shortTitle = function(maximumCharacters) {
3269 if (this.bookTitle.length < maximumCharacters) {
3270 return this.bookTitle;
3273 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3278 // Parameter related functions
3280 // updateFromParams(params)
3282 // Update ourselves from the params object.
3284 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3285 BookReader.prototype.updateFromParams = function(params) {
3286 if ('undefined' != typeof(params.mode)) {
3287 this.switchMode(params.mode);
3291 if ('undefined' != typeof(params.searchTerm)) {
3292 if (this.searchTerm != params.searchTerm) {
3293 this.search(params.searchTerm);
3297 // $$$ process /zoom
3299 // We only respect page if index is not set
3300 if ('undefined' != typeof(params.index)) {
3301 if (params.index != this.currentIndex()) {
3302 this.jumpToIndex(params.index);
3304 } else if ('undefined' != typeof(params.page)) {
3305 // $$$ this assumes page numbers are unique
3306 if (params.page != this.getPageNum(this.currentIndex())) {
3307 this.jumpToPage(params.page);
3311 // $$$ process /region
3312 // $$$ process /highlight
3315 // paramsFromFragment(urlFragment)
3317 // Returns a object with configuration parametes from a URL fragment.
3319 // E.g paramsFromFragment(window.location.hash)
3320 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3321 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3325 // For convenience we allow an initial # character (as from window.location.hash)
3326 // but don't require it
3327 if (urlFragment.substr(0,1) == '#') {
3328 urlFragment = urlFragment.substr(1);
3331 // Simple #nn syntax
3332 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3333 if ( !isNaN(oldStyleLeafNum) ) {
3334 params.index = oldStyleLeafNum;
3336 // Done processing if using old-style syntax
3340 // Split into key-value pairs
3341 var urlArray = urlFragment.split('/');
3343 for (var i = 0; i < urlArray.length; i += 2) {
3344 urlHash[urlArray[i]] = urlArray[i+1];
3348 if ('1up' == urlHash['mode']) {
3349 params.mode = this.constMode1up;
3350 } else if ('2up' == urlHash['mode']) {
3351 params.mode = this.constMode2up;
3352 } else if ('thumb' == urlHash['mode']) {
3353 params.mode = this.constModeThumb;
3357 if ('undefined' != typeof(urlHash['page'])) {
3358 // page was set -- may not be int
3359 params.page = urlHash['page'];
3362 // $$$ process /region
3363 // $$$ process /search
3365 if (urlHash['search'] != undefined) {
3366 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3369 // $$$ process /highlight
3374 // paramsFromCurrent()
3376 // Create a params object from the current parameters.
3377 BookReader.prototype.paramsFromCurrent = function() {
3381 var index = this.currentIndex();
3382 var pageNum = this.getPageNum(index);
3383 if ((pageNum === 0) || pageNum) {
3384 params.page = pageNum;
3387 params.index = index;
3388 params.mode = this.mode;
3394 if (this.searchHighlightVisible()) {
3395 params.searchTerm = this.searchTerm;
3401 // fragmentFromParams(params)
3403 // Create a fragment string from the params object.
3404 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3405 BookReader.prototype.fragmentFromParams = function(params) {
3406 var separator = '/';
3410 if ('undefined' != typeof(params.page)) {
3411 fragments.push('page', params.page);
3413 // Don't have page numbering -- use index instead
3414 fragments.push('page', 'n' + params.index);
3421 if ('undefined' != typeof(params.mode)) {
3422 if (params.mode == this.constMode1up) {
3423 fragments.push('mode', '1up');
3424 } else if (params.mode == this.constMode2up) {
3425 fragments.push('mode', '2up');
3426 } else if (params.mode == this.constModeThumb) {
3427 fragments.push('mode', 'thumb');
3429 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3434 if (params.searchTerm) {
3435 fragments.push('search', params.searchTerm);
3438 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3441 // getPageIndex(pageNum)
3443 // Returns the *highest* index the given page number, or undefined
3444 BookReader.prototype.getPageIndex = function(pageNum) {
3445 var pageIndices = this.getPageIndices(pageNum);
3447 if (pageIndices.length > 0) {
3448 return pageIndices[pageIndices.length - 1];
3454 // getPageIndices(pageNum)
3456 // Returns an array (possibly empty) of the indices with the given page number
3457 BookReader.prototype.getPageIndices = function(pageNum) {
3460 // Check for special "nXX" page number
3461 if (pageNum.slice(0,1) == 'n') {
3463 var pageIntStr = pageNum.slice(1, pageNum.length);
3464 var pageIndex = parseInt(pageIntStr);
3465 indices.push(pageIndex);
3468 // Do nothing... will run through page names and see if one matches
3473 for (i=0; i<this.numLeafs; i++) {
3474 if (this.getPageNum(i) == pageNum) {
3482 // getPageName(index)
3484 // Returns the name of the page as it should be displayed in the user interface
3485 BookReader.prototype.getPageName = function(index) {
3486 return 'Page ' + this.getPageNum(index);
3489 // updateLocationHash
3491 // Update the location hash from the current parameters. Call this instead of manually
3492 // using window.location.replace
3493 BookReader.prototype.updateLocationHash = function() {
3494 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3495 window.location.replace(newHash);
3497 // This is the variable checked in the timer. Only user-generated changes
3498 // to the URL will trigger the event.
3499 this.oldLocationHash = newHash;
3502 // startLocationPolling
3504 // Starts polling of window.location to see hash fragment changes
3505 BookReader.prototype.startLocationPolling = function() {
3506 var self = this; // remember who I am
3507 self.oldLocationHash = window.location.hash;
3509 if (this.locationPollId) {
3510 clearInterval(this.locationPollID);
3511 this.locationPollId = null;
3514 this.locationPollId = setInterval(function() {
3515 var newHash = window.location.hash;
3516 if (newHash != self.oldLocationHash) {
3517 if (newHash != self.oldUserHash) { // Only process new user hash once
3518 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3520 // Queue change if animating
3521 if (self.animating) {
3523 self.animationFinishedCallback = function() {
3524 self.updateFromParams(self.paramsFromFragment(newHash));
3526 } else { // update immediately
3527 self.updateFromParams(self.paramsFromFragment(newHash));
3529 self.oldUserHash = newHash;
3537 // Returns true if we can switch to the requested mode
3538 BookReader.prototype.canSwitchToMode = function(mode) {
3539 if (mode == this.constMode2up) {
3540 // check there are enough pages to display
3541 // $$$ this is a workaround for the mis-feature that we can't display
3542 // short books in 2up mode
3543 if (this.numLeafs < 6) {
3551 // searchHighlightVisible
3553 // Returns true if a search highlight is currently being displayed
3554 BookReader.prototype.searchHighlightVisible = function() {
3555 if (this.constMode2up == this.mode) {
3556 if (this.searchResults[this.twoPage.currentIndexL]
3557 || this.searchResults[this.twoPage.currentIndexR]) {
3561 if (this.searchResults[this.currentIndex()]) {
3568 // getPageBackgroundColor
3570 // Returns a CSS property string for the background color for the given page
3571 // $$$ turn into regular CSS?
3572 BookReader.prototype.getPageBackgroundColor = function(index) {
3573 if (index >= 0 && index < this.numLeafs) {
3575 return this.pageDefaultBackgroundColor;
3583 // Returns the page width for the given index, or first or last page if out of range
3584 BookReader.prototype._getPageWidth = function(index) {
3585 // Synthesize a page width for pages not actually present in book.
3586 // May or may not be the best approach.
3587 // If index is out of range we return the width of first or last page
3588 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3589 return this.getPageWidth(index);
3594 // Returns the page height for the given index, or first or last page if out of range
3595 BookReader.prototype._getPageHeight= function(index) {
3596 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3597 return this.getPageHeight(index);
3602 // Returns the page URI or transparent image if out of range
3603 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3604 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3605 return this.imagesBaseURL + "/transparent.png";
3608 if ('undefined' == typeof(reduce)) {
3609 // reduce not passed in
3610 var ratio = this.getPageHeight(index) / this.twoPage.height;
3612 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3615 } else if (ratio < 4) {
3617 } else if (ratio < 8) {
3619 } else if (ratio < 16) {
3621 } else if (ratio < 32) {
3629 return this.getPageURI(index, reduce, rotate);
3632 // Library functions
3634 clamp: function(value, min, max) {
3635 return Math.min(Math.max(value, min), max);
3638 getIFrameDocument: function(iframe) {
3639 // Adapted from http://xkr.us/articles/dom/iframe-document/
3640 var outer = (iframe.contentWindow || iframe.contentDocument);
3641 return (outer.document || outer);
3644 decodeURIComponentPlus: function(value) {
3645 // Decodes a URI component and converts '+' to ' '
3646 return decodeURIComponent(value).replace(/\+/g, ' ');
3649 encodeURIComponentPlus: function(value) {
3650 // Encodes a URI component and converts ' ' to '+'
3651 return encodeURIComponent(value).replace(/%20/g, '+');
3653 // The final property here must NOT have a comma after it - IE7