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
43 this.thumbWidth = 100;
44 this.thumbRowBuffer = 3; // number of rows to pre-cache out a view
45 this.displayedRows=[];
46 this.displayedIndices = [];
47 //this.indicesToDisplay = [];
49 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
52 this.animating = false;
54 this.autoTimer = null;
55 this.flipSpeed = 'fast';
57 this.twoPagePopUp = null;
58 this.leafEdgeTmp = null;
59 this.embedPopup = null;
60 this.printPopup = null;
63 this.searchResults = {};
65 this.firstIndex = null;
67 this.lastDisplayableIndex2up = null;
69 // We link to index.php to avoid redirect which breaks back button
70 this.logoURL = 'http://www.archive.org/index.php';
72 // Base URL for images
73 this.imagesBaseURL = '/bookreader/images/';
76 this.constMode1up = 1;
77 this.constMode2up = 2;
78 this.constModeThumb = 3;
81 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
83 // Object to hold parameters related to 2up mode
85 coverInternalPadding: 10, // Width of cover
86 coverExternalPadding: 10, // Padding outside of cover
87 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
91 // Background color for pages (e.g. when loading page image)
92 // $$$ TODO dynamically calculate based on page images
93 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
97 //______________________________________________________________________________
98 BookReader.prototype.init = function() {
100 var startIndex = undefined;
101 this.pageScale = this.reduce; // preserve current reduce
103 // Find start index and mode if set in location hash
104 var params = this.paramsFromFragment(window.location.hash);
106 if ('undefined' != typeof(params.index)) {
107 startIndex = params.index;
108 } else if ('undefined' != typeof(params.page)) {
109 startIndex = this.getPageIndex(params.page);
112 if ('undefined' == typeof(startIndex)) {
113 if ('undefined' != typeof(this.titleLeaf)) {
114 startIndex = this.leafNumToIndex(this.titleLeaf);
118 if ('undefined' == typeof(startIndex)) {
122 if ('undefined' != typeof(params.mode)) {
123 this.mode = params.mode;
126 // Set document title -- may have already been set in enclosing html for
127 // search engine visibility
128 document.title = this.shortTitle(50);
130 // Sanitize parameters
131 if ( !this.canSwitchToMode( this.mode ) ) {
132 this.mode = this.constMode1up;
135 $("#BookReader").empty();
136 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
137 $("#BookReader").append("<div id='BRcontainer'></div>");
138 $("#BRcontainer").append("<div id='BRpageview'></div>");
140 $("#BRcontainer").bind('scroll', this, function(e) {
144 this.setupKeyListeners();
145 this.startLocationPolling();
147 $(window).bind('resize', this, function(e) {
148 //console.log('resize!');
149 if (1 == e.data.mode) {
150 //console.log('centering 1page view');
151 e.data.centerPageView();
152 $('#BRpageview').empty()
153 e.data.displayedIndices = [];
154 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
156 } else if (3 == e.data.mode){
157 e.data.prepareThumbnailView();
159 //console.log('drawing 2 page view');
161 // We only need to prepare again in autofit (size of spread changes)
162 if (e.data.twoPage.autofit) {
163 e.data.prepareTwoPageView();
165 // Re-center if the scrollbars have disappeared
166 var center = e.data.twoPageGetViewCenter();
167 var doRecenter = false;
168 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
169 center.percentageX = 0.5;
172 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
173 center.percentageY = 0.5;
177 e.data.twoPageCenterView(center.percentageX, center.percentageY);
183 $('.BRpagediv1up').bind('mousedown', this, function(e) {
184 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
185 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
188 if (1 == this.mode) {
189 this.resizePageView();
190 this.firstIndex = startIndex;
191 this.jumpToIndex(startIndex);
192 } else if (3 == this.mode) {
193 this.firstIndex = startIndex;
194 this.prepareThumbnailView();
195 this.jumpToIndex(startIndex);
197 //this.resizePageView();
199 this.displayedIndices=[0];
200 this.firstIndex = startIndex;
201 this.displayedIndices = [this.firstIndex];
202 //console.log('titleLeaf: %d', this.titleLeaf);
203 //console.log('displayedIndices: %s', this.displayedIndices);
204 this.prepareTwoPageView();
207 // Enact other parts of initial params
208 this.updateFromParams(params);
211 BookReader.prototype.setupKeyListeners = function() {
224 // We use document here instead of window to avoid a bug in jQuery on IE7
225 $(document).keydown(function(e) {
227 // Keyboard navigation
228 if (!self.keyboardNavigationIsDisabled(e)) {
232 // In 1up mode page scrolling is handled by browser
233 if (2 == self.mode) {
240 if (2 == self.mode) {
254 if (2 == self.mode) {
260 if (2 == self.mode) {
271 //______________________________________________________________________________
272 BookReader.prototype.drawLeafs = function() {
273 if (1 == this.mode) {
274 this.drawLeafsOnePage();
275 } else if(3 == this.mode) {
276 this.drawLeafsThumbnail();
278 this.drawLeafsTwoPage();
283 //______________________________________________________________________________
284 BookReader.prototype.setDragHandler = function(div) {
285 div.dragging = false;
287 $(div).unbind('mousedown').bind('mousedown', function(e) {
290 //console.log('mousedown at ' + e.pageY);
292 this.dragging = true;
293 this.prevMouseX = e.pageX;
294 this.prevMouseY = e.pageY;
296 var startX = e.pageX;
297 var startY = e.pageY;
298 var startTop = $('#BRcontainer').attr('scrollTop');
299 var startLeft = $('#BRcontainer').attr('scrollLeft');
303 $(div).unbind('mousemove').bind('mousemove', function(ee) {
306 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
308 var offsetX = ee.pageX - this.prevMouseX;
309 var offsetY = ee.pageY - this.prevMouseY;
312 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
313 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
316 this.prevMouseX = ee.pageX;
317 this.prevMouseY = ee.pageY;
321 $(div).unbind('mouseup').bind('mouseup', function(ee) {
323 //console.log('mouseup');
325 this.dragging = false;
328 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
330 //console.log('mouseleave');
332 this.dragging = false;
335 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
337 //console.log('mouseenter');
339 this.dragging = false;
343 // setDragHandler2UP()
344 //______________________________________________________________________________
345 BookReader.prototype.setDragHandler2UP = function(div) {
346 div.dragging = false;
348 $(div).unbind('mousedown').bind('mousedown', function(e) {
351 //console.log('mousedown at ' + e.pageY);
353 this.dragStart = {x: e.pageX, y: e.pageY };
354 this.mouseDown = true;
355 this.dragging = false; // wait until drag distance
356 this.prevMouseX = e.pageX;
357 this.prevMouseY = e.pageY;
359 var startX = e.pageX;
360 var startY = e.pageY;
361 var startTop = $('#BRcontainer').attr('scrollTop');
362 var startLeft = $('#BRcontainer').attr('scrollLeft');
366 $(div).unbind('mousemove').bind('mousemove', function(ee) {
369 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
371 var offsetX = ee.pageX - this.prevMouseX;
372 var offsetY = ee.pageY - this.prevMouseY;
374 var minDragDistance = 5; // $$$ constant
376 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
378 if (this.mouseDown && (distance > minDragDistance)) {
379 //console.log('drag start!');
381 this.dragging = true;
385 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
386 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
387 this.prevMouseX = ee.pageX;
388 this.prevMouseY = ee.pageY;
395 $(div).unbind('mouseup').bind('mouseup', function(ee) {
397 //console.log('mouseup');
399 this.dragging = false;
400 this.mouseDown = false;
405 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
407 //console.log('mouseleave');
409 this.dragging = false;
410 this.mouseDown = false;
413 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
415 //console.log('mouseenter');
417 this.dragging = false;
418 this.mouseDown = false;
422 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
423 //console.log('setting handler');
424 //console.log(element.tagName);
426 $(element).unbind('click').bind('click', data, function(e) {
429 //console.log('click!');
431 if (this.mouseDown && (!this.dragging)) {
432 //console.log('click not dragging!');
436 this.dragging = false;
437 this.mouseDown = false;
441 // drawLeafsOnePage()
442 //______________________________________________________________________________
443 BookReader.prototype.drawLeafsOnePage = function() {
444 //alert('drawing leafs!');
448 var scrollTop = $('#BRcontainer').attr('scrollTop');
449 var scrollBottom = scrollTop + $('#BRcontainer').height();
450 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
452 var indicesToDisplay = [];
457 for (i=0; i<this.numLeafs; i++) {
458 var height = parseInt(this._getPageHeight(i)/this.reduce);
460 leafBottom += height;
461 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
462 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
463 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
464 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
465 if (topInView | bottomInView | middleInView) {
466 //console.log('displayed: ' + this.displayedIndices);
467 //console.log('to display: ' + i);
468 indicesToDisplay.push(i);
470 leafTop += height +10;
474 var firstIndexToDraw = indicesToDisplay[0];
475 this.firstIndex = firstIndexToDraw;
477 // Update hash, but only if we're currently displaying a leaf
478 // Hack that fixes #365790
479 if (this.displayedIndices.length > 0) {
480 this.updateLocationHash();
483 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
485 indicesToDisplay.unshift(firstIndexToDraw);
488 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
489 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
490 indicesToDisplay.push(lastIndexToDraw+1);
495 for (i=0; i<firstIndexToDraw; i++) {
496 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
499 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
500 var viewWidth = $('#BRcontainer').attr('scrollWidth');
503 for (i=0; i<indicesToDisplay.length; i++) {
504 var index = indicesToDisplay[i];
505 var height = parseInt(this._getPageHeight(index)/this.reduce);
507 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
508 var width = parseInt(this._getPageWidth(index)/this.reduce);
509 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
510 var div = document.createElement("div");
511 div.className = 'BRpagediv1up';
512 div.id = 'pagediv'+index;
513 div.style.position = "absolute";
514 $(div).css('top', leafTop + 'px');
515 var left = (viewWidth-width)>>1;
516 if (left<0) left = 0;
517 $(div).css('left', left+'px');
518 $(div).css('width', width+'px');
519 $(div).css('height', height+'px');
520 //$(div).text('loading...');
522 this.setDragHandler(div);
524 $('#BRpageview').append(div);
526 var img = document.createElement("img");
527 img.src = this._getPageURI(index, this.reduce, 0);
528 $(img).css('width', width+'px');
529 $(img).css('height', height+'px');
533 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
536 leafTop += height +10;
540 for (i=0; i<this.displayedIndices.length; i++) {
541 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
542 var index = this.displayedIndices[i];
543 //console.log('Removing leaf ' + index);
544 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
545 $('#pagediv'+index).remove();
547 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
551 this.displayedIndices = indicesToDisplay.slice();
552 this.updateSearchHilites();
554 if (null != this.getPageNum(firstIndexToDraw)) {
555 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
557 $("#BRpagenum").val('');
560 this.updateToolbarZoom(this.reduce);
564 // drawLeafsThumbnail()
565 //______________________________________________________________________________
566 BookReader.prototype.drawLeafsThumbnail = function() {
567 //alert('drawing leafs!');
570 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
572 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
584 for (i=0; i<this.numLeafs; i++) {
585 leafWidth = this.thumbWidth;
586 if (rightPos + (leafWidth + this.padding) > viewWidth){
592 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
593 if (leafMap[currentRow].leafs===undefined) {
594 leafMap[currentRow].leafs = [];
595 leafMap[currentRow].height = 0;
596 leafMap[currentRow].top = 0;
598 leafMap[currentRow].leafs[leafIndex] = {};
599 leafMap[currentRow].leafs[leafIndex].num = i;
600 leafMap[currentRow].leafs[leafIndex].left = rightPos;
602 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
603 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
604 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
605 rightPos += leafWidth + this.padding;
606 if (rightPos > maxRight) { maxRight = rightPos; }
610 // reset the bottom position based on thumbnails
611 $('#BRpageview').height(bottomPos);
613 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
614 var scrollTop = $('#BRcontainer').attr('scrollTop');
615 var scrollBottom = scrollTop + $('#BRcontainer').height();
619 var rowsToDisplay = [];
621 for (i=0; i<leafMap.length; i++) {
622 leafBottom += this.padding + leafMap[i].height;
623 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
624 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
625 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
626 if (topInView | bottomInView | middleInView) {
627 //console.log('row to display: ' + j);
628 rowsToDisplay.push(i);
630 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
631 leafTop = leafBottom;
634 // create a buffer of preloaded rows before and after the visible rows
635 var firstRow = rowsToDisplay[0];
636 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
637 for (i=1; i<this.thumbRowBuffer+1; i++) {
638 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
640 for (i=1; i<this.thumbRowBuffer+1; i++) {
641 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
644 // Update hash, but only if we're currently displaying a leaf
645 // Hack that fixes #365790
646 if (this.displayedRows.length > 0) {
647 this.updateLocationHash();
658 for (i=0; i<rowsToDisplay.length; i++) {
659 if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {
660 row = rowsToDisplay[i];
662 for (j=0; j<leafMap[row].leafs.length; j++) {
664 leaf = leafMap[row].leafs[j].num;
666 leafWidth = this.thumbWidth;
667 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
668 leafTop = leafMap[row].top;
669 left = leafMap[row].leafs[index].left + pageViewBuffer;
670 if ('rl' == this.pageProgression){
671 left = viewWidth - leafWidth - left;
674 div = document.createElement("div");
675 div.id = 'pagediv'+leaf;
676 div.style.position = "absolute";
677 div.className = "BRpagedivthumb";
679 left += this.padding;
680 $(div).css('top', leafTop + 'px');
681 $(div).css('left', left+'px');
682 $(div).css('width', leafWidth+'px');
683 $(div).css('height', leafHeight+'px');
684 //$(div).text('loading...');
686 // link to page in single page mode
687 link = document.createElement("a");
688 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
691 $('#BRpageview').append(div);
693 img = document.createElement("img");
694 img.src = this.getPageURI(leaf);
695 $(img).css('width', leafWidth+'px');
696 $(img).css('height', leafHeight+'px');
697 img.style.border = "0";
699 //console.log('displaying thumbnail: ' + leafMap[j]);
704 // remove previous highlights
705 if ($('.BRpagedivthumb_highlight').length>0) {
706 div = $('.BRpagedivthumb_highlight')
707 div.attr({className: 'BRpagedivthumb' });
709 // highlight current page
710 $('#pagediv'+this.currentIndex()).attr({className: 'BRpagedivthumb_highlight' });
713 for (i=0; i<this.displayedRows.length; i++) {
714 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
715 row = this.displayedRows[i];
716 for (k=0; k<leafMap[row].leafs.length; k++) {
717 index = leafMap[row].leafs[k].num;
718 //console.log('Removing leaf ' + index);
719 $('#pagediv'+index).remove();
723 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
727 this.displayedRows = rowsToDisplay.slice();
729 if (null !== this.getPageNum(this.currentIndex())) {
730 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
732 $("#BRpagenum").val('');
735 this.updateToolbarZoom(this.reduce);
738 // drawLeafsTwoPage()
739 //______________________________________________________________________________
740 BookReader.prototype.drawLeafsTwoPage = function() {
741 var scrollTop = $('#BRtwopageview').attr('scrollTop');
742 var scrollBottom = scrollTop + $('#BRtwopageview').height();
744 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
746 var indexL = this.twoPage.currentIndexL;
748 var heightL = this._getPageHeight(indexL);
749 var widthL = this._getPageWidth(indexL);
751 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
752 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
753 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
754 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
755 //console.log(leafEdgeWidthL);
757 var middle = this.twoPage.middle; // $$$ getter instead?
758 var top = this.twoPageTop();
759 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
761 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
762 this.twoPage.gutter = this.twoPageGutter();
764 this.prefetchImg(indexL);
765 $(this.prefetchedImgs[indexL]).css({
766 position: 'absolute',
767 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
770 backgroundColor: this.getPageBackgroundColor(indexL),
771 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
772 width: this.twoPage.scaledWL + 'px',
773 borderRight: '1px solid black',
775 }).appendTo('#BRtwopageview');
777 var indexR = this.twoPage.currentIndexR;
778 var heightR = this._getPageHeight(indexR);
779 var widthR = this._getPageWidth(indexR);
781 // $$$ should use getwidth2up?
782 //var scaledWR = this.twoPage.height*widthR/heightR;
783 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
784 this.prefetchImg(indexR);
785 $(this.prefetchedImgs[indexR]).css({
786 position: 'absolute',
787 left: this.twoPage.gutter+'px',
790 backgroundColor: this.getPageBackgroundColor(indexR),
791 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
792 width: this.twoPage.scaledWR + 'px',
793 borderLeft: '1px solid black',
795 }).appendTo('#BRtwopageview');
798 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
799 this.setMouseHandlers2UP();
800 this.twoPageSetCursor();
802 this.updatePageNumBox2UP();
803 this.updateToolbarZoom(this.reduce);
805 // this.twoPagePlaceFlipAreas(); // No longer used
809 // updatePageNumBox2UP
810 //______________________________________________________________________________
811 BookReader.prototype.updatePageNumBox2UP = function() {
812 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
813 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
815 $("#BRpagenum").val('');
817 this.updateLocationHash();
821 //______________________________________________________________________________
822 BookReader.prototype.loadLeafs = function() {
826 if (null == this.timer) {
827 this.timer=setTimeout(function(){self.drawLeafs()},250);
829 clearTimeout(this.timer);
830 this.timer=setTimeout(function(){self.drawLeafs()},250);
836 // Pass 1 to zoom in, anything else to zoom out
837 //______________________________________________________________________________
838 BookReader.prototype.zoom = function(direction) {
840 case this.constMode1up:
841 return this.zoom1up(direction);
842 case this.constMode2up:
843 return this.zoom2up(direction);
848 //______________________________________________________________________________
849 BookReader.prototype.zoom1up = function(dir) {
851 if (2 == this.mode) { //can only zoom in 1-page mode
856 // $$$ with flexible zoom we could "snap" to /2 page reductions
857 // for better scaling
859 if (this.reduce <= 0.5) return;
860 this.reduce*=0.5; //zoom in
862 if (this.reduce >= 8) return;
863 this.reduce*=2; //zoom out
866 this.pageScale = this.reduce; // preserve current reduce
867 this.resizePageView();
869 $('#BRpageview').empty()
870 this.displayedIndices = [];
873 this.updateToolbarZoom(this.reduce);
875 // Recalculate search hilites
876 this.removeSearchHilites();
877 this.updateSearchHilites();
882 //______________________________________________________________________________
883 BookReader.prototype.resizePageView = function() {
886 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
887 var viewWidth = $('#BRcontainer').attr('clientWidth');
889 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
890 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
891 var oldPageViewHeight = $('#BRpageview').height();
892 var oldPageViewWidth = $('#BRpageview').width();
894 var oldCenterY = this.centerY1up();
895 var oldCenterX = this.centerX1up();
897 if (0 != oldPageViewHeight) {
898 var scrollRatio = oldCenterY / oldPageViewHeight;
903 for (i=0; i<this.numLeafs; i++) {
904 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
905 var width = parseInt(this._getPageWidth(i)/this.reduce);
906 if (width>viewWidth) viewWidth=width;
908 $('#BRpageview').height(viewHeight);
909 $('#BRpageview').width(viewWidth);
911 var newCenterY = scrollRatio*viewHeight;
912 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
913 $('#BRcontainer').attr('scrollTop', newTop);
915 // We use clientWidth here to avoid miscalculating due to scroll bar
916 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
917 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
918 newLeft = Math.max(newLeft, 0);
919 $('#BRcontainer').attr('scrollLeft', newLeft);
920 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
922 //this.centerPageView();
925 // Not really needed until there is 1up autofit
926 this.removeSearchHilites();
927 this.updateSearchHilites();
931 //______________________________________________________________________________
932 // Returns the current offset of the viewport center in scaled document coordinates.
933 BookReader.prototype.centerX1up = function() {
935 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
936 centerX = $('#BRpageview').width();
938 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
940 centerX = Math.floor(centerX);
945 //______________________________________________________________________________
946 // Returns the current offset of the viewport center in scaled document coordinates.
947 BookReader.prototype.centerY1up = function() {
948 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
949 return Math.floor(centerY);
953 //______________________________________________________________________________
954 BookReader.prototype.centerPageView = function() {
956 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
957 var clientWidth = $('#BRcontainer').attr('clientWidth');
958 //console.log('sW='+scrollWidth+' cW='+clientWidth);
959 if (scrollWidth > clientWidth) {
960 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
965 // zoom2up(direction)
966 //______________________________________________________________________________
967 BookReader.prototype.zoom2up = function(direction) {
969 // Hard stop autoplay
970 this.stopFlipAnimations();
972 // Get new zoom state
973 var newZoom = this.twoPageNextReduce(this.reduce, direction);
974 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
977 this.twoPage.autofit = newZoom.autofit;
978 this.reduce = newZoom.reduce;
979 this.pageScale = this.reduce; // preserve current reduce
981 // Preserve view center position
982 var oldCenter = this.twoPageGetViewCenter();
984 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
985 // $$$ An improvement would be to use the low res image until the larger one is loaded.
986 if (1 == direction) {
987 for (var img in this.prefetchedImgs) {
988 delete this.prefetchedImgs[img];
992 // Prepare view with new center to minimize visual glitches
993 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
997 // quantizeReduce(reduce)
998 //______________________________________________________________________________
999 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1000 BookReader.prototype.quantizeReduce = function(reduce) {
1001 var quantized = this.reductionFactors[0];
1002 var distance = Math.abs(reduce - quantized);
1003 for (var i = 1; i < this.reductionFactors.length; i++) {
1004 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1005 if (newDistance < distance) {
1006 distance = newDistance;
1007 quantized = this.reductionFactors[i];
1014 // twoPageNextReduce()
1015 //______________________________________________________________________________
1016 // Returns the next reduction level
1017 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1019 var autofitReduce = this.twoPageGetAutofitReduce();
1021 if (0 == direction) { // autofit
1022 result.autofit = true;
1023 result.reduce = autofitReduce;
1025 } else if (1 == direction) { // zoom in
1026 var newReduce = this.reductionFactors[0];
1028 for (var i = 1; i < this.reductionFactors.length; i++) {
1029 if (this.reductionFactors[i] < reduce) {
1030 newReduce = this.reductionFactors[i];
1034 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1036 result.autofit = true;
1037 result.reduce = autofitReduce;
1039 result.autofit = false;
1040 result.reduce = newReduce;
1043 } else { // zoom out
1044 var lastIndex = this.reductionFactors.length - 1;
1045 var newReduce = this.reductionFactors[lastIndex];
1047 for (var i = lastIndex; i >= 0; i--) {
1048 if (this.reductionFactors[i] > reduce) {
1049 newReduce = this.reductionFactors[i];
1053 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1055 result.autofit = true;
1056 result.reduce = autofitReduce;
1058 result.autofit = false;
1059 result.reduce = newReduce;
1067 //______________________________________________________________________________
1068 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1069 BookReader.prototype.jumpToPage = function(pageNum) {
1071 var pageIndex = this.getPageIndex(pageNum);
1073 if ('undefined' != typeof(pageIndex)) {
1076 this.jumpToIndex(pageIndex);
1077 $('#BRcontainer').attr('scrollTop', leafTop);
1086 //______________________________________________________________________________
1087 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1089 if (2 == this.mode) {
1092 // By checking against min/max we do nothing if requested index
1094 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1095 this.flipBackToIndex(index);
1096 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1097 this.flipFwdToIndex(index);
1100 } else if (3 == this.mode){
1101 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1111 for (i=0; i<(index+1); i++) {
1112 leafWidth = this.thumbWidth;
1113 if (rightPos + (leafWidth + this.padding) > viewWidth){
1118 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1119 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1120 if (leafIndex==0) { leafTop = bottomPos; }
1121 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1122 rightPos += leafWidth + this.padding;
1125 this.firstIndex=index;
1126 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1129 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1136 for (i=0; i<index; i++) {
1137 h = parseInt(this._getPageHeight(i)/this.reduce);
1138 leafTop += h + this.padding;
1142 //console.log('pageY ' + pageY);
1143 var offset = parseInt( (pageY) / this.reduce);
1144 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1145 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1150 var offset = parseInt( (pageX) / this.reduce);
1151 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1155 //$('#BRcontainer').attr('scrollTop', leafTop);
1156 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1162 //______________________________________________________________________________
1163 BookReader.prototype.switchMode = function(mode) {
1165 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1167 if (mode == this.mode) return;
1169 if (!this.canSwitchToMode(mode)) {
1174 this.removeSearchHilites();
1177 this.switchToolbarMode(mode);
1179 // reinstate scale if moving from thumbnail view
1180 if (this.pageScale != this.reduce) this.reduce = this.pageScale;
1182 // $$$ TODO preserve center of view when switching between mode
1183 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1186 this.reduce = this.quantizeReduce(this.reduce);
1187 this.prepareOnePageView();
1188 } else if (3 == mode) {
1189 this.reduce = this.quantizeReduce(this.reduce);
1190 this.prepareThumbnailView();
1191 this.jumpToIndex(this.currentIndex());
1193 this.twoPage.autofit = false; // Take zoom level from other mode
1194 this.reduce = this.quantizeReduce(this.reduce);
1195 this.prepareTwoPageView();
1196 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1201 //prepareOnePageView()
1202 //______________________________________________________________________________
1203 BookReader.prototype.prepareOnePageView = function() {
1205 // var startLeaf = this.displayedIndices[0];
1206 var startLeaf = this.currentIndex();
1208 $('#BRcontainer').empty();
1209 $('#BRcontainer').css({
1210 overflowY: 'scroll',
1214 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1216 this.resizePageView();
1218 this.jumpToIndex(startLeaf);
1219 this.displayedIndices = [];
1221 this.drawLeafsOnePage();
1223 // Bind mouse handlers
1224 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1225 brPageView.bind('mousedown', function(e) {
1226 // $$$ check here for right-click and don't disable. Also use jQuery style
1227 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1230 // Special hack for IE7
1231 brPageView[0].onselectstart = function(e) { return false; };
1234 //prepareThumbnailView()
1235 //______________________________________________________________________________
1236 BookReader.prototype.prepareThumbnailView = function() {
1238 // var startLeaf = this.displayedIndices[0];
1239 var startLeaf = this.currentIndex();
1240 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1242 $('#BRcontainer').empty();
1243 $('#BRcontainer').css({
1244 overflowY: 'scroll',
1248 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
1250 this.resizePageView();
1252 this.displayedRows = [];
1253 this.drawLeafsThumbnail();
1255 // Bind mouse handlers
1256 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1257 brPageView.bind('mousedown', function(e) {
1258 // $$$ check here for right-click and don't disable. Also use jQuery style
1259 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1262 // Special hack for IE7
1263 brPageView[0].onselectstart = function(e) { return false; };
1266 // prepareTwoPageView()
1267 //______________________________________________________________________________
1268 // Some decisions about two page view:
1270 // Both pages will be displayed at the same height, even if they were different physical/scanned
1271 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1272 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1273 // aspect ratio to determine the height.
1275 // The two page view div is resized to keep the middle of the book in the middle of the div
1276 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1277 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1278 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1279 $('#BRcontainer').empty();
1280 $('#BRcontainer').css('overflow', 'auto');
1282 // We want to display two facing pages. We may be missing
1283 // one side of the spread because it is the first/last leaf,
1284 // foldouts, missing pages, etc
1286 //var targetLeaf = this.displayedIndices[0];
1287 var targetLeaf = this.firstIndex;
1289 if (targetLeaf < this.firstDisplayableIndex()) {
1290 targetLeaf = this.firstDisplayableIndex();
1293 if (targetLeaf > this.lastDisplayableIndex()) {
1294 targetLeaf = this.lastDisplayableIndex();
1297 //this.twoPage.currentIndexL = null;
1298 //this.twoPage.currentIndexR = null;
1299 //this.pruneUnusedImgs();
1301 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1302 this.twoPage.currentIndexL = currentSpreadIndices[0];
1303 this.twoPage.currentIndexR = currentSpreadIndices[1];
1304 this.firstIndex = this.twoPage.currentIndexL;
1306 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1308 this.pruneUnusedImgs();
1309 this.prefetch(); // Preload images or reload if scaling has changed
1311 //console.dir(this.twoPage);
1313 // Add the two page view
1314 // $$$ Can we get everything set up and then append?
1315 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1317 // $$$ calculate first then set
1318 $('#BRtwopageview').css( {
1319 height: this.twoPage.totalHeight + 'px',
1320 width: this.twoPage.totalWidth + 'px',
1321 position: 'absolute'
1324 // If there will not be scrollbars (e.g. when zooming out) we center the book
1325 // since otherwise the book will be stuck off-center
1326 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1327 centerPercentageX = 0.5;
1329 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1330 centerPercentageY = 0.5;
1333 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1335 this.twoPage.coverDiv = document.createElement('div');
1336 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1337 border: '1px solid rgb(68, 25, 17)',
1338 width: this.twoPage.bookCoverDivWidth + 'px',
1339 height: this.twoPage.bookCoverDivHeight+'px',
1340 visibility: 'visible',
1341 position: 'absolute',
1342 backgroundColor: '#663929',
1343 left: this.twoPage.bookCoverDivLeft + 'px',
1344 top: this.twoPage.bookCoverDivTop+'px',
1345 MozBorderRadiusTopleft: '7px',
1346 MozBorderRadiusTopright: '7px',
1347 MozBorderRadiusBottomright: '7px',
1348 MozBorderRadiusBottomleft: '7px'
1349 }).appendTo('#BRtwopageview');
1351 this.leafEdgeR = document.createElement('div');
1352 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1353 $(this.leafEdgeR).css({
1354 borderStyle: 'solid solid solid none',
1355 borderColor: 'rgb(51, 51, 34)',
1356 borderWidth: '1px 1px 1px 0px',
1357 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1358 width: this.twoPage.leafEdgeWidthR + 'px',
1359 height: this.twoPage.height-1 + 'px',
1361 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1362 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1363 position: 'absolute'
1364 }).appendTo('#BRtwopageview');
1366 this.leafEdgeL = document.createElement('div');
1367 this.leafEdgeL.className = 'leafEdgeL';
1368 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1369 borderStyle: 'solid none solid solid',
1370 borderColor: 'rgb(51, 51, 34)',
1371 borderWidth: '1px 0px 1px 1px',
1372 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1373 width: this.twoPage.leafEdgeWidthL + 'px',
1374 height: this.twoPage.height-1 + 'px',
1375 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1376 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1377 position: 'absolute'
1378 }).appendTo('#BRtwopageview');
1380 div = document.createElement('div');
1381 $(div).attr('id', 'BRbookspine').css({
1382 border: '1px solid rgb(68, 25, 17)',
1383 width: this.twoPage.bookSpineDivWidth+'px',
1384 height: this.twoPage.bookSpineDivHeight+'px',
1385 position: 'absolute',
1386 backgroundColor: 'rgb(68, 25, 17)',
1387 left: this.twoPage.bookSpineDivLeft+'px',
1388 top: this.twoPage.bookSpineDivTop+'px'
1389 }).appendTo('#BRtwopageview');
1391 var self = this; // for closure
1393 /* Flip areas no longer used
1394 this.twoPage.leftFlipArea = document.createElement('div');
1395 this.twoPage.leftFlipArea.className = 'BRfliparea';
1396 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1398 width: this.twoPageFlipAreaWidth() + 'px',
1399 height: this.twoPageFlipAreaHeight() + 'px',
1400 position: 'absolute',
1401 left: this.twoPageLeftFlipAreaLeft() + 'px',
1402 top: this.twoPageFlipAreaTop() + 'px',
1405 }).bind('click', function(e) {
1407 }).bind('mousedown', function(e) {
1409 }).appendTo('#BRtwopageview');
1411 this.twoPage.rightFlipArea = document.createElement('div');
1412 this.twoPage.rightFlipArea.className = 'BRfliparea';
1413 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1415 width: this.twoPageFlipAreaWidth() + 'px',
1416 height: this.twoPageFlipAreaHeight() + 'px',
1417 position: 'absolute',
1418 left: this.twoPageRightFlipAreaLeft() + 'px',
1419 top: this.twoPageFlipAreaTop() + 'px',
1422 }).bind('click', function(e) {
1424 }).bind('mousedown', function(e) {
1426 }).appendTo('#BRtwopageview');
1429 this.prepareTwoPagePopUp();
1431 this.displayedIndices = [];
1433 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1434 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1436 this.drawLeafsTwoPage();
1437 this.updateToolbarZoom(this.reduce);
1441 this.removeSearchHilites();
1442 this.updateSearchHilites();
1446 // prepareTwoPagePopUp()
1448 // This function prepares the "View Page n" popup that shows while the mouse is
1449 // over the left/right "stack of sheets" edges. It also binds the mouse
1450 // events for these divs.
1451 //______________________________________________________________________________
1452 BookReader.prototype.prepareTwoPagePopUp = function() {
1454 this.twoPagePopUp = document.createElement('div');
1455 $(this.twoPagePopUp).css({
1456 border: '1px solid black',
1458 position: 'absolute',
1459 fontFamily: 'sans-serif',
1462 backgroundColor: 'rgb(255, 255, 238)',
1464 }).appendTo('#BRcontainer');
1465 $(this.twoPagePopUp).hide();
1467 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1468 $(e.data.twoPagePopUp).show();
1471 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1472 $(e.data.twoPagePopUp).hide();
1475 $(this.leafEdgeL).bind('click', this, function(e) {
1477 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1478 e.data.jumpToIndex(jumpIndex);
1481 $(this.leafEdgeR).bind('click', this, function(e) {
1483 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1484 e.data.jumpToIndex(jumpIndex);
1487 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1489 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1490 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1492 // $$$ TODO: Make sure popup is positioned so that it is in view
1493 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1494 $(e.data.twoPagePopUp).css({
1495 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1496 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1500 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1502 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1503 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1505 // $$$ TODO: Make sure popup is positioned so that it is in view
1506 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1507 $(e.data.twoPagePopUp).css({
1508 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1509 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1514 // calculateSpreadSize()
1515 //______________________________________________________________________________
1516 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1517 // this.twoPage.currentIndexR
1518 // This function sets this.twoPage.height, twoPage.width
1520 BookReader.prototype.calculateSpreadSize = function() {
1522 var firstIndex = this.twoPage.currentIndexL;
1523 var secondIndex = this.twoPage.currentIndexR;
1524 //console.log('first page is ' + firstIndex);
1526 // Calculate page sizes and total leaf width
1528 if ( this.twoPage.autofit) {
1529 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1531 // set based on reduction factor
1532 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1535 // Both pages together
1536 this.twoPage.height = spreadSize.height;
1537 this.twoPage.width = spreadSize.width;
1540 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1541 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1544 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1545 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1546 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1550 // The width of the book cover div. The combined width of both pages, twice the width
1551 // of the book cover internal padding (2*10) and the page edges
1552 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1553 // The height of the book cover div
1554 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1557 // We calculate the total width and height for the div so that we can make the book
1559 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1560 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1561 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1562 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1563 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1564 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1566 // We want to minimize the unused space in two-up mode (maximize the amount of page
1567 // shown). We give width to the leaf edges and these widths change (though the sum
1568 // of the two remains constant) as we flip through the book. With the book
1569 // cover centered and fixed in the BRcontainer div the page images will meet
1570 // at the "gutter" which is generally offset from the center.
1571 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1572 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1574 // The left edge of the book cover moves depending on the width of the pages
1575 // $$$ change to getter
1576 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1577 // The top edge of the book cover stays a fixed distance from the top
1578 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1581 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1582 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1583 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1586 this.reduce = spreadSize.reduce; // $$$ really set this here?
1589 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1592 // We check which page is closest to a "normal" page and use that to set the height
1593 // for both pages. This means that foldouts and other odd size pages will be displayed
1594 // smaller than the nominal zoom amount.
1595 var canon5Dratio = 1.5;
1598 height: this._getPageHeight(firstIndex),
1599 width: this._getPageWidth(firstIndex)
1603 height: this._getPageHeight(secondIndex),
1604 width: this._getPageWidth(secondIndex)
1607 var firstIndexRatio = first.height / first.width;
1608 var secondIndexRatio = second.height / second.width;
1609 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1612 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1613 ratio = firstIndexRatio;
1614 //console.log('using firstIndexRatio ' + ratio);
1616 ratio = secondIndexRatio;
1617 //console.log('using secondIndexRatio ' + ratio);
1620 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1621 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1622 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1624 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1625 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1627 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1628 ideal.width -= 10; // $$$ fudge factor
1629 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1630 ideal.height -= 20; // fudge factor
1631 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1633 if (ideal.height/ratio <= ideal.width) {
1635 ideal.width = parseInt(ideal.height/ratio);
1638 ideal.height = parseInt(ideal.width*ratio);
1641 // $$$ check this logic with large spreads
1642 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1647 // getSpreadSizeFromReduce()
1648 //______________________________________________________________________________
1649 // Returns the spread size calculated from the reduction factor for the given pages
1650 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1651 var spreadSize = {};
1652 // $$$ Scale this based on reduce?
1653 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1654 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1655 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1657 // $$$ Possibly incorrect -- we should make height "dominant"
1658 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1659 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1660 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1661 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1662 spreadSize.reduce = reduce;
1667 // twoPageGetAutofitReduce()
1668 //______________________________________________________________________________
1669 // Returns the current ideal reduction factor
1670 BookReader.prototype.twoPageGetAutofitReduce = function() {
1671 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1672 return spreadSize.reduce;
1675 // twoPageSetCursor()
1676 //______________________________________________________________________________
1677 // Set the cursor for two page view
1678 BookReader.prototype.twoPageSetCursor = function() {
1679 // console.log('setting cursor');
1680 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1681 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1682 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1683 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1685 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1686 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1691 //______________________________________________________________________________
1692 // Returns the currently active index.
1693 BookReader.prototype.currentIndex = function() {
1694 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1695 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1696 return this.firstIndex; // $$$ TODO page in center of view would be better
1697 } else if (this.mode == this.constMode2up) {
1698 // Only allow indices that are actually present in book
1699 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1701 throw 'currentIndex called for unimplemented mode ' + this.mode;
1706 //______________________________________________________________________________
1707 // Flip the right page over onto the left
1708 BookReader.prototype.right = function() {
1709 if ('rl' != this.pageProgression) {
1719 //______________________________________________________________________________
1720 // Flip to the rightmost page
1721 BookReader.prototype.rightmost = function() {
1722 if ('rl' != this.pageProgression) {
1730 //______________________________________________________________________________
1731 // Flip the left page over onto the right.
1732 BookReader.prototype.left = function() {
1733 if ('rl' != this.pageProgression) {
1743 //______________________________________________________________________________
1744 // Flip to the leftmost page
1745 BookReader.prototype.leftmost = function() {
1746 if ('rl' != this.pageProgression) {
1754 //______________________________________________________________________________
1755 BookReader.prototype.next = function() {
1756 if (2 == this.mode) {
1758 this.flipFwdToIndex(null);
1760 if (this.firstIndex < this.lastDisplayableIndex()) {
1761 this.jumpToIndex(this.firstIndex+1);
1767 //______________________________________________________________________________
1768 BookReader.prototype.prev = function() {
1769 if (2 == this.mode) {
1771 this.flipBackToIndex(null);
1773 if (this.firstIndex >= 1) {
1774 this.jumpToIndex(this.firstIndex-1);
1779 BookReader.prototype.first = function() {
1780 this.jumpToIndex(this.firstDisplayableIndex());
1783 BookReader.prototype.last = function() {
1784 this.jumpToIndex(this.lastDisplayableIndex());
1787 // flipBackToIndex()
1788 //______________________________________________________________________________
1789 // to flip back one spread, pass index=null
1790 BookReader.prototype.flipBackToIndex = function(index) {
1792 if (1 == this.mode) return;
1794 var leftIndex = this.twoPage.currentIndexL;
1796 if (this.animating) return;
1798 if (null != this.leafEdgeTmp) {
1799 alert('error: leafEdgeTmp should be null!');
1803 if (null == index) {
1804 index = leftIndex-2;
1806 //if (index<0) return;
1808 var previousIndices = this.getSpreadIndices(index);
1810 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1814 this.animating = true;
1816 if ('rl' != this.pageProgression) {
1817 // Assume LTR and we are going backward
1818 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1819 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1821 // RTL and going backward
1822 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1823 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1827 // flipLeftToRight()
1828 //______________________________________________________________________________
1829 // Flips the page on the left towards the page on the right
1830 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1832 var leftLeaf = this.twoPage.currentIndexL;
1834 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1835 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1836 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1838 var currWidthL = this.getPageWidth2UP(leftLeaf);
1839 var newWidthL = this.getPageWidth2UP(newIndexL);
1840 var newWidthR = this.getPageWidth2UP(newIndexR);
1842 var top = this.twoPageTop();
1843 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1845 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1846 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1848 //animation strategy:
1849 // 0. remove search highlight, if any.
1850 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1851 // of the left leaf and where the user clicked in the leaf edge.
1852 // Note that if this function was triggered by left() and not a
1853 // mouse click, the width of leafEdgeTmp is very small (zero px).
1854 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1855 // leftLeaf to width=0.
1856 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1857 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1858 // its new full width.
1859 // 4. After step 3 is finished, do the following:
1860 // - remove leafEdgeTmp from the dom.
1861 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1862 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1863 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1864 // and width=newLeafEdgeWidthL.
1865 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1866 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1867 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1868 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1869 // - prefetch new adjacent leafs.
1870 // - set up click handlers for both new left and right leafs.
1871 // - redraw the search highlight.
1872 // - update the pagenum box and the url.
1875 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1877 this.leafEdgeTmp = document.createElement('div');
1878 $(this.leafEdgeTmp).css({
1879 borderStyle: 'solid none solid solid',
1880 borderColor: 'rgb(51, 51, 34)',
1881 borderWidth: '1px 0px 1px 1px',
1882 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1883 width: leafEdgeTmpW + 'px',
1884 height: this.twoPage.height-1 + 'px',
1885 left: leftEdgeTmpLeft + 'px',
1887 position: 'absolute',
1889 }).appendTo('#BRtwopageview');
1891 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1892 $(this.leafEdgeL).css({
1893 width: newLeafEdgeWidthL+'px',
1894 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1897 // Left gets the offset of the current left leaf from the document
1898 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1899 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1900 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1902 // We change the left leaf to right positioning
1903 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1904 $(this.prefetchedImgs[leftLeaf]).css({
1909 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1910 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1914 this.removeSearchHilites();
1916 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1917 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1919 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1920 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1922 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1923 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1924 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1926 $(self.leafEdgeR).css({
1927 // Moves the right leaf edge
1928 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1929 left: gutter+newWidthR+'px'
1932 $(self.leafEdgeL).css({
1933 // Moves and resizes the left leaf edge
1934 width: newLeafEdgeWidthL+'px',
1935 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1938 // Resizes the brown border div
1939 $(self.twoPage.coverDiv).css({
1940 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1941 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1944 $(self.leafEdgeTmp).remove();
1945 self.leafEdgeTmp = null;
1947 // $$$ TODO refactor with opposite direction flip
1949 self.twoPage.currentIndexL = newIndexL;
1950 self.twoPage.currentIndexR = newIndexR;
1951 self.twoPage.scaledWL = newWidthL;
1952 self.twoPage.scaledWR = newWidthR;
1953 self.twoPage.gutter = gutter;
1955 self.firstIndex = self.twoPage.currentIndexL;
1956 self.displayedIndices = [newIndexL, newIndexR];
1957 self.pruneUnusedImgs();
1959 self.animating = false;
1961 self.updateSearchHilites2UP();
1962 self.updatePageNumBox2UP();
1964 // self.twoPagePlaceFlipAreas(); // No longer used
1965 self.setMouseHandlers2UP();
1966 self.twoPageSetCursor();
1968 if (self.animationFinishedCallback) {
1969 self.animationFinishedCallback();
1970 self.animationFinishedCallback = null;
1978 //______________________________________________________________________________
1979 // Whether we flip left or right is dependent on the page progression
1980 // to flip forward one spread, pass index=null
1981 BookReader.prototype.flipFwdToIndex = function(index) {
1983 if (this.animating) return;
1985 if (null != this.leafEdgeTmp) {
1986 alert('error: leafEdgeTmp should be null!');
1990 if (null == index) {
1991 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1993 if (index > this.lastDisplayableIndex()) return;
1995 this.animating = true;
1997 var nextIndices = this.getSpreadIndices(index);
1999 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2001 if ('rl' != this.pageProgression) {
2002 // We did not specify RTL
2003 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2004 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2007 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2008 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2012 // flipRightToLeft(nextL, nextR, gutter)
2013 // $$$ better not to have to pass gutter in
2014 //______________________________________________________________________________
2015 // Flip from left to right and show the nextL and nextR indices on those sides
2016 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2017 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2018 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2019 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2020 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2022 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2024 var top = this.twoPageTop();
2025 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2027 var middle = this.twoPage.middle;
2028 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2030 this.leafEdgeTmp = document.createElement('div');
2031 $(this.leafEdgeTmp).css({
2032 borderStyle: 'solid none solid solid',
2033 borderColor: 'rgb(51, 51, 34)',
2034 borderWidth: '1px 0px 1px 1px',
2035 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2036 width: leafEdgeTmpW + 'px',
2037 height: this.twoPage.height-1 + 'px',
2038 left: gutter+scaledW+'px',
2040 position: 'absolute',
2042 }).appendTo('#BRtwopageview');
2044 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2045 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2047 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2048 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2049 var newWidthL = this.getPageWidth2UP(newIndexL);
2050 var newWidthR = this.getPageWidth2UP(newIndexR);
2052 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2054 var self = this; // closure-tastic!
2056 var speed = this.flipSpeed;
2058 this.removeSearchHilites();
2060 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2061 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2062 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2063 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2064 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2066 $(self.leafEdgeL).css({
2067 width: newLeafEdgeWidthL+'px',
2068 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2071 // Resizes the book cover
2072 $(self.twoPage.coverDiv).css({
2073 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2074 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2077 $(self.leafEdgeTmp).remove();
2078 self.leafEdgeTmp = null;
2080 self.twoPage.currentIndexL = newIndexL;
2081 self.twoPage.currentIndexR = newIndexR;
2082 self.twoPage.scaledWL = newWidthL;
2083 self.twoPage.scaledWR = newWidthR;
2084 self.twoPage.gutter = gutter;
2086 self.firstIndex = self.twoPage.currentIndexL;
2087 self.displayedIndices = [newIndexL, newIndexR];
2088 self.pruneUnusedImgs();
2090 self.animating = false;
2093 self.updateSearchHilites2UP();
2094 self.updatePageNumBox2UP();
2096 // self.twoPagePlaceFlipAreas(); // No longer used
2097 self.setMouseHandlers2UP();
2098 self.twoPageSetCursor();
2100 if (self.animationFinishedCallback) {
2101 self.animationFinishedCallback();
2102 self.animationFinishedCallback = null;
2108 // setMouseHandlers2UP
2109 //______________________________________________________________________________
2110 BookReader.prototype.setMouseHandlers2UP = function() {
2112 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2117 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2124 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2125 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2132 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2133 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2136 e.data.self.right();
2142 //______________________________________________________________________________
2143 BookReader.prototype.prefetchImg = function(index) {
2144 var pageURI = this._getPageURI(index);
2146 // Load image if not loaded or URI has changed (e.g. due to scaling)
2147 var loadImage = false;
2148 if (undefined == this.prefetchedImgs[index]) {
2149 //console.log('no image for ' + index);
2151 } else if (pageURI != this.prefetchedImgs[index].uri) {
2152 //console.log('uri changed for ' + index);
2157 //console.log('prefetching ' + index);
2158 var img = document.createElement("img");
2160 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2161 this.prefetchedImgs[index] = img;
2166 // prepareFlipLeftToRight()
2168 //______________________________________________________________________________
2170 // Prepare to flip the left page towards the right. This corresponds to moving
2171 // backward when the page progression is left to right.
2172 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2174 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2176 this.prefetchImg(prevL);
2177 this.prefetchImg(prevR);
2179 var height = this._getPageHeight(prevL);
2180 var width = this._getPageWidth(prevL);
2181 var middle = this.twoPage.middle;
2182 var top = this.twoPageTop();
2183 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2185 // The gutter is the dividing line between the left and right pages.
2186 // It is offset from the middle to create the illusion of thickness to the pages
2187 var gutter = middle + this.gutterOffsetForIndex(prevL);
2189 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2190 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2191 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2194 position: 'absolute',
2195 left: gutter-scaledW+'px',
2196 right: '', // clear right property
2198 height: this.twoPage.height,
2199 width: scaledW+'px',
2200 backgroundColor: this.getPageBackgroundColor(prevL),
2201 borderRight: '1px solid black',
2205 $(this.prefetchedImgs[prevL]).css(leftCSS);
2207 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2209 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2212 position: 'absolute',
2216 height: this.twoPage.height,
2218 backgroundColor: this.getPageBackgroundColor(prevR),
2219 borderLeft: '1px solid black',
2223 $(this.prefetchedImgs[prevR]).css(rightCSS);
2225 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2229 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2230 // prepareFlipRightToLeft()
2231 //______________________________________________________________________________
2232 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2234 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2237 this.prefetchImg(nextL);
2238 this.prefetchImg(nextR);
2240 var height = this._getPageHeight(nextR);
2241 var width = this._getPageWidth(nextR);
2242 var middle = this.twoPage.middle;
2243 var top = this.twoPageTop();
2244 var scaledW = this.twoPage.height*width/height;
2246 var gutter = middle + this.gutterOffsetForIndex(nextL);
2248 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2249 $(this.prefetchedImgs[nextR]).css({
2250 position: 'absolute',
2253 backgroundColor: this.getPageBackgroundColor(nextR),
2254 height: this.twoPage.height,
2255 width: scaledW+'px',
2256 borderLeft: '1px solid black',
2260 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2262 height = this._getPageHeight(nextL);
2263 width = this._getPageWidth(nextL);
2264 scaledW = this.twoPage.height*width/height;
2266 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2267 $(this.prefetchedImgs[nextL]).css({
2268 position: 'absolute',
2269 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2271 backgroundColor: this.getPageBackgroundColor(nextL),
2272 height: this.twoPage.height,
2273 width: 0+'px', // Start at 0 width, then grow to the left
2274 borderRight: '1px solid black',
2278 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2282 // getNextLeafs() -- NOT RTL AWARE
2283 //______________________________________________________________________________
2284 // BookReader.prototype.getNextLeafs = function(o) {
2285 // //TODO: we might have two left or two right leafs in a row (damaged book)
2286 // //For now, assume that leafs are contiguous.
2288 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2289 // o.L = this.twoPage.currentIndexL+2;
2290 // o.R = this.twoPage.currentIndexL+3;
2293 // getprevLeafs() -- NOT RTL AWARE
2294 //______________________________________________________________________________
2295 // BookReader.prototype.getPrevLeafs = function(o) {
2296 // //TODO: we might have two left or two right leafs in a row (damaged book)
2297 // //For now, assume that leafs are contiguous.
2299 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2300 // o.L = this.twoPage.currentIndexL-2;
2301 // o.R = this.twoPage.currentIndexL-1;
2304 // pruneUnusedImgs()
2305 //______________________________________________________________________________
2306 BookReader.prototype.pruneUnusedImgs = function() {
2307 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2308 for (var key in this.prefetchedImgs) {
2309 //console.log('key is ' + key);
2310 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2311 //console.log('removing key '+ key);
2312 $(this.prefetchedImgs[key]).remove();
2314 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2315 //console.log('deleting key '+ key);
2316 delete this.prefetchedImgs[key];
2322 //______________________________________________________________________________
2323 BookReader.prototype.prefetch = function() {
2325 // prefetch visible pages first
2326 this.prefetchImg(this.twoPage.currentIndexL);
2327 this.prefetchImg(this.twoPage.currentIndexR);
2329 var adjacentPagesToLoad = 3;
2331 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2332 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2334 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2335 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2337 // Load images spreading out from current
2338 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2339 var goingDown = lowCurrent - i;
2340 if (goingDown >= start) {
2341 this.prefetchImg(goingDown);
2343 var goingUp = highCurrent + i;
2344 if (goingUp <= end) {
2345 this.prefetchImg(goingUp);
2350 var lim = this.twoPage.currentIndexL-4;
2352 lim = Math.max(lim, 0);
2353 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2354 this.prefetchImg(i);
2357 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2358 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2359 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2360 this.prefetchImg(i);
2366 // getPageWidth2UP()
2367 //______________________________________________________________________________
2368 BookReader.prototype.getPageWidth2UP = function(index) {
2369 // We return the width based on the dominant height
2370 var height = this._getPageHeight(index);
2371 var width = this._getPageWidth(index);
2372 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2376 //______________________________________________________________________________
2377 BookReader.prototype.search = function(term) {
2378 term = term.replace(/\//g, ' '); // strip slashes
2379 this.searchTerm = term;
2380 $('#BookReaderSearchScript').remove();
2381 var script = document.createElement("script");
2382 script.setAttribute('id', 'BookReaderSearchScript');
2383 script.setAttribute("type", "text/javascript");
2384 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2385 document.getElementsByTagName('head')[0].appendChild(script);
2386 $('#BookReaderSearchBox').val(term);
2387 $('#BookReaderSearchResults').html('Searching...');
2390 // BRSearchCallback()
2391 //______________________________________________________________________________
2392 BookReader.prototype.BRSearchCallback = function(txt) {
2394 if (jQuery.browser.msie) {
2395 var dom=new ActiveXObject("Microsoft.XMLDOM");
2399 var parser = new DOMParser();
2400 var dom = parser.parseFromString(txt, "text/xml");
2403 $('#BookReaderSearchResults').empty();
2404 $('#BookReaderSearchResults').append('<ul>');
2406 for (var key in this.searchResults) {
2407 if (null != this.searchResults[key].div) {
2408 $(this.searchResults[key].div).remove();
2410 delete this.searchResults[key];
2413 var pages = dom.getElementsByTagName('PAGE');
2415 if (0 == pages.length) {
2416 // $$$ it would be nice to echo the (sanitized) search result here
2417 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2419 for (var i = 0; i < pages.length; i++){
2420 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2423 var re = new RegExp (/_(\d{4})/);
2424 var reMatch = re.exec(pages[i].getAttribute('file'));
2425 var index = parseInt(reMatch[1], 10);
2426 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2428 var children = pages[i].childNodes;
2430 for (var j=0; j<children.length; j++) {
2431 //console.log(j + ' - ' + children[j].nodeName);
2432 //console.log(children[j].firstChild.nodeValue);
2433 if ('CONTEXT' == children[j].nodeName) {
2434 context += children[j].firstChild.nodeValue;
2435 } else if ('WORD' == children[j].nodeName) {
2436 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2438 var index = this.leafNumToIndex(index);
2439 if (null != index) {
2440 //coordinates are [left, bottom, right, top, [baseline]]
2441 //we'll skip baseline for now...
2442 var coords = children[j].getAttribute('coords').split(',',4);
2443 if (4 == coords.length) {
2444 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2449 var pageName = this.getPageName(index);
2450 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2451 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2452 //TODO: remove hardcoded instance name
2453 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2456 $('#BookReaderSearchResults').append('</ul>');
2458 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2459 $('#BookReaderSearchBox').val(this.searchTerm);
2461 this.updateSearchHilites();
2464 // updateSearchHilites()
2465 //______________________________________________________________________________
2466 BookReader.prototype.updateSearchHilites = function() {
2467 if (2 == this.mode) {
2468 this.updateSearchHilites2UP();
2470 this.updateSearchHilites1UP();
2474 // showSearchHilites1UP()
2475 //______________________________________________________________________________
2476 BookReader.prototype.updateSearchHilites1UP = function() {
2478 for (var key in this.searchResults) {
2480 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2481 var result = this.searchResults[key];
2482 if(null == result.div) {
2483 result.div = document.createElement('div');
2484 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2485 //console.log('appending ' + key);
2488 width: (result.r-result.l)/this.reduce + 'px',
2489 height: (result.b-result.t)/this.reduce + 'px',
2490 left: (result.l)/this.reduce + 'px',
2491 top: (result.t)/this.reduce +'px'
2495 //console.log(key + ' not displayed');
2496 this.searchResults[key].div=null;
2502 //______________________________________________________________________________
2503 // Returns the position of the gutter (line between the page images)
2504 BookReader.prototype.twoPageGutter = function() {
2505 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2509 //______________________________________________________________________________
2510 // Returns the offset for the top of the page images
2511 BookReader.prototype.twoPageTop = function() {
2512 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2515 // twoPageCoverWidth()
2516 //______________________________________________________________________________
2517 // Returns the width of the cover div given the total page width
2518 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2519 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2522 // twoPageGetViewCenter()
2523 //______________________________________________________________________________
2524 // Returns the percentage offset into twopageview div at the center of container div
2525 // { percentageX: float, percentageY: float }
2526 BookReader.prototype.twoPageGetViewCenter = function() {
2529 var containerOffset = $('#BRcontainer').offset();
2530 var viewOffset = $('#BRtwopageview').offset();
2531 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2532 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2537 // twoPageCenterView(percentageX, percentageY)
2538 //______________________________________________________________________________
2539 // Centers the point given by percentage from left,top of twopageview
2540 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2541 if ('undefined' == typeof(percentageX)) {
2544 if ('undefined' == typeof(percentageY)) {
2548 var viewWidth = $('#BRtwopageview').width();
2549 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2550 var intoViewX = percentageX * viewWidth;
2552 var viewHeight = $('#BRtwopageview').height();
2553 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2554 var intoViewY = percentageY * viewHeight;
2556 if (viewWidth < containerClientWidth) {
2557 // Can fit width without scrollbars - center by adjusting offset
2558 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2560 // Need to scroll to center
2561 $('#BRtwopageview').css('left', 0);
2562 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2565 if (viewHeight < containerClientHeight) {
2566 // Fits with scrollbars - add offset
2567 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2569 $('#BRtwopageview').css('top', 0);
2570 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2574 // twoPageFlipAreaHeight
2575 //______________________________________________________________________________
2576 // Returns the integer height of the click-to-flip areas at the edges of the book
2577 BookReader.prototype.twoPageFlipAreaHeight = function() {
2578 return parseInt(this.twoPage.height);
2581 // twoPageFlipAreaWidth
2582 //______________________________________________________________________________
2583 // Returns the integer width of the flip areas
2584 BookReader.prototype.twoPageFlipAreaWidth = function() {
2585 var max = 100; // $$$ TODO base on view width?
2588 var width = this.twoPage.width * 0.15;
2589 return parseInt(BookReader.util.clamp(width, min, max));
2592 // twoPageFlipAreaTop
2593 //______________________________________________________________________________
2594 // Returns integer top offset for flip areas
2595 BookReader.prototype.twoPageFlipAreaTop = function() {
2596 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2599 // twoPageLeftFlipAreaLeft
2600 //______________________________________________________________________________
2601 // Left offset for left flip area
2602 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2603 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2606 // twoPageRightFlipAreaLeft
2607 //______________________________________________________________________________
2608 // Left offset for right flip area
2609 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2610 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2613 // twoPagePlaceFlipAreas
2614 //______________________________________________________________________________
2615 // Readjusts position of flip areas based on current layout
2616 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2617 // We don't set top since it shouldn't change relative to view
2618 $(this.twoPage.leftFlipArea).css({
2619 left: this.twoPageLeftFlipAreaLeft() + 'px',
2620 width: this.twoPageFlipAreaWidth() + 'px'
2622 $(this.twoPage.rightFlipArea).css({
2623 left: this.twoPageRightFlipAreaLeft() + 'px',
2624 width: this.twoPageFlipAreaWidth() + 'px'
2628 // showSearchHilites2UP()
2629 //______________________________________________________________________________
2630 BookReader.prototype.updateSearchHilites2UP = function() {
2632 for (var key in this.searchResults) {
2633 key = parseInt(key, 10);
2634 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2635 var result = this.searchResults[key];
2636 if(null == result.div) {
2637 result.div = document.createElement('div');
2638 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2639 //console.log('appending ' + key);
2642 // We calculate the reduction factor for the specific page because it can be different
2643 // for each page in the spread
2644 var height = this._getPageHeight(key);
2645 var width = this._getPageWidth(key)
2646 var reduce = this.twoPage.height/height;
2647 var scaledW = parseInt(width*reduce);
2649 var gutter = this.twoPageGutter();
2651 if ('L' == this.getPageSide(key)) {
2652 pageL = gutter-scaledW;
2656 var pageT = this.twoPageTop();
2659 width: (result.r-result.l)*reduce + 'px',
2660 height: (result.b-result.t)*reduce + 'px',
2661 left: pageL+(result.l)*reduce + 'px',
2662 top: pageT+(result.t)*reduce +'px'
2666 //console.log(key + ' not displayed');
2667 if (null != this.searchResults[key].div) {
2668 //console.log('removing ' + key);
2669 $(this.searchResults[key].div).remove();
2671 this.searchResults[key].div=null;
2676 // removeSearchHilites()
2677 //______________________________________________________________________________
2678 BookReader.prototype.removeSearchHilites = function() {
2679 for (var key in this.searchResults) {
2680 if (null != this.searchResults[key].div) {
2681 $(this.searchResults[key].div).remove();
2682 this.searchResults[key].div=null;
2688 //______________________________________________________________________________
2689 BookReader.prototype.printPage = function() {
2690 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2692 /* iframe implementation
2694 if (null != this.printPopup) { // check if already showing
2697 this.printPopup = document.createElement("div");
2698 $(this.printPopup).css({
2699 position: 'absolute',
2701 left: ($('#BRcontainer').width()-400)/2 + 'px',
2704 border: "3px double #999999",
2706 backgroundColor: "#fff"
2707 }).appendTo('#BookReader');
2710 if (this.constMode1up == this.mode) {
2711 indexToPrint = this.firstIndex;
2713 indexToPrint = this.twoPage.currentIndexL;
2716 this.indexToPrint = indexToPrint;
2718 var htmlStr = '<div style="text-align: center;">';
2719 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>';
2720 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2721 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2722 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2723 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2724 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2726 htmlStr += '</div>';
2727 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2728 htmlStr += '</div>';
2730 this.printPopup.innerHTML = htmlStr;
2732 var iframe = document.createElement('iframe');
2733 iframe.id = 'printFrame';
2734 iframe.name = 'printFrame';
2735 iframe.width = '233px'; // 8.5 x 11 aspect
2736 iframe.height = '300px';
2738 var self = this; // closure
2740 $(iframe).load(function() {
2741 var doc = BookReader.util.getIFrameDocument(this);
2742 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2745 $('#printDiv').prepend(iframe);
2749 // Get print URI from current indices and mode
2750 BookReader.prototype.getPrintURI = function() {
2752 if (this.constMode2up == this.mode) {
2753 indexToPrint = this.twoPage.currentIndexL;
2755 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2758 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2759 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2760 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2762 if (this.constMode2up == this.mode) {
2763 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2764 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2765 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2767 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2770 return '/bookreader/print.php?' + options;
2773 /* iframe implementation
2774 BookReader.prototype.getPrintFrameContent = function(index) {
2775 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2776 // 8.5x11 so we should end up not overflowing on either paper size.
2777 var paperAspect = 8.5 / 11;
2778 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2782 // Rotate if possible and appropriate, to get larger image size on printed page
2783 if (this.canRotatePage(index)) {
2784 if (imageAspect > 1 && imageAspect > paperAspect) {
2785 // more wide than square, and more wide than paper
2787 imageAspect = 1/imageAspect;
2792 if (imageAspect > paperAspect) {
2793 // wider than paper, fit width
2794 fitAttrs = 'width="95%"';
2796 // taller than paper, fit height
2797 fitAttrs = 'height="95%"';
2800 var imageURL = this._getPageURI(index, 1, rotate);
2801 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2802 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2803 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2804 iframeStr += '</div>';
2805 iframeStr += '</body></html>';
2810 BookReader.prototype.updatePrintFrame = function(delta) {
2811 var newIndex = this.indexToPrint + delta;
2812 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2813 if (newIndex == this.indexToPrint) {
2816 this.indexToPrint = newIndex;
2817 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2818 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2823 //______________________________________________________________________________
2824 BookReader.prototype.showEmbedCode = function() {
2825 if (null != this.embedPopup) { // check if already showing
2829 this.embedPopup = document.createElement("div");
2830 $(this.embedPopup).css({
2831 position: 'absolute',
2833 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2836 border: "3px double #999999",
2838 backgroundColor: "#fff"
2839 }).appendTo('#BookReader');
2841 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2842 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>';
2843 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2844 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2846 this.embedPopup.innerHTML = htmlStr;
2847 $(this.embedPopup).find('input').bind('click', function() {
2853 //______________________________________________________________________________
2854 BookReader.prototype.autoToggle = function() {
2856 var bComingFrom1up = false;
2857 if (2 != this.mode) {
2858 bComingFrom1up = true;
2862 // Change to autofit if book is too large
2863 if (this.reduce < this.twoPageGetAutofitReduce()) {
2868 if (null == this.autoTimer) {
2869 this.flipSpeed = 2000;
2871 // $$$ Draw events currently cause layout problems when they occur during animation.
2872 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2873 // we workaround for now by not triggering immediate animation in that case.
2874 // See https://bugs.launchpad.net/gnubook/+bug/328327
2875 if (('rl' == this.pageProgression) && bComingFrom1up) {
2876 // don't flip immediately -- wait until timer fires
2879 this.flipFwdToIndex();
2882 $('#BRtoolbar .play').hide();
2883 $('#BRtoolbar .pause').show();
2884 this.autoTimer=setInterval(function(){
2885 if (self.animating) {return;}
2887 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2888 self.flipBackToIndex(1); // $$$ really what we want?
2890 self.flipFwdToIndex();
2899 //______________________________________________________________________________
2900 // Stop autoplay mode, allowing animations to finish
2901 BookReader.prototype.autoStop = function() {
2902 if (null != this.autoTimer) {
2903 clearInterval(this.autoTimer);
2904 this.flipSpeed = 'fast';
2905 $('#BRtoolbar .pause').hide();
2906 $('#BRtoolbar .play').show();
2907 this.autoTimer = null;
2911 // stopFlipAnimations
2912 //______________________________________________________________________________
2913 // Immediately stop flip animations. Callbacks are triggered.
2914 BookReader.prototype.stopFlipAnimations = function() {
2916 this.autoStop(); // Clear timers
2918 // Stop animation, clear queue, trigger callbacks
2919 if (this.leafEdgeTmp) {
2920 $(this.leafEdgeTmp).stop(false, true);
2922 jQuery.each(this.prefetchedImgs, function() {
2923 $(this).stop(false, true);
2926 // And again since animations also queued in callbacks
2927 if (this.leafEdgeTmp) {
2928 $(this.leafEdgeTmp).stop(false, true);
2930 jQuery.each(this.prefetchedImgs, function() {
2931 $(this).stop(false, true);
2936 // keyboardNavigationIsDisabled(event)
2937 // - returns true if keyboard navigation should be disabled for the event
2938 //______________________________________________________________________________
2939 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2940 if (event.target.tagName == "INPUT") {
2946 // gutterOffsetForIndex
2947 //______________________________________________________________________________
2949 // Returns the gutter offset for the spread containing the given index.
2950 // This function supports RTL
2951 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2953 // To find the offset of the gutter from the middle we calculate our percentage distance
2954 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2955 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2957 // But then again for RTL it's the opposite
2958 if ('rl' == this.pageProgression) {
2966 //______________________________________________________________________________
2967 // Returns the width of the leaf edge div for the page with index given
2968 BookReader.prototype.leafEdgeWidth = function(pindex) {
2969 // $$$ could there be single pixel rounding errors for L vs R?
2970 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2971 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2973 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2977 // jumpIndexForLeftEdgePageX
2978 //______________________________________________________________________________
2979 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2980 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2981 if ('rl' != this.pageProgression) {
2982 // LTR - flipping backward
2983 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2985 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2986 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2990 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2991 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2996 // jumpIndexForRightEdgePageX
2997 //______________________________________________________________________________
2998 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2999 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3000 if ('rl' != this.pageProgression) {
3002 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3003 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3006 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3007 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3012 BookReader.prototype.initToolbar = function(mode, ui) {
3014 $("#BookReader").append("<div id='BRtoolbar'>"
3015 + "<span id='BRtoolbarbuttons' style='float: right'>"
3016 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3017 + "<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>"
3018 + "<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>"
3019 + "<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>"
3020 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3024 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3025 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3026 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3027 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3028 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3029 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3030 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3033 + "<span id='#BRbooktitle'>"
3034 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3038 this.updateToolbarZoom(this.reduce); // Pretty format
3040 if (ui == "embed") {
3041 $("#BookReader a.logo").attr("target","_blank");
3044 // $$$ turn this into a member variable
3045 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3047 // We build in mode 2
3050 this.bindToolbarNavHandlers(jToolbar);
3052 // Setup tooltips -- later we could load these from a file for i18n
3053 var titles = { '.logo': 'Go to Archive.org',
3054 '.zoom_in': 'Zoom in',
3055 '.zoom_out': 'Zoom out',
3056 '.one_page_mode': 'One-page view',
3057 '.two_page_mode': 'Two-page view',
3058 '.thumbnail_mode': 'Thumbnail view',
3059 '.print': 'Print this page',
3060 '.embed': 'Embed bookreader',
3061 '.book_left': 'Flip left',
3062 '.book_right': 'Flip right',
3063 '.book_up': 'Page up',
3064 '.book_down': 'Page down',
3067 '.book_top': 'First page',
3068 '.book_bottom': 'Last page'
3070 if ('rl' == this.pageProgression) {
3071 titles['.book_leftmost'] = 'Last page';
3072 titles['.book_rightmost'] = 'First page';
3074 titles['.book_leftmost'] = 'First page';
3075 titles['.book_rightmost'] = 'Last page';
3078 for (var icon in titles) {
3079 jToolbar.find(icon).attr('title', titles[icon]);
3082 // Hide mode buttons and autoplay if 2up is not available
3083 // $$$ if we end up with more than two modes we should show the applicable buttons
3084 if ( !this.canSwitchToMode(this.constMode2up) ) {
3085 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3088 // Switch to requested mode -- binds other click handlers
3089 this.switchToolbarMode(mode);
3094 // switchToolbarMode
3095 //______________________________________________________________________________
3096 // Update the toolbar for the given mode (changes navigation buttons)
3097 // $$$ we should soon split the toolbar out into its own module
3098 BookReader.prototype.switchToolbarMode = function(mode) {
3101 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3102 $('#BRtoolbar .BRtoolbarmode2').hide();
3103 $('#BRtoolbar .BRtoolbarmode3').hide();
3104 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3105 } else if (2 == mode) {
3107 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3108 $('#BRtoolbar .BRtoolbarmode1').hide();
3109 $('#BRtoolbar .BRtoolbarmode3').hide();
3110 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3113 $('#BRtoolbar .BRtoolbarzoom').hide();
3114 $('#BRtoolbar .BRtoolbarmode2').hide();
3115 $('#BRtoolbar .BRtoolbarmode1').hide();
3116 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3120 // bindToolbarNavHandlers
3121 //______________________________________________________________________________
3122 // Binds the toolbar handlers
3123 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3125 var self = this; // closure
3127 jToolbar.find('.book_left').bind('click', function(e) {
3132 jToolbar.find('.book_right').bind('click', function(e) {
3137 jToolbar.find('.book_up').bind('click', function(e) {
3142 jToolbar.find('.book_down').bind('click', function(e) {
3147 jToolbar.find('.print').bind('click', function(e) {
3152 jToolbar.find('.embed').bind('click', function(e) {
3153 self.showEmbedCode();
3157 jToolbar.find('.play').bind('click', function(e) {
3162 jToolbar.find('.pause').bind('click', function(e) {
3167 jToolbar.find('.book_top').bind('click', function(e) {
3172 jToolbar.find('.book_bottom').bind('click', function(e) {
3177 jToolbar.find('.book_leftmost').bind('click', function(e) {
3182 jToolbar.find('.book_rightmost').bind('click', function(e) {
3188 // updateToolbarZoom(reduce)
3189 //______________________________________________________________________________
3190 // Update the displayed zoom factor based on reduction factor
3191 BookReader.prototype.updateToolbarZoom = function(reduce) {
3193 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3196 value = (100 / reduce).toFixed(2);
3197 // Strip trailing zeroes and decimal if all zeroes
3198 value = value.replace(/0+$/,'');
3199 value = value.replace(/\.$/,'');
3202 $('#BRzoom').text(value);
3205 // firstDisplayableIndex
3206 //______________________________________________________________________________
3207 // Returns the index of the first visible page, dependent on the mode.
3208 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3209 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3210 BookReader.prototype.firstDisplayableIndex = function() {
3211 if (this.mode != this.constMode2up) {
3215 if ('rl' != this.pageProgression) {
3217 if (this.getPageSide(0) == 'L') {
3224 if (this.getPageSide(0) == 'R') {
3232 // lastDisplayableIndex
3233 //______________________________________________________________________________
3234 // Returns the index of the last visible page, dependent on the mode.
3235 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3236 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3237 BookReader.prototype.lastDisplayableIndex = function() {
3239 var lastIndex = this.numLeafs - 1;
3241 if (this.mode != this.constMode2up) {
3245 if ('rl' != this.pageProgression) {
3247 if (this.getPageSide(lastIndex) == 'R') {
3250 return lastIndex + 1;
3254 if (this.getPageSide(lastIndex) == 'L') {
3257 return lastIndex + 1;
3262 // shortTitle(maximumCharacters)
3264 // Returns a shortened version of the title with the maximum number of characters
3265 BookReader.prototype.shortTitle = function(maximumCharacters) {
3266 if (this.bookTitle.length < maximumCharacters) {
3267 return this.bookTitle;
3270 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3275 // Parameter related functions
3277 // updateFromParams(params)
3279 // Update ourselves from the params object.
3281 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3282 BookReader.prototype.updateFromParams = function(params) {
3283 if ('undefined' != typeof(params.mode)) {
3284 this.switchMode(params.mode);
3288 if ('undefined' != typeof(params.searchTerm)) {
3289 if (this.searchTerm != params.searchTerm) {
3290 this.search(params.searchTerm);
3294 // $$$ process /zoom
3296 // We only respect page if index is not set
3297 if ('undefined' != typeof(params.index)) {
3298 if (params.index != this.currentIndex()) {
3299 this.jumpToIndex(params.index);
3301 } else if ('undefined' != typeof(params.page)) {
3302 // $$$ this assumes page numbers are unique
3303 if (params.page != this.getPageNum(this.currentIndex())) {
3304 this.jumpToPage(params.page);
3308 // $$$ process /region
3309 // $$$ process /highlight
3312 // paramsFromFragment(urlFragment)
3314 // Returns a object with configuration parametes from a URL fragment.
3316 // E.g paramsFromFragment(window.location.hash)
3317 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3318 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3322 // For convenience we allow an initial # character (as from window.location.hash)
3323 // but don't require it
3324 if (urlFragment.substr(0,1) == '#') {
3325 urlFragment = urlFragment.substr(1);
3328 // Simple #nn syntax
3329 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3330 if ( !isNaN(oldStyleLeafNum) ) {
3331 params.index = oldStyleLeafNum;
3333 // Done processing if using old-style syntax
3337 // Split into key-value pairs
3338 var urlArray = urlFragment.split('/');
3340 for (var i = 0; i < urlArray.length; i += 2) {
3341 urlHash[urlArray[i]] = urlArray[i+1];
3345 if ('1up' == urlHash['mode']) {
3346 params.mode = this.constMode1up;
3347 } else if ('2up' == urlHash['mode']) {
3348 params.mode = this.constMode2up;
3349 } else if ('thumb' == urlHash['mode']) {
3350 params.mode = this.constModeThumb;
3354 if ('undefined' != typeof(urlHash['page'])) {
3355 // page was set -- may not be int
3356 params.page = urlHash['page'];
3359 // $$$ process /region
3360 // $$$ process /search
3362 if (urlHash['search'] != undefined) {
3363 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3366 // $$$ process /highlight
3371 // paramsFromCurrent()
3373 // Create a params object from the current parameters.
3374 BookReader.prototype.paramsFromCurrent = function() {
3378 var index = this.currentIndex();
3379 var pageNum = this.getPageNum(index);
3380 if ((pageNum === 0) || pageNum) {
3381 params.page = pageNum;
3384 params.index = index;
3385 params.mode = this.mode;
3391 if (this.searchHighlightVisible()) {
3392 params.searchTerm = this.searchTerm;
3398 // fragmentFromParams(params)
3400 // Create a fragment string from the params object.
3401 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3402 BookReader.prototype.fragmentFromParams = function(params) {
3403 var separator = '/';
3407 if ('undefined' != typeof(params.page)) {
3408 fragments.push('page', params.page);
3410 // Don't have page numbering -- use index instead
3411 fragments.push('page', 'n' + params.index);
3418 if ('undefined' != typeof(params.mode)) {
3419 if (params.mode == this.constMode1up) {
3420 fragments.push('mode', '1up');
3421 } else if (params.mode == this.constMode2up) {
3422 fragments.push('mode', '2up');
3423 } else if (params.mode == this.constModeThumb) {
3424 fragments.push('mode', 'thumb');
3426 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3431 if (params.searchTerm) {
3432 fragments.push('search', params.searchTerm);
3435 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3438 // getPageIndex(pageNum)
3440 // Returns the *highest* index the given page number, or undefined
3441 BookReader.prototype.getPageIndex = function(pageNum) {
3442 var pageIndices = this.getPageIndices(pageNum);
3444 if (pageIndices.length > 0) {
3445 return pageIndices[pageIndices.length - 1];
3451 // getPageIndices(pageNum)
3453 // Returns an array (possibly empty) of the indices with the given page number
3454 BookReader.prototype.getPageIndices = function(pageNum) {
3457 // Check for special "nXX" page number
3458 if (pageNum.slice(0,1) == 'n') {
3460 var pageIntStr = pageNum.slice(1, pageNum.length);
3461 var pageIndex = parseInt(pageIntStr);
3462 indices.push(pageIndex);
3465 // Do nothing... will run through page names and see if one matches
3470 for (i=0; i<this.numLeafs; i++) {
3471 if (this.getPageNum(i) == pageNum) {
3479 // getPageName(index)
3481 // Returns the name of the page as it should be displayed in the user interface
3482 BookReader.prototype.getPageName = function(index) {
3483 return 'Page ' + this.getPageNum(index);
3486 // updateLocationHash
3488 // Update the location hash from the current parameters. Call this instead of manually
3489 // using window.location.replace
3490 BookReader.prototype.updateLocationHash = function() {
3491 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3492 window.location.replace(newHash);
3494 // This is the variable checked in the timer. Only user-generated changes
3495 // to the URL will trigger the event.
3496 this.oldLocationHash = newHash;
3499 // startLocationPolling
3501 // Starts polling of window.location to see hash fragment changes
3502 BookReader.prototype.startLocationPolling = function() {
3503 var self = this; // remember who I am
3504 self.oldLocationHash = window.location.hash;
3506 if (this.locationPollId) {
3507 clearInterval(this.locationPollID);
3508 this.locationPollId = null;
3511 this.locationPollId = setInterval(function() {
3512 var newHash = window.location.hash;
3513 if (newHash != self.oldLocationHash) {
3514 if (newHash != self.oldUserHash) { // Only process new user hash once
3515 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3517 // Queue change if animating
3518 if (self.animating) {
3520 self.animationFinishedCallback = function() {
3521 self.updateFromParams(self.paramsFromFragment(newHash));
3523 } else { // update immediately
3524 self.updateFromParams(self.paramsFromFragment(newHash));
3526 self.oldUserHash = newHash;
3534 // Returns true if we can switch to the requested mode
3535 BookReader.prototype.canSwitchToMode = function(mode) {
3536 if (mode == this.constMode2up) {
3537 // check there are enough pages to display
3538 // $$$ this is a workaround for the mis-feature that we can't display
3539 // short books in 2up mode
3540 if (this.numLeafs < 6) {
3548 // searchHighlightVisible
3550 // Returns true if a search highlight is currently being displayed
3551 BookReader.prototype.searchHighlightVisible = function() {
3552 if (this.constMode2up == this.mode) {
3553 if (this.searchResults[this.twoPage.currentIndexL]
3554 || this.searchResults[this.twoPage.currentIndexR]) {
3558 if (this.searchResults[this.currentIndex()]) {
3565 // getPageBackgroundColor
3567 // Returns a CSS property string for the background color for the given page
3568 // $$$ turn into regular CSS?
3569 BookReader.prototype.getPageBackgroundColor = function(index) {
3570 if (index >= 0 && index < this.numLeafs) {
3572 return this.pageDefaultBackgroundColor;
3580 // Returns the page width for the given index, or first or last page if out of range
3581 BookReader.prototype._getPageWidth = function(index) {
3582 // Synthesize a page width for pages not actually present in book.
3583 // May or may not be the best approach.
3584 // If index is out of range we return the width of first or last page
3585 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3586 return this.getPageWidth(index);
3591 // Returns the page height for the given index, or first or last page if out of range
3592 BookReader.prototype._getPageHeight= function(index) {
3593 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3594 return this.getPageHeight(index);
3599 // Returns the page URI or transparent image if out of range
3600 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3601 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3602 return this.imagesBaseURL + "/transparent.png";
3605 if ('undefined' == typeof(reduce)) {
3606 // reduce not passed in
3607 var ratio = this.getPageHeight(index) / this.twoPage.height;
3609 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3612 } else if (ratio < 4) {
3614 } else if (ratio < 8) {
3616 } else if (ratio < 16) {
3618 } else if (ratio < 32) {
3626 return this.getPageURI(index, reduce, rotate);
3629 // Library functions
3631 clamp: function(value, min, max) {
3632 return Math.min(Math.max(value, min), max);
3635 getIFrameDocument: function(iframe) {
3636 // Adapted from http://xkr.us/articles/dom/iframe-document/
3637 var outer = (iframe.contentWindow || iframe.contentDocument);
3638 return (outer.document || outer);
3641 decodeURIComponentPlus: function(value) {
3642 // Decodes a URI component and converts '+' to ' '
3643 return decodeURIComponent(value).replace(/\+/g, ' ');
3646 encodeURIComponentPlus: function(value) {
3647 // Encodes a URI component and converts ' ' to '+'
3648 return encodeURIComponent(value).replace(/%20/g, '+');
3650 // The final property here must NOT have a comma after it - IE7