2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
6 BookReader is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 BookReader is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
45 this.thumbWidth = 100; // will be overridden during prepareThumbnailView
46 this.thumbRowBuffer = 3; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.displayedRows=[];
50 this.displayedIndices = [];
51 //this.indicesToDisplay = [];
53 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
56 this.animating = false;
58 this.autoTimer = null;
59 this.flipSpeed = 'fast';
61 this.twoPagePopUp = null;
62 this.leafEdgeTmp = null;
63 this.embedPopup = null;
64 this.printPopup = null;
67 this.searchResults = {};
69 this.firstIndex = null;
71 this.lastDisplayableIndex2up = null;
73 // We link to index.php to avoid redirect which breaks back button
74 this.logoURL = 'http://www.archive.org/index.php';
76 // Base URL for images
77 this.imagesBaseURL = '/bookreader/images/';
80 this.constMode1up = 1;
81 this.constMode2up = 2;
82 this.constModeThumb = 3;
85 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
87 // Object to hold parameters related to 2up mode
89 coverInternalPadding: 10, // Width of cover
90 coverExternalPadding: 10, // Padding outside of cover
91 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
95 // Background color for pages (e.g. when loading page image)
96 // $$$ TODO dynamically calculate based on page images
97 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
101 //______________________________________________________________________________
102 BookReader.prototype.init = function() {
104 var startIndex = undefined;
105 this.pageScale = this.reduce; // preserve current reduce
107 // Find start index and mode if set in location hash
108 var params = this.paramsFromFragment(window.location.hash);
110 if ('undefined' != typeof(params.index)) {
111 startIndex = params.index;
112 } else if ('undefined' != typeof(params.page)) {
113 startIndex = this.getPageIndex(params.page);
116 if ('undefined' == typeof(startIndex)) {
117 if ('undefined' != typeof(this.titleLeaf)) {
118 startIndex = this.leafNumToIndex(this.titleLeaf);
122 if ('undefined' == typeof(startIndex)) {
126 if ('undefined' != typeof(params.mode)) {
127 this.mode = params.mode;
130 // Set document title -- may have already been set in enclosing html for
131 // search engine visibility
132 document.title = this.shortTitle(50);
134 // Sanitize parameters
135 if ( !this.canSwitchToMode( this.mode ) ) {
136 this.mode = this.constMode1up;
139 $("#BookReader").empty();
140 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
141 $("#BookReader").append("<div id='BRcontainer'></div>");
142 $("#BRcontainer").append("<div id='BRpageview'></div>");
144 $("#BRcontainer").bind('scroll', this, function(e) {
148 this.setupKeyListeners();
149 this.startLocationPolling();
151 $(window).bind('resize', this, function(e) {
152 //console.log('resize!');
153 if (1 == e.data.mode) {
154 //console.log('centering 1page view');
155 e.data.centerPageView();
156 $('#BRpageview').empty()
157 e.data.displayedIndices = [];
158 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
160 } else if (3 == e.data.mode){
161 e.data.prepareThumbnailView();
163 //console.log('drawing 2 page view');
165 // We only need to prepare again in autofit (size of spread changes)
166 if (e.data.twoPage.autofit) {
167 e.data.prepareTwoPageView();
169 // Re-center if the scrollbars have disappeared
170 var center = e.data.twoPageGetViewCenter();
171 var doRecenter = false;
172 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
173 center.percentageX = 0.5;
176 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
177 center.percentageY = 0.5;
181 e.data.twoPageCenterView(center.percentageX, center.percentageY);
187 $('.BRpagediv1up').bind('mousedown', this, function(e) {
188 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
189 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
193 if (1 == this.mode) {
194 this.resizePageView();
195 this.firstIndex = startIndex;
196 this.jumpToIndex(startIndex);
197 } else if (3 == this.mode) {
198 this.firstIndex = startIndex;
199 this.prepareThumbnailView();
200 this.jumpToIndex(startIndex);
202 //this.resizePageView();
204 this.displayedIndices=[0];
205 this.firstIndex = startIndex;
206 this.displayedIndices = [this.firstIndex];
207 //console.log('titleLeaf: %d', this.titleLeaf);
208 //console.log('displayedIndices: %s', this.displayedIndices);
209 this.prepareTwoPageView();
212 // Enact other parts of initial params
213 this.updateFromParams(params);
216 BookReader.prototype.setupKeyListeners = function() {
229 // We use document here instead of window to avoid a bug in jQuery on IE7
230 $(document).keydown(function(e) {
232 // Keyboard navigation
233 if (!self.keyboardNavigationIsDisabled(e)) {
237 // In 1up mode page scrolling is handled by browser
238 if (2 == self.mode) {
245 if (2 == self.mode) {
259 if (2 == self.mode) {
265 if (2 == self.mode) {
276 //______________________________________________________________________________
277 BookReader.prototype.drawLeafs = function() {
278 if (1 == this.mode) {
279 this.drawLeafsOnePage();
280 } else if(3 == this.mode) {
281 this.drawLeafsThumbnail();
283 this.drawLeafsTwoPage();
288 //______________________________________________________________________________
289 BookReader.prototype.setDragHandler = function(div) {
290 div.dragging = false;
292 $(div).unbind('mousedown').bind('mousedown', function(e) {
295 //console.log('mousedown at ' + e.pageY);
297 this.dragging = true;
298 this.prevMouseX = e.pageX;
299 this.prevMouseY = e.pageY;
301 var startX = e.pageX;
302 var startY = e.pageY;
303 var startTop = $('#BRcontainer').attr('scrollTop');
304 var startLeft = $('#BRcontainer').attr('scrollLeft');
308 $(div).unbind('mousemove').bind('mousemove', function(ee) {
311 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
313 var offsetX = ee.pageX - this.prevMouseX;
314 var offsetY = ee.pageY - this.prevMouseY;
317 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
318 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
321 this.prevMouseX = ee.pageX;
322 this.prevMouseY = ee.pageY;
326 $(div).unbind('mouseup').bind('mouseup', function(ee) {
328 //console.log('mouseup');
330 this.dragging = false;
333 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
335 //console.log('mouseleave');
337 this.dragging = false;
340 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
342 //console.log('mouseenter');
344 this.dragging = false;
348 // setDragHandler2UP()
349 //______________________________________________________________________________
350 BookReader.prototype.setDragHandler2UP = function(div) {
351 div.dragging = false;
353 $(div).unbind('mousedown').bind('mousedown', function(e) {
356 //console.log('mousedown at ' + e.pageY);
358 this.dragStart = {x: e.pageX, y: e.pageY };
359 this.mouseDown = true;
360 this.dragging = false; // wait until drag distance
361 this.prevMouseX = e.pageX;
362 this.prevMouseY = e.pageY;
364 var startX = e.pageX;
365 var startY = e.pageY;
366 var startTop = $('#BRcontainer').attr('scrollTop');
367 var startLeft = $('#BRcontainer').attr('scrollLeft');
371 $(div).unbind('mousemove').bind('mousemove', function(ee) {
374 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
376 var offsetX = ee.pageX - this.prevMouseX;
377 var offsetY = ee.pageY - this.prevMouseY;
379 var minDragDistance = 5; // $$$ constant
381 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
383 if (this.mouseDown && (distance > minDragDistance)) {
384 //console.log('drag start!');
386 this.dragging = true;
390 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
391 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
392 this.prevMouseX = ee.pageX;
393 this.prevMouseY = ee.pageY;
400 $(div).unbind('mouseup').bind('mouseup', function(ee) {
402 //console.log('mouseup');
404 this.dragging = false;
405 this.mouseDown = false;
410 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
412 //console.log('mouseleave');
414 this.dragging = false;
415 this.mouseDown = false;
418 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
420 //console.log('mouseenter');
422 this.dragging = false;
423 this.mouseDown = false;
427 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
428 //console.log('setting handler');
429 //console.log(element.tagName);
431 $(element).unbind('click').bind('click', data, function(e) {
434 //console.log('click!');
436 if (this.mouseDown && (!this.dragging)) {
437 //console.log('click not dragging!');
441 this.dragging = false;
442 this.mouseDown = false;
446 // drawLeafsOnePage()
447 //______________________________________________________________________________
448 BookReader.prototype.drawLeafsOnePage = function() {
449 //alert('drawing leafs!');
453 var scrollTop = $('#BRcontainer').attr('scrollTop');
454 var scrollBottom = scrollTop + $('#BRcontainer').height();
455 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
457 var indicesToDisplay = [];
462 for (i=0; i<this.numLeafs; i++) {
463 var height = parseInt(this._getPageHeight(i)/this.reduce);
465 leafBottom += height;
466 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
467 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
468 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
469 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
470 if (topInView | bottomInView | middleInView) {
471 //console.log('displayed: ' + this.displayedIndices);
472 //console.log('to display: ' + i);
473 indicesToDisplay.push(i);
475 leafTop += height +10;
479 var firstIndexToDraw = indicesToDisplay[0];
480 this.firstIndex = firstIndexToDraw;
482 // Update hash, but only if we're currently displaying a leaf
483 // Hack that fixes #365790
484 if (this.displayedIndices.length > 0) {
485 this.updateLocationHash();
488 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
490 indicesToDisplay.unshift(firstIndexToDraw);
493 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
494 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
495 indicesToDisplay.push(lastIndexToDraw+1);
500 for (i=0; i<firstIndexToDraw; i++) {
501 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
504 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
505 var viewWidth = $('#BRcontainer').attr('scrollWidth');
508 for (i=0; i<indicesToDisplay.length; i++) {
509 var index = indicesToDisplay[i];
510 var height = parseInt(this._getPageHeight(index)/this.reduce);
512 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
513 var width = parseInt(this._getPageWidth(index)/this.reduce);
514 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
515 var div = document.createElement("div");
516 div.className = 'BRpagediv1up';
517 div.id = 'pagediv'+index;
518 div.style.position = "absolute";
519 $(div).css('top', leafTop + 'px');
520 var left = (viewWidth-width)>>1;
521 if (left<0) left = 0;
522 $(div).css('left', left+'px');
523 $(div).css('width', width+'px');
524 $(div).css('height', height+'px');
525 //$(div).text('loading...');
527 this.setDragHandler(div);
529 $('#BRpageview').append(div);
531 var img = document.createElement("img");
532 img.src = this._getPageURI(index, this.reduce, 0);
533 $(img).css('width', width+'px');
534 $(img).css('height', height+'px');
538 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
541 leafTop += height +10;
545 for (i=0; i<this.displayedIndices.length; i++) {
546 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
547 var index = this.displayedIndices[i];
548 //console.log('Removing leaf ' + index);
549 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
550 $('#pagediv'+index).remove();
552 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
556 this.displayedIndices = indicesToDisplay.slice();
557 this.updateSearchHilites();
559 if (null != this.getPageNum(firstIndexToDraw)) {
560 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
562 $("#BRpagenum").val('');
565 this.updateToolbarZoom(this.reduce);
569 // drawLeafsThumbnail()
570 //______________________________________________________________________________
571 BookReader.prototype.drawLeafsThumbnail = function() {
572 //alert('drawing leafs!');
575 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
577 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
589 for (i=0; i<this.numLeafs; i++) {
590 leafWidth = this.thumbWidth;
591 if (rightPos + (leafWidth + this.padding) > viewWidth){
597 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
598 if (leafMap[currentRow].leafs===undefined) {
599 leafMap[currentRow].leafs = [];
600 leafMap[currentRow].height = 0;
601 leafMap[currentRow].top = 0;
603 leafMap[currentRow].leafs[leafIndex] = {};
604 leafMap[currentRow].leafs[leafIndex].num = i;
605 leafMap[currentRow].leafs[leafIndex].left = rightPos;
607 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
608 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
609 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
610 rightPos += leafWidth + this.padding;
611 if (rightPos > maxRight) { maxRight = rightPos; }
615 // reset the bottom position based on thumbnails
616 $('#BRpageview').height(bottomPos);
618 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
619 var scrollTop = $('#BRcontainer').attr('scrollTop');
620 var scrollBottom = scrollTop + $('#BRcontainer').height();
624 var rowsToDisplay = [];
626 for (i=0; i<leafMap.length; i++) {
627 leafBottom += this.padding + leafMap[i].height;
628 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
629 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
630 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
631 if (topInView | bottomInView | middleInView) {
632 //console.log('row to display: ' + j);
633 rowsToDisplay.push(i);
635 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
636 leafTop = leafBottom;
639 // create a buffer of preloaded rows before and after the visible rows
640 var firstRow = rowsToDisplay[0];
641 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
642 for (i=1; i<this.thumbRowBuffer+1; i++) {
643 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
645 for (i=1; i<this.thumbRowBuffer+1; i++) {
646 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
649 // Update hash, but only if we're currently displaying a leaf
650 // Hack that fixes #365790
651 if (this.displayedRows.length > 0) {
652 this.updateLocationHash();
663 for (i=0; i<rowsToDisplay.length; i++) {
664 if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {
665 row = rowsToDisplay[i];
667 for (j=0; j<leafMap[row].leafs.length; j++) {
669 leaf = leafMap[row].leafs[j].num;
671 leafWidth = this.thumbWidth;
672 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
673 leafTop = leafMap[row].top;
674 left = leafMap[row].leafs[index].left + pageViewBuffer;
675 if ('rl' == this.pageProgression){
676 left = viewWidth - leafWidth - left;
679 div = document.createElement("div");
680 div.id = 'pagediv'+leaf;
681 div.style.position = "absolute";
682 div.className = "BRpagedivthumb";
684 left += this.padding;
685 $(div).css('top', leafTop + 'px');
686 $(div).css('left', left+'px');
687 $(div).css('width', leafWidth+'px');
688 $(div).css('height', leafHeight+'px');
689 //$(div).text('loading...');
691 // link to page in single page mode
692 // $$$ direct JS calls instead should reduce visual disruption
693 link = document.createElement("a");
694 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
697 $('#BRpageview').append(div);
699 img = document.createElement("img");
700 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
701 img.src = this._getPageURI(leaf, thumbReduce);
702 $(img).css('width', leafWidth+'px');
703 $(img).css('height', leafHeight+'px');
704 img.style.border = "0";
706 //console.log('displaying thumbnail: ' + leafMap[j]);
711 // remove previous highlights
712 if ($('.BRpagedivthumb_highlight').length>0) {
713 div = $('.BRpagedivthumb_highlight')
714 div.attr({className: 'BRpagedivthumb' });
716 // highlight current page
717 $('#pagediv'+this.currentIndex()).attr({className: 'BRpagedivthumb_highlight' });
720 for (i=0; i<this.displayedRows.length; i++) {
721 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
722 row = this.displayedRows[i];
723 for (k=0; k<leafMap[row].leafs.length; k++) {
724 index = leafMap[row].leafs[k].num;
725 //console.log('Removing leaf ' + index);
726 $('#pagediv'+index).remove();
730 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
734 this.displayedRows = rowsToDisplay.slice();
736 if (null !== this.getPageNum(this.currentIndex())) {
737 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
739 $("#BRpagenum").val('');
742 this.updateToolbarZoom(this.reduce);
745 // drawLeafsTwoPage()
746 //______________________________________________________________________________
747 BookReader.prototype.drawLeafsTwoPage = function() {
748 var scrollTop = $('#BRtwopageview').attr('scrollTop');
749 var scrollBottom = scrollTop + $('#BRtwopageview').height();
751 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
753 var indexL = this.twoPage.currentIndexL;
755 var heightL = this._getPageHeight(indexL);
756 var widthL = this._getPageWidth(indexL);
758 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
759 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
760 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
761 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
762 //console.log(leafEdgeWidthL);
764 var middle = this.twoPage.middle; // $$$ getter instead?
765 var top = this.twoPageTop();
766 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
768 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
769 this.twoPage.gutter = this.twoPageGutter();
771 this.prefetchImg(indexL);
772 $(this.prefetchedImgs[indexL]).css({
773 position: 'absolute',
774 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
777 backgroundColor: this.getPageBackgroundColor(indexL),
778 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
779 width: this.twoPage.scaledWL + 'px',
780 borderRight: '1px solid black',
782 }).appendTo('#BRtwopageview');
784 var indexR = this.twoPage.currentIndexR;
785 var heightR = this._getPageHeight(indexR);
786 var widthR = this._getPageWidth(indexR);
788 // $$$ should use getwidth2up?
789 //var scaledWR = this.twoPage.height*widthR/heightR;
790 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
791 this.prefetchImg(indexR);
792 $(this.prefetchedImgs[indexR]).css({
793 position: 'absolute',
794 left: this.twoPage.gutter+'px',
797 backgroundColor: this.getPageBackgroundColor(indexR),
798 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
799 width: this.twoPage.scaledWR + 'px',
800 borderLeft: '1px solid black',
802 }).appendTo('#BRtwopageview');
805 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
806 this.setMouseHandlers2UP();
807 this.twoPageSetCursor();
809 this.updatePageNumBox2UP();
810 this.updateToolbarZoom(this.reduce);
812 // this.twoPagePlaceFlipAreas(); // No longer used
816 // updatePageNumBox2UP
817 //______________________________________________________________________________
818 BookReader.prototype.updatePageNumBox2UP = function() {
819 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
820 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
822 $("#BRpagenum").val('');
824 this.updateLocationHash();
828 //______________________________________________________________________________
829 BookReader.prototype.loadLeafs = function() {
833 if (null == this.timer) {
834 this.timer=setTimeout(function(){self.drawLeafs()},250);
836 clearTimeout(this.timer);
837 this.timer=setTimeout(function(){self.drawLeafs()},250);
843 // Pass 1 to zoom in, anything else to zoom out
844 //______________________________________________________________________________
845 BookReader.prototype.zoom = function(direction) {
847 case this.constMode1up:
848 return this.zoom1up(direction);
849 case this.constMode2up:
850 return this.zoom2up(direction);
851 case this.constModeThumb:
852 return this.zoomThumb(direction);
857 //______________________________________________________________________________
858 BookReader.prototype.zoom1up = function(dir) {
860 if (2 == this.mode) { //can only zoom in 1-page mode
865 // $$$ with flexible zoom we could "snap" to /2 page reductions
866 // for better scaling
868 if (this.reduce <= 0.5) return;
869 this.reduce*=0.5; //zoom in
871 if (this.reduce >= 8) return;
872 this.reduce*=2; //zoom out
875 this.pageScale = this.reduce; // preserve current reduce
876 this.resizePageView();
878 $('#BRpageview').empty()
879 this.displayedIndices = [];
882 this.updateToolbarZoom(this.reduce);
884 // Recalculate search hilites
885 this.removeSearchHilites();
886 this.updateSearchHilites();
891 //______________________________________________________________________________
892 BookReader.prototype.resizePageView = function() {
895 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
896 var viewWidth = $('#BRcontainer').attr('clientWidth');
898 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
899 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
900 var oldPageViewHeight = $('#BRpageview').height();
901 var oldPageViewWidth = $('#BRpageview').width();
903 var oldCenterY = this.centerY1up();
904 var oldCenterX = this.centerX1up();
906 if (0 != oldPageViewHeight) {
907 var scrollRatio = oldCenterY / oldPageViewHeight;
912 for (i=0; i<this.numLeafs; i++) {
913 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
914 var width = parseInt(this._getPageWidth(i)/this.reduce);
915 if (width>viewWidth) viewWidth=width;
917 $('#BRpageview').height(viewHeight);
918 $('#BRpageview').width(viewWidth);
920 var newCenterY = scrollRatio*viewHeight;
921 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
922 $('#BRcontainer').attr('scrollTop', newTop);
924 // We use clientWidth here to avoid miscalculating due to scroll bar
925 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
926 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
927 newLeft = Math.max(newLeft, 0);
928 $('#BRcontainer').attr('scrollLeft', newLeft);
929 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
931 //this.centerPageView();
934 // Not really needed until there is 1up autofit
935 this.removeSearchHilites();
936 this.updateSearchHilites();
940 //______________________________________________________________________________
941 // Returns the current offset of the viewport center in scaled document coordinates.
942 BookReader.prototype.centerX1up = function() {
944 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
945 centerX = $('#BRpageview').width();
947 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
949 centerX = Math.floor(centerX);
954 //______________________________________________________________________________
955 // Returns the current offset of the viewport center in scaled document coordinates.
956 BookReader.prototype.centerY1up = function() {
957 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
958 return Math.floor(centerY);
962 //______________________________________________________________________________
963 BookReader.prototype.centerPageView = function() {
965 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
966 var clientWidth = $('#BRcontainer').attr('clientWidth');
967 //console.log('sW='+scrollWidth+' cW='+clientWidth);
968 if (scrollWidth > clientWidth) {
969 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
974 // zoom2up(direction)
975 //______________________________________________________________________________
976 BookReader.prototype.zoom2up = function(direction) {
978 // Hard stop autoplay
979 this.stopFlipAnimations();
981 // Get new zoom state
982 var newZoom = this.twoPageNextReduce(this.reduce, direction);
983 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
986 this.twoPage.autofit = newZoom.autofit;
987 this.reduce = newZoom.reduce;
988 this.pageScale = this.reduce; // preserve current reduce
990 // Preserve view center position
991 var oldCenter = this.twoPageGetViewCenter();
993 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
994 // $$$ An improvement would be to use the low res image until the larger one is loaded.
995 if (1 == direction) {
996 for (var img in this.prefetchedImgs) {
997 delete this.prefetchedImgs[img];
1001 // Prepare view with new center to minimize visual glitches
1002 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1005 BookReader.prototype.zoomThumb = function(direction) {
1006 var oldColumns = this.thumbColumns;
1007 switch (direction) {
1009 this.thumbColumns += 1;
1012 this.thumbColumns -= 1;
1017 if (this.thumbColumns < 2) {
1018 this.thumbColumns = 2;
1019 } else if (this.thumbColumns > 8) {
1020 this.thumbColumns = 8;
1023 if (this.thumbColumns != oldColumns) {
1024 this.prepareThumbnailView();
1025 this.jumpToIndex(this.currentIndex());
1029 // Returns the width per thumbnail to display the requested number of columns
1030 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1031 var padding = (thumbnailColumns + 1) * this.padding;
1032 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1033 return parseInt(width);
1036 // quantizeReduce(reduce)
1037 //______________________________________________________________________________
1038 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1039 BookReader.prototype.quantizeReduce = function(reduce) {
1040 var quantized = this.reductionFactors[0];
1041 var distance = Math.abs(reduce - quantized);
1042 for (var i = 1; i < this.reductionFactors.length; i++) {
1043 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1044 if (newDistance < distance) {
1045 distance = newDistance;
1046 quantized = this.reductionFactors[i];
1053 // twoPageNextReduce()
1054 //______________________________________________________________________________
1055 // Returns the next reduction level
1056 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1058 var autofitReduce = this.twoPageGetAutofitReduce();
1060 if (0 == direction) { // autofit
1061 result.autofit = true;
1062 result.reduce = autofitReduce;
1064 } else if (1 == direction) { // zoom in
1065 var newReduce = this.reductionFactors[0];
1067 for (var i = 1; i < this.reductionFactors.length; i++) {
1068 if (this.reductionFactors[i] < reduce) {
1069 newReduce = this.reductionFactors[i];
1073 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1075 result.autofit = true;
1076 result.reduce = autofitReduce;
1078 result.autofit = false;
1079 result.reduce = newReduce;
1082 } else { // zoom out
1083 var lastIndex = this.reductionFactors.length - 1;
1084 var newReduce = this.reductionFactors[lastIndex];
1086 for (var i = lastIndex; i >= 0; i--) {
1087 if (this.reductionFactors[i] > reduce) {
1088 newReduce = this.reductionFactors[i];
1092 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1094 result.autofit = true;
1095 result.reduce = autofitReduce;
1097 result.autofit = false;
1098 result.reduce = newReduce;
1106 //______________________________________________________________________________
1107 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1108 BookReader.prototype.jumpToPage = function(pageNum) {
1110 var pageIndex = this.getPageIndex(pageNum);
1112 if ('undefined' != typeof(pageIndex)) {
1115 this.jumpToIndex(pageIndex);
1116 $('#BRcontainer').attr('scrollTop', leafTop);
1125 //______________________________________________________________________________
1126 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1128 if (2 == this.mode) {
1131 // By checking against min/max we do nothing if requested index
1133 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1134 this.flipBackToIndex(index);
1135 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1136 this.flipFwdToIndex(index);
1139 } else if (3 == this.mode) {
1140 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1150 for (i=0; i<(index+1); i++) {
1151 leafWidth = this.thumbWidth;
1152 if (rightPos + (leafWidth + this.padding) > viewWidth){
1157 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1158 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1159 if (leafIndex==0) { leafTop = bottomPos; }
1160 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1161 rightPos += leafWidth + this.padding;
1164 this.firstIndex=index;
1165 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1168 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1175 for (i=0; i<index; i++) {
1176 h = parseInt(this._getPageHeight(i)/this.reduce);
1177 leafTop += h + this.padding;
1181 //console.log('pageY ' + pageY);
1182 var offset = parseInt( (pageY) / this.reduce);
1183 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1184 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1189 var offset = parseInt( (pageX) / this.reduce);
1190 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1194 //$('#BRcontainer').attr('scrollTop', leafTop);
1195 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1201 //______________________________________________________________________________
1202 BookReader.prototype.switchMode = function(mode) {
1204 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1206 if (mode == this.mode) {
1210 if (!this.canSwitchToMode(mode)) {
1215 this.removeSearchHilites();
1218 this.switchToolbarMode(mode);
1220 // reinstate scale if moving from thumbnail view
1221 if (this.pageScale != this.reduce) {
1222 this.reduce = this.pageScale;
1225 // $$$ TODO preserve center of view when switching between mode
1226 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1229 this.reduce = this.quantizeReduce(this.reduce);
1230 this.prepareOnePageView();
1231 } else if (3 == mode) {
1232 this.reduce = this.quantizeReduce(this.reduce);
1233 this.prepareThumbnailView();
1234 this.jumpToIndex(this.currentIndex());
1236 // $$$ why don't we save autofit?
1237 this.twoPage.autofit = false; // Take zoom level from other mode
1238 this.reduce = this.quantizeReduce(this.reduce);
1239 this.prepareTwoPageView();
1240 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1245 //prepareOnePageView()
1246 //______________________________________________________________________________
1247 BookReader.prototype.prepareOnePageView = function() {
1249 // var startLeaf = this.displayedIndices[0];
1250 var startLeaf = this.currentIndex();
1252 $('#BRcontainer').empty();
1253 $('#BRcontainer').css({
1254 overflowY: 'scroll',
1258 $("#BRcontainer").append("<div id='BRpageview'></div>");
1259 BookReader.util.disableSelect($('#BRpageview'));
1261 this.resizePageView();
1263 this.jumpToIndex(startLeaf);
1264 this.displayedIndices = [];
1266 this.drawLeafsOnePage();
1269 //prepareThumbnailView()
1270 //______________________________________________________________________________
1271 BookReader.prototype.prepareThumbnailView = function() {
1273 // var startLeaf = this.displayedIndices[0];
1274 var startLeaf = this.currentIndex();
1275 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1276 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1278 $('#BRcontainer').empty();
1279 $('#BRcontainer').css({
1280 overflowY: 'scroll',
1284 $("#BRcontainer").append("<div id='BRpageview'></div>");
1285 BookReader.util.disableSelect($('#BRpageview'));
1287 this.resizePageView();
1289 this.displayedRows = [];
1290 this.drawLeafsThumbnail();
1293 // prepareTwoPageView()
1294 //______________________________________________________________________________
1295 // Some decisions about two page view:
1297 // Both pages will be displayed at the same height, even if they were different physical/scanned
1298 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1299 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1300 // aspect ratio to determine the height.
1302 // The two page view div is resized to keep the middle of the book in the middle of the div
1303 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1304 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1305 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1306 $('#BRcontainer').empty();
1307 $('#BRcontainer').css('overflow', 'auto');
1309 // We want to display two facing pages. We may be missing
1310 // one side of the spread because it is the first/last leaf,
1311 // foldouts, missing pages, etc
1313 //var targetLeaf = this.displayedIndices[0];
1314 var targetLeaf = this.firstIndex;
1316 if (targetLeaf < this.firstDisplayableIndex()) {
1317 targetLeaf = this.firstDisplayableIndex();
1320 if (targetLeaf > this.lastDisplayableIndex()) {
1321 targetLeaf = this.lastDisplayableIndex();
1324 //this.twoPage.currentIndexL = null;
1325 //this.twoPage.currentIndexR = null;
1326 //this.pruneUnusedImgs();
1328 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1329 this.twoPage.currentIndexL = currentSpreadIndices[0];
1330 this.twoPage.currentIndexR = currentSpreadIndices[1];
1331 this.firstIndex = this.twoPage.currentIndexL;
1333 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1335 this.pruneUnusedImgs();
1336 this.prefetch(); // Preload images or reload if scaling has changed
1338 //console.dir(this.twoPage);
1340 // Add the two page view
1341 // $$$ Can we get everything set up and then append?
1342 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1344 // $$$ calculate first then set
1345 $('#BRtwopageview').css( {
1346 height: this.twoPage.totalHeight + 'px',
1347 width: this.twoPage.totalWidth + 'px',
1348 position: 'absolute'
1351 // If there will not be scrollbars (e.g. when zooming out) we center the book
1352 // since otherwise the book will be stuck off-center
1353 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1354 centerPercentageX = 0.5;
1356 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1357 centerPercentageY = 0.5;
1360 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1362 this.twoPage.coverDiv = document.createElement('div');
1363 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1364 border: '1px solid rgb(68, 25, 17)',
1365 width: this.twoPage.bookCoverDivWidth + 'px',
1366 height: this.twoPage.bookCoverDivHeight+'px',
1367 visibility: 'visible',
1368 position: 'absolute',
1369 backgroundColor: '#663929',
1370 left: this.twoPage.bookCoverDivLeft + 'px',
1371 top: this.twoPage.bookCoverDivTop+'px',
1372 MozBorderRadiusTopleft: '7px',
1373 MozBorderRadiusTopright: '7px',
1374 MozBorderRadiusBottomright: '7px',
1375 MozBorderRadiusBottomleft: '7px'
1376 }).appendTo('#BRtwopageview');
1378 this.leafEdgeR = document.createElement('div');
1379 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1380 $(this.leafEdgeR).css({
1381 borderStyle: 'solid solid solid none',
1382 borderColor: 'rgb(51, 51, 34)',
1383 borderWidth: '1px 1px 1px 0px',
1384 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1385 width: this.twoPage.leafEdgeWidthR + 'px',
1386 height: this.twoPage.height-1 + 'px',
1388 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1389 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1390 position: 'absolute'
1391 }).appendTo('#BRtwopageview');
1393 this.leafEdgeL = document.createElement('div');
1394 this.leafEdgeL.className = 'leafEdgeL';
1395 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1396 borderStyle: 'solid none solid solid',
1397 borderColor: 'rgb(51, 51, 34)',
1398 borderWidth: '1px 0px 1px 1px',
1399 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1400 width: this.twoPage.leafEdgeWidthL + 'px',
1401 height: this.twoPage.height-1 + 'px',
1402 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1403 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1404 position: 'absolute'
1405 }).appendTo('#BRtwopageview');
1407 div = document.createElement('div');
1408 $(div).attr('id', 'BRbookspine').css({
1409 border: '1px solid rgb(68, 25, 17)',
1410 width: this.twoPage.bookSpineDivWidth+'px',
1411 height: this.twoPage.bookSpineDivHeight+'px',
1412 position: 'absolute',
1413 backgroundColor: 'rgb(68, 25, 17)',
1414 left: this.twoPage.bookSpineDivLeft+'px',
1415 top: this.twoPage.bookSpineDivTop+'px'
1416 }).appendTo('#BRtwopageview');
1418 var self = this; // for closure
1420 /* Flip areas no longer used
1421 this.twoPage.leftFlipArea = document.createElement('div');
1422 this.twoPage.leftFlipArea.className = 'BRfliparea';
1423 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1425 width: this.twoPageFlipAreaWidth() + 'px',
1426 height: this.twoPageFlipAreaHeight() + 'px',
1427 position: 'absolute',
1428 left: this.twoPageLeftFlipAreaLeft() + 'px',
1429 top: this.twoPageFlipAreaTop() + 'px',
1432 }).bind('click', function(e) {
1434 }).bind('mousedown', function(e) {
1436 }).appendTo('#BRtwopageview');
1438 this.twoPage.rightFlipArea = document.createElement('div');
1439 this.twoPage.rightFlipArea.className = 'BRfliparea';
1440 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1442 width: this.twoPageFlipAreaWidth() + 'px',
1443 height: this.twoPageFlipAreaHeight() + 'px',
1444 position: 'absolute',
1445 left: this.twoPageRightFlipAreaLeft() + 'px',
1446 top: this.twoPageFlipAreaTop() + 'px',
1449 }).bind('click', function(e) {
1451 }).bind('mousedown', function(e) {
1453 }).appendTo('#BRtwopageview');
1456 this.prepareTwoPagePopUp();
1458 this.displayedIndices = [];
1460 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1461 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1463 this.drawLeafsTwoPage();
1464 this.updateToolbarZoom(this.reduce);
1468 this.removeSearchHilites();
1469 this.updateSearchHilites();
1473 // prepareTwoPagePopUp()
1475 // This function prepares the "View Page n" popup that shows while the mouse is
1476 // over the left/right "stack of sheets" edges. It also binds the mouse
1477 // events for these divs.
1478 //______________________________________________________________________________
1479 BookReader.prototype.prepareTwoPagePopUp = function() {
1481 this.twoPagePopUp = document.createElement('div');
1482 $(this.twoPagePopUp).css({
1483 border: '1px solid black',
1485 position: 'absolute',
1486 fontFamily: 'sans-serif',
1489 backgroundColor: 'rgb(255, 255, 238)',
1491 }).appendTo('#BRcontainer');
1492 $(this.twoPagePopUp).hide();
1494 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1495 $(e.data.twoPagePopUp).show();
1498 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1499 $(e.data.twoPagePopUp).hide();
1502 $(this.leafEdgeL).bind('click', this, function(e) {
1504 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1505 e.data.jumpToIndex(jumpIndex);
1508 $(this.leafEdgeR).bind('click', this, function(e) {
1510 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1511 e.data.jumpToIndex(jumpIndex);
1514 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1516 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1517 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1519 // $$$ TODO: Make sure popup is positioned so that it is in view
1520 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1521 $(e.data.twoPagePopUp).css({
1522 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1523 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1527 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1529 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1530 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1532 // $$$ TODO: Make sure popup is positioned so that it is in view
1533 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1534 $(e.data.twoPagePopUp).css({
1535 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1536 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1541 // calculateSpreadSize()
1542 //______________________________________________________________________________
1543 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1544 // this.twoPage.currentIndexR
1545 // This function sets this.twoPage.height, twoPage.width
1547 BookReader.prototype.calculateSpreadSize = function() {
1549 var firstIndex = this.twoPage.currentIndexL;
1550 var secondIndex = this.twoPage.currentIndexR;
1551 //console.log('first page is ' + firstIndex);
1553 // Calculate page sizes and total leaf width
1555 if ( this.twoPage.autofit) {
1556 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1558 // set based on reduction factor
1559 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1562 // Both pages together
1563 this.twoPage.height = spreadSize.height;
1564 this.twoPage.width = spreadSize.width;
1567 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1568 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1571 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1572 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1573 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1577 // The width of the book cover div. The combined width of both pages, twice the width
1578 // of the book cover internal padding (2*10) and the page edges
1579 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1580 // The height of the book cover div
1581 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1584 // We calculate the total width and height for the div so that we can make the book
1586 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1587 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1588 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1589 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1590 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1591 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1593 // We want to minimize the unused space in two-up mode (maximize the amount of page
1594 // shown). We give width to the leaf edges and these widths change (though the sum
1595 // of the two remains constant) as we flip through the book. With the book
1596 // cover centered and fixed in the BRcontainer div the page images will meet
1597 // at the "gutter" which is generally offset from the center.
1598 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1599 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1601 // The left edge of the book cover moves depending on the width of the pages
1602 // $$$ change to getter
1603 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1604 // The top edge of the book cover stays a fixed distance from the top
1605 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1608 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1609 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1610 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1613 this.reduce = spreadSize.reduce; // $$$ really set this here?
1616 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1619 // We check which page is closest to a "normal" page and use that to set the height
1620 // for both pages. This means that foldouts and other odd size pages will be displayed
1621 // smaller than the nominal zoom amount.
1622 var canon5Dratio = 1.5;
1625 height: this._getPageHeight(firstIndex),
1626 width: this._getPageWidth(firstIndex)
1630 height: this._getPageHeight(secondIndex),
1631 width: this._getPageWidth(secondIndex)
1634 var firstIndexRatio = first.height / first.width;
1635 var secondIndexRatio = second.height / second.width;
1636 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1639 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1640 ratio = firstIndexRatio;
1641 //console.log('using firstIndexRatio ' + ratio);
1643 ratio = secondIndexRatio;
1644 //console.log('using secondIndexRatio ' + ratio);
1647 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1648 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1649 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1651 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1652 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1654 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1655 ideal.width -= 10; // $$$ fudge factor
1656 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1657 ideal.height -= 20; // fudge factor
1658 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1660 if (ideal.height/ratio <= ideal.width) {
1662 ideal.width = parseInt(ideal.height/ratio);
1665 ideal.height = parseInt(ideal.width*ratio);
1668 // $$$ check this logic with large spreads
1669 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1674 // getSpreadSizeFromReduce()
1675 //______________________________________________________________________________
1676 // Returns the spread size calculated from the reduction factor for the given pages
1677 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1678 var spreadSize = {};
1679 // $$$ Scale this based on reduce?
1680 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1681 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1682 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1684 // $$$ Possibly incorrect -- we should make height "dominant"
1685 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1686 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1687 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1688 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1689 spreadSize.reduce = reduce;
1694 // twoPageGetAutofitReduce()
1695 //______________________________________________________________________________
1696 // Returns the current ideal reduction factor
1697 BookReader.prototype.twoPageGetAutofitReduce = function() {
1698 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1699 return spreadSize.reduce;
1702 // twoPageSetCursor()
1703 //______________________________________________________________________________
1704 // Set the cursor for two page view
1705 BookReader.prototype.twoPageSetCursor = function() {
1706 // console.log('setting cursor');
1707 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1708 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1709 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1710 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1712 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1713 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1718 //______________________________________________________________________________
1719 // Returns the currently active index.
1720 BookReader.prototype.currentIndex = function() {
1721 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1722 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1723 return this.firstIndex; // $$$ TODO page in center of view would be better
1724 } else if (this.mode == this.constMode2up) {
1725 // Only allow indices that are actually present in book
1726 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1728 throw 'currentIndex called for unimplemented mode ' + this.mode;
1733 //______________________________________________________________________________
1734 // Flip the right page over onto the left
1735 BookReader.prototype.right = function() {
1736 if ('rl' != this.pageProgression) {
1746 //______________________________________________________________________________
1747 // Flip to the rightmost page
1748 BookReader.prototype.rightmost = function() {
1749 if ('rl' != this.pageProgression) {
1757 //______________________________________________________________________________
1758 // Flip the left page over onto the right.
1759 BookReader.prototype.left = function() {
1760 if ('rl' != this.pageProgression) {
1770 //______________________________________________________________________________
1771 // Flip to the leftmost page
1772 BookReader.prototype.leftmost = function() {
1773 if ('rl' != this.pageProgression) {
1781 //______________________________________________________________________________
1782 BookReader.prototype.next = function() {
1783 if (2 == this.mode) {
1785 this.flipFwdToIndex(null);
1787 if (this.firstIndex < this.lastDisplayableIndex()) {
1788 this.jumpToIndex(this.firstIndex+1);
1794 //______________________________________________________________________________
1795 BookReader.prototype.prev = function() {
1796 if (2 == this.mode) {
1798 this.flipBackToIndex(null);
1800 if (this.firstIndex >= 1) {
1801 this.jumpToIndex(this.firstIndex-1);
1806 BookReader.prototype.first = function() {
1807 this.jumpToIndex(this.firstDisplayableIndex());
1810 BookReader.prototype.last = function() {
1811 this.jumpToIndex(this.lastDisplayableIndex());
1815 //______________________________________________________________________________
1816 // Scrolls down one screen view
1817 BookReader.prototype.scrollDown = function() {
1818 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1819 $('#BRcontainer').animate(
1820 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1821 450, 'easeInOutQuint'
1830 //______________________________________________________________________________
1831 // Scrolls up one screen view
1832 BookReader.prototype.scrollUp = function() {
1833 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1834 $('#BRcontainer').animate(
1835 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1836 450, 'easeInOutQuint'
1845 // flipBackToIndex()
1846 //______________________________________________________________________________
1847 // to flip back one spread, pass index=null
1848 BookReader.prototype.flipBackToIndex = function(index) {
1850 if (1 == this.mode) return;
1852 var leftIndex = this.twoPage.currentIndexL;
1854 if (this.animating) return;
1856 if (null != this.leafEdgeTmp) {
1857 alert('error: leafEdgeTmp should be null!');
1861 if (null == index) {
1862 index = leftIndex-2;
1864 //if (index<0) return;
1866 var previousIndices = this.getSpreadIndices(index);
1868 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1872 this.animating = true;
1874 if ('rl' != this.pageProgression) {
1875 // Assume LTR and we are going backward
1876 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1877 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1879 // RTL and going backward
1880 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1881 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1885 // flipLeftToRight()
1886 //______________________________________________________________________________
1887 // Flips the page on the left towards the page on the right
1888 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1890 var leftLeaf = this.twoPage.currentIndexL;
1892 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1893 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1894 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1896 var currWidthL = this.getPageWidth2UP(leftLeaf);
1897 var newWidthL = this.getPageWidth2UP(newIndexL);
1898 var newWidthR = this.getPageWidth2UP(newIndexR);
1900 var top = this.twoPageTop();
1901 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1903 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1904 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1906 //animation strategy:
1907 // 0. remove search highlight, if any.
1908 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1909 // of the left leaf and where the user clicked in the leaf edge.
1910 // Note that if this function was triggered by left() and not a
1911 // mouse click, the width of leafEdgeTmp is very small (zero px).
1912 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1913 // leftLeaf to width=0.
1914 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1915 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1916 // its new full width.
1917 // 4. After step 3 is finished, do the following:
1918 // - remove leafEdgeTmp from the dom.
1919 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1920 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1921 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1922 // and width=newLeafEdgeWidthL.
1923 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1924 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1925 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1926 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1927 // - prefetch new adjacent leafs.
1928 // - set up click handlers for both new left and right leafs.
1929 // - redraw the search highlight.
1930 // - update the pagenum box and the url.
1933 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1935 this.leafEdgeTmp = document.createElement('div');
1936 $(this.leafEdgeTmp).css({
1937 borderStyle: 'solid none solid solid',
1938 borderColor: 'rgb(51, 51, 34)',
1939 borderWidth: '1px 0px 1px 1px',
1940 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1941 width: leafEdgeTmpW + 'px',
1942 height: this.twoPage.height-1 + 'px',
1943 left: leftEdgeTmpLeft + 'px',
1945 position: 'absolute',
1947 }).appendTo('#BRtwopageview');
1949 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1950 $(this.leafEdgeL).css({
1951 width: newLeafEdgeWidthL+'px',
1952 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1955 // Left gets the offset of the current left leaf from the document
1956 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1957 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1958 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1960 // We change the left leaf to right positioning
1961 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1962 $(this.prefetchedImgs[leftLeaf]).css({
1967 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1968 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1972 this.removeSearchHilites();
1974 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1975 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1977 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1978 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1980 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1981 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1982 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1984 $(self.leafEdgeR).css({
1985 // Moves the right leaf edge
1986 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1987 left: gutter+newWidthR+'px'
1990 $(self.leafEdgeL).css({
1991 // Moves and resizes the left leaf edge
1992 width: newLeafEdgeWidthL+'px',
1993 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1996 // Resizes the brown border div
1997 $(self.twoPage.coverDiv).css({
1998 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1999 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2002 $(self.leafEdgeTmp).remove();
2003 self.leafEdgeTmp = null;
2005 // $$$ TODO refactor with opposite direction flip
2007 self.twoPage.currentIndexL = newIndexL;
2008 self.twoPage.currentIndexR = newIndexR;
2009 self.twoPage.scaledWL = newWidthL;
2010 self.twoPage.scaledWR = newWidthR;
2011 self.twoPage.gutter = gutter;
2013 self.firstIndex = self.twoPage.currentIndexL;
2014 self.displayedIndices = [newIndexL, newIndexR];
2015 self.pruneUnusedImgs();
2017 self.animating = false;
2019 self.updateSearchHilites2UP();
2020 self.updatePageNumBox2UP();
2022 // self.twoPagePlaceFlipAreas(); // No longer used
2023 self.setMouseHandlers2UP();
2024 self.twoPageSetCursor();
2026 if (self.animationFinishedCallback) {
2027 self.animationFinishedCallback();
2028 self.animationFinishedCallback = null;
2036 //______________________________________________________________________________
2037 // Whether we flip left or right is dependent on the page progression
2038 // to flip forward one spread, pass index=null
2039 BookReader.prototype.flipFwdToIndex = function(index) {
2041 if (this.animating) return;
2043 if (null != this.leafEdgeTmp) {
2044 alert('error: leafEdgeTmp should be null!');
2048 if (null == index) {
2049 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2051 if (index > this.lastDisplayableIndex()) return;
2053 this.animating = true;
2055 var nextIndices = this.getSpreadIndices(index);
2057 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2059 if ('rl' != this.pageProgression) {
2060 // We did not specify RTL
2061 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2062 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2065 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2066 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2070 // flipRightToLeft(nextL, nextR, gutter)
2071 // $$$ better not to have to pass gutter in
2072 //______________________________________________________________________________
2073 // Flip from left to right and show the nextL and nextR indices on those sides
2074 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2075 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2076 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2077 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2078 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2080 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2082 var top = this.twoPageTop();
2083 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2085 var middle = this.twoPage.middle;
2086 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2088 this.leafEdgeTmp = document.createElement('div');
2089 $(this.leafEdgeTmp).css({
2090 borderStyle: 'solid none solid solid',
2091 borderColor: 'rgb(51, 51, 34)',
2092 borderWidth: '1px 0px 1px 1px',
2093 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2094 width: leafEdgeTmpW + 'px',
2095 height: this.twoPage.height-1 + 'px',
2096 left: gutter+scaledW+'px',
2098 position: 'absolute',
2100 }).appendTo('#BRtwopageview');
2102 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2103 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2105 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2106 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2107 var newWidthL = this.getPageWidth2UP(newIndexL);
2108 var newWidthR = this.getPageWidth2UP(newIndexR);
2110 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2112 var self = this; // closure-tastic!
2114 var speed = this.flipSpeed;
2116 this.removeSearchHilites();
2118 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2119 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2120 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2121 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2122 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2124 $(self.leafEdgeL).css({
2125 width: newLeafEdgeWidthL+'px',
2126 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2129 // Resizes the book cover
2130 $(self.twoPage.coverDiv).css({
2131 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2132 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2135 $(self.leafEdgeTmp).remove();
2136 self.leafEdgeTmp = null;
2138 self.twoPage.currentIndexL = newIndexL;
2139 self.twoPage.currentIndexR = newIndexR;
2140 self.twoPage.scaledWL = newWidthL;
2141 self.twoPage.scaledWR = newWidthR;
2142 self.twoPage.gutter = gutter;
2144 self.firstIndex = self.twoPage.currentIndexL;
2145 self.displayedIndices = [newIndexL, newIndexR];
2146 self.pruneUnusedImgs();
2148 self.animating = false;
2151 self.updateSearchHilites2UP();
2152 self.updatePageNumBox2UP();
2154 // self.twoPagePlaceFlipAreas(); // No longer used
2155 self.setMouseHandlers2UP();
2156 self.twoPageSetCursor();
2158 if (self.animationFinishedCallback) {
2159 self.animationFinishedCallback();
2160 self.animationFinishedCallback = null;
2166 // setMouseHandlers2UP
2167 //______________________________________________________________________________
2168 BookReader.prototype.setMouseHandlers2UP = function() {
2170 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2175 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2182 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2183 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2190 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2191 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2194 e.data.self.right();
2200 //______________________________________________________________________________
2201 BookReader.prototype.prefetchImg = function(index) {
2202 var pageURI = this._getPageURI(index);
2204 // Load image if not loaded or URI has changed (e.g. due to scaling)
2205 var loadImage = false;
2206 if (undefined == this.prefetchedImgs[index]) {
2207 //console.log('no image for ' + index);
2209 } else if (pageURI != this.prefetchedImgs[index].uri) {
2210 //console.log('uri changed for ' + index);
2215 //console.log('prefetching ' + index);
2216 var img = document.createElement("img");
2218 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2219 this.prefetchedImgs[index] = img;
2224 // prepareFlipLeftToRight()
2226 //______________________________________________________________________________
2228 // Prepare to flip the left page towards the right. This corresponds to moving
2229 // backward when the page progression is left to right.
2230 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2232 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2234 this.prefetchImg(prevL);
2235 this.prefetchImg(prevR);
2237 var height = this._getPageHeight(prevL);
2238 var width = this._getPageWidth(prevL);
2239 var middle = this.twoPage.middle;
2240 var top = this.twoPageTop();
2241 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2243 // The gutter is the dividing line between the left and right pages.
2244 // It is offset from the middle to create the illusion of thickness to the pages
2245 var gutter = middle + this.gutterOffsetForIndex(prevL);
2247 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2248 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2249 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2252 position: 'absolute',
2253 left: gutter-scaledW+'px',
2254 right: '', // clear right property
2256 height: this.twoPage.height,
2257 width: scaledW+'px',
2258 backgroundColor: this.getPageBackgroundColor(prevL),
2259 borderRight: '1px solid black',
2263 $(this.prefetchedImgs[prevL]).css(leftCSS);
2265 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2267 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2270 position: 'absolute',
2274 height: this.twoPage.height,
2276 backgroundColor: this.getPageBackgroundColor(prevR),
2277 borderLeft: '1px solid black',
2281 $(this.prefetchedImgs[prevR]).css(rightCSS);
2283 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2287 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2288 // prepareFlipRightToLeft()
2289 //______________________________________________________________________________
2290 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2292 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2295 this.prefetchImg(nextL);
2296 this.prefetchImg(nextR);
2298 var height = this._getPageHeight(nextR);
2299 var width = this._getPageWidth(nextR);
2300 var middle = this.twoPage.middle;
2301 var top = this.twoPageTop();
2302 var scaledW = this.twoPage.height*width/height;
2304 var gutter = middle + this.gutterOffsetForIndex(nextL);
2306 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2307 $(this.prefetchedImgs[nextR]).css({
2308 position: 'absolute',
2311 backgroundColor: this.getPageBackgroundColor(nextR),
2312 height: this.twoPage.height,
2313 width: scaledW+'px',
2314 borderLeft: '1px solid black',
2318 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2320 height = this._getPageHeight(nextL);
2321 width = this._getPageWidth(nextL);
2322 scaledW = this.twoPage.height*width/height;
2324 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2325 $(this.prefetchedImgs[nextL]).css({
2326 position: 'absolute',
2327 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2329 backgroundColor: this.getPageBackgroundColor(nextL),
2330 height: this.twoPage.height,
2331 width: 0+'px', // Start at 0 width, then grow to the left
2332 borderRight: '1px solid black',
2336 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2340 // getNextLeafs() -- NOT RTL AWARE
2341 //______________________________________________________________________________
2342 // BookReader.prototype.getNextLeafs = function(o) {
2343 // //TODO: we might have two left or two right leafs in a row (damaged book)
2344 // //For now, assume that leafs are contiguous.
2346 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2347 // o.L = this.twoPage.currentIndexL+2;
2348 // o.R = this.twoPage.currentIndexL+3;
2351 // getprevLeafs() -- NOT RTL AWARE
2352 //______________________________________________________________________________
2353 // BookReader.prototype.getPrevLeafs = function(o) {
2354 // //TODO: we might have two left or two right leafs in a row (damaged book)
2355 // //For now, assume that leafs are contiguous.
2357 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2358 // o.L = this.twoPage.currentIndexL-2;
2359 // o.R = this.twoPage.currentIndexL-1;
2362 // pruneUnusedImgs()
2363 //______________________________________________________________________________
2364 BookReader.prototype.pruneUnusedImgs = function() {
2365 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2366 for (var key in this.prefetchedImgs) {
2367 //console.log('key is ' + key);
2368 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2369 //console.log('removing key '+ key);
2370 $(this.prefetchedImgs[key]).remove();
2372 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2373 //console.log('deleting key '+ key);
2374 delete this.prefetchedImgs[key];
2380 //______________________________________________________________________________
2381 BookReader.prototype.prefetch = function() {
2383 // prefetch visible pages first
2384 this.prefetchImg(this.twoPage.currentIndexL);
2385 this.prefetchImg(this.twoPage.currentIndexR);
2387 var adjacentPagesToLoad = 3;
2389 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2390 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2392 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2393 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2395 // Load images spreading out from current
2396 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2397 var goingDown = lowCurrent - i;
2398 if (goingDown >= start) {
2399 this.prefetchImg(goingDown);
2401 var goingUp = highCurrent + i;
2402 if (goingUp <= end) {
2403 this.prefetchImg(goingUp);
2408 var lim = this.twoPage.currentIndexL-4;
2410 lim = Math.max(lim, 0);
2411 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2412 this.prefetchImg(i);
2415 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2416 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2417 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2418 this.prefetchImg(i);
2424 // getPageWidth2UP()
2425 //______________________________________________________________________________
2426 BookReader.prototype.getPageWidth2UP = function(index) {
2427 // We return the width based on the dominant height
2428 var height = this._getPageHeight(index);
2429 var width = this._getPageWidth(index);
2430 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2434 //______________________________________________________________________________
2435 BookReader.prototype.search = function(term) {
2436 term = term.replace(/\//g, ' '); // strip slashes
2437 this.searchTerm = term;
2438 $('#BookReaderSearchScript').remove();
2439 var script = document.createElement("script");
2440 script.setAttribute('id', 'BookReaderSearchScript');
2441 script.setAttribute("type", "text/javascript");
2442 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2443 document.getElementsByTagName('head')[0].appendChild(script);
2444 $('#BookReaderSearchBox').val(term);
2445 $('#BookReaderSearchResults').html('Searching...');
2448 // BRSearchCallback()
2449 //______________________________________________________________________________
2450 BookReader.prototype.BRSearchCallback = function(txt) {
2452 if (jQuery.browser.msie) {
2453 var dom=new ActiveXObject("Microsoft.XMLDOM");
2457 var parser = new DOMParser();
2458 var dom = parser.parseFromString(txt, "text/xml");
2461 $('#BookReaderSearchResults').empty();
2462 $('#BookReaderSearchResults').append('<ul>');
2464 for (var key in this.searchResults) {
2465 if (null != this.searchResults[key].div) {
2466 $(this.searchResults[key].div).remove();
2468 delete this.searchResults[key];
2471 var pages = dom.getElementsByTagName('PAGE');
2473 if (0 == pages.length) {
2474 // $$$ it would be nice to echo the (sanitized) search result here
2475 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2477 for (var i = 0; i < pages.length; i++){
2478 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2481 var re = new RegExp (/_(\d{4})\.djvu/);
2482 var reMatch = re.exec(pages[i].getAttribute('file'));
2483 var index = parseInt(reMatch[1], 10);
2484 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2486 var children = pages[i].childNodes;
2488 for (var j=0; j<children.length; j++) {
2489 //console.log(j + ' - ' + children[j].nodeName);
2490 //console.log(children[j].firstChild.nodeValue);
2491 if ('CONTEXT' == children[j].nodeName) {
2492 context += children[j].firstChild.nodeValue;
2493 } else if ('WORD' == children[j].nodeName) {
2494 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2496 var index = this.leafNumToIndex(index);
2497 if (null != index) {
2498 //coordinates are [left, bottom, right, top, [baseline]]
2499 //we'll skip baseline for now...
2500 var coords = children[j].getAttribute('coords').split(',',4);
2501 if (4 == coords.length) {
2502 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2507 var pageName = this.getPageName(index);
2508 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2509 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2510 //TODO: remove hardcoded instance name
2511 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2514 $('#BookReaderSearchResults').append('</ul>');
2516 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2517 $('#BookReaderSearchBox').val(this.searchTerm);
2519 this.updateSearchHilites();
2522 // updateSearchHilites()
2523 //______________________________________________________________________________
2524 BookReader.prototype.updateSearchHilites = function() {
2525 if (2 == this.mode) {
2526 this.updateSearchHilites2UP();
2528 this.updateSearchHilites1UP();
2532 // showSearchHilites1UP()
2533 //______________________________________________________________________________
2534 BookReader.prototype.updateSearchHilites1UP = function() {
2536 for (var key in this.searchResults) {
2538 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2539 var result = this.searchResults[key];
2540 if(null == result.div) {
2541 result.div = document.createElement('div');
2542 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2543 //console.log('appending ' + key);
2546 width: (result.r-result.l)/this.reduce + 'px',
2547 height: (result.b-result.t)/this.reduce + 'px',
2548 left: (result.l)/this.reduce + 'px',
2549 top: (result.t)/this.reduce +'px'
2553 //console.log(key + ' not displayed');
2554 this.searchResults[key].div=null;
2560 //______________________________________________________________________________
2561 // Returns the position of the gutter (line between the page images)
2562 BookReader.prototype.twoPageGutter = function() {
2563 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2567 //______________________________________________________________________________
2568 // Returns the offset for the top of the page images
2569 BookReader.prototype.twoPageTop = function() {
2570 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2573 // twoPageCoverWidth()
2574 //______________________________________________________________________________
2575 // Returns the width of the cover div given the total page width
2576 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2577 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2580 // twoPageGetViewCenter()
2581 //______________________________________________________________________________
2582 // Returns the percentage offset into twopageview div at the center of container div
2583 // { percentageX: float, percentageY: float }
2584 BookReader.prototype.twoPageGetViewCenter = function() {
2587 var containerOffset = $('#BRcontainer').offset();
2588 var viewOffset = $('#BRtwopageview').offset();
2589 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2590 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2595 // twoPageCenterView(percentageX, percentageY)
2596 //______________________________________________________________________________
2597 // Centers the point given by percentage from left,top of twopageview
2598 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2599 if ('undefined' == typeof(percentageX)) {
2602 if ('undefined' == typeof(percentageY)) {
2606 var viewWidth = $('#BRtwopageview').width();
2607 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2608 var intoViewX = percentageX * viewWidth;
2610 var viewHeight = $('#BRtwopageview').height();
2611 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2612 var intoViewY = percentageY * viewHeight;
2614 if (viewWidth < containerClientWidth) {
2615 // Can fit width without scrollbars - center by adjusting offset
2616 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2618 // Need to scroll to center
2619 $('#BRtwopageview').css('left', 0);
2620 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2623 if (viewHeight < containerClientHeight) {
2624 // Fits with scrollbars - add offset
2625 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2627 $('#BRtwopageview').css('top', 0);
2628 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2632 // twoPageFlipAreaHeight
2633 //______________________________________________________________________________
2634 // Returns the integer height of the click-to-flip areas at the edges of the book
2635 BookReader.prototype.twoPageFlipAreaHeight = function() {
2636 return parseInt(this.twoPage.height);
2639 // twoPageFlipAreaWidth
2640 //______________________________________________________________________________
2641 // Returns the integer width of the flip areas
2642 BookReader.prototype.twoPageFlipAreaWidth = function() {
2643 var max = 100; // $$$ TODO base on view width?
2646 var width = this.twoPage.width * 0.15;
2647 return parseInt(BookReader.util.clamp(width, min, max));
2650 // twoPageFlipAreaTop
2651 //______________________________________________________________________________
2652 // Returns integer top offset for flip areas
2653 BookReader.prototype.twoPageFlipAreaTop = function() {
2654 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2657 // twoPageLeftFlipAreaLeft
2658 //______________________________________________________________________________
2659 // Left offset for left flip area
2660 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2661 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2664 // twoPageRightFlipAreaLeft
2665 //______________________________________________________________________________
2666 // Left offset for right flip area
2667 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2668 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2671 // twoPagePlaceFlipAreas
2672 //______________________________________________________________________________
2673 // Readjusts position of flip areas based on current layout
2674 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2675 // We don't set top since it shouldn't change relative to view
2676 $(this.twoPage.leftFlipArea).css({
2677 left: this.twoPageLeftFlipAreaLeft() + 'px',
2678 width: this.twoPageFlipAreaWidth() + 'px'
2680 $(this.twoPage.rightFlipArea).css({
2681 left: this.twoPageRightFlipAreaLeft() + 'px',
2682 width: this.twoPageFlipAreaWidth() + 'px'
2686 // showSearchHilites2UP()
2687 //______________________________________________________________________________
2688 BookReader.prototype.updateSearchHilites2UP = function() {
2690 for (var key in this.searchResults) {
2691 key = parseInt(key, 10);
2692 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2693 var result = this.searchResults[key];
2694 if(null == result.div) {
2695 result.div = document.createElement('div');
2696 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2697 //console.log('appending ' + key);
2700 // We calculate the reduction factor for the specific page because it can be different
2701 // for each page in the spread
2702 var height = this._getPageHeight(key);
2703 var width = this._getPageWidth(key)
2704 var reduce = this.twoPage.height/height;
2705 var scaledW = parseInt(width*reduce);
2707 var gutter = this.twoPageGutter();
2709 if ('L' == this.getPageSide(key)) {
2710 pageL = gutter-scaledW;
2714 var pageT = this.twoPageTop();
2717 width: (result.r-result.l)*reduce + 'px',
2718 height: (result.b-result.t)*reduce + 'px',
2719 left: pageL+(result.l)*reduce + 'px',
2720 top: pageT+(result.t)*reduce +'px'
2724 //console.log(key + ' not displayed');
2725 if (null != this.searchResults[key].div) {
2726 //console.log('removing ' + key);
2727 $(this.searchResults[key].div).remove();
2729 this.searchResults[key].div=null;
2734 // removeSearchHilites()
2735 //______________________________________________________________________________
2736 BookReader.prototype.removeSearchHilites = function() {
2737 for (var key in this.searchResults) {
2738 if (null != this.searchResults[key].div) {
2739 $(this.searchResults[key].div).remove();
2740 this.searchResults[key].div=null;
2746 //______________________________________________________________________________
2747 BookReader.prototype.printPage = function() {
2748 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2750 /* iframe implementation
2752 if (null != this.printPopup) { // check if already showing
2755 this.printPopup = document.createElement("div");
2756 $(this.printPopup).css({
2757 position: 'absolute',
2759 left: ($('#BRcontainer').width()-400)/2 + 'px',
2762 border: "3px double #999999",
2764 backgroundColor: "#fff"
2765 }).appendTo('#BookReader');
2768 if (this.constMode1up == this.mode) {
2769 indexToPrint = this.firstIndex;
2771 indexToPrint = this.twoPage.currentIndexL;
2774 this.indexToPrint = indexToPrint;
2776 var htmlStr = '<div style="text-align: center;">';
2777 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>';
2778 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2779 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2780 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2781 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2782 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2784 htmlStr += '</div>';
2785 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2786 htmlStr += '</div>';
2788 this.printPopup.innerHTML = htmlStr;
2790 var iframe = document.createElement('iframe');
2791 iframe.id = 'printFrame';
2792 iframe.name = 'printFrame';
2793 iframe.width = '233px'; // 8.5 x 11 aspect
2794 iframe.height = '300px';
2796 var self = this; // closure
2798 $(iframe).load(function() {
2799 var doc = BookReader.util.getIFrameDocument(this);
2800 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2803 $('#printDiv').prepend(iframe);
2807 // Get print URI from current indices and mode
2808 BookReader.prototype.getPrintURI = function() {
2810 if (this.constMode2up == this.mode) {
2811 indexToPrint = this.twoPage.currentIndexL;
2813 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2816 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2817 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2818 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2820 if (this.constMode2up == this.mode) {
2821 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2822 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2823 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2825 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2828 return '/bookreader/print.php?' + options;
2831 /* iframe implementation
2832 BookReader.prototype.getPrintFrameContent = function(index) {
2833 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2834 // 8.5x11 so we should end up not overflowing on either paper size.
2835 var paperAspect = 8.5 / 11;
2836 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2840 // Rotate if possible and appropriate, to get larger image size on printed page
2841 if (this.canRotatePage(index)) {
2842 if (imageAspect > 1 && imageAspect > paperAspect) {
2843 // more wide than square, and more wide than paper
2845 imageAspect = 1/imageAspect;
2850 if (imageAspect > paperAspect) {
2851 // wider than paper, fit width
2852 fitAttrs = 'width="95%"';
2854 // taller than paper, fit height
2855 fitAttrs = 'height="95%"';
2858 var imageURL = this._getPageURI(index, 1, rotate);
2859 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2860 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2861 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2862 iframeStr += '</div>';
2863 iframeStr += '</body></html>';
2868 BookReader.prototype.updatePrintFrame = function(delta) {
2869 var newIndex = this.indexToPrint + delta;
2870 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2871 if (newIndex == this.indexToPrint) {
2874 this.indexToPrint = newIndex;
2875 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2876 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2881 //______________________________________________________________________________
2882 BookReader.prototype.showEmbedCode = function() {
2883 if (null != this.embedPopup) { // check if already showing
2887 this.embedPopup = document.createElement("div");
2888 $(this.embedPopup).css({
2889 position: 'absolute',
2891 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2894 border: "3px double #999999",
2896 backgroundColor: "#fff"
2897 }).appendTo('#BookReader');
2899 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2900 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>';
2901 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2902 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2904 this.embedPopup.innerHTML = htmlStr;
2905 $(this.embedPopup).find('input').bind('click', function() {
2911 //______________________________________________________________________________
2912 BookReader.prototype.autoToggle = function() {
2914 var bComingFrom1up = false;
2915 if (2 != this.mode) {
2916 bComingFrom1up = true;
2920 // Change to autofit if book is too large
2921 if (this.reduce < this.twoPageGetAutofitReduce()) {
2926 if (null == this.autoTimer) {
2927 this.flipSpeed = 2000;
2929 // $$$ Draw events currently cause layout problems when they occur during animation.
2930 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2931 // we workaround for now by not triggering immediate animation in that case.
2932 // See https://bugs.launchpad.net/gnubook/+bug/328327
2933 if (('rl' == this.pageProgression) && bComingFrom1up) {
2934 // don't flip immediately -- wait until timer fires
2937 this.flipFwdToIndex();
2940 $('#BRtoolbar .play').hide();
2941 $('#BRtoolbar .pause').show();
2942 this.autoTimer=setInterval(function(){
2943 if (self.animating) {return;}
2945 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2946 self.flipBackToIndex(1); // $$$ really what we want?
2948 self.flipFwdToIndex();
2957 //______________________________________________________________________________
2958 // Stop autoplay mode, allowing animations to finish
2959 BookReader.prototype.autoStop = function() {
2960 if (null != this.autoTimer) {
2961 clearInterval(this.autoTimer);
2962 this.flipSpeed = 'fast';
2963 $('#BRtoolbar .pause').hide();
2964 $('#BRtoolbar .play').show();
2965 this.autoTimer = null;
2969 // stopFlipAnimations
2970 //______________________________________________________________________________
2971 // Immediately stop flip animations. Callbacks are triggered.
2972 BookReader.prototype.stopFlipAnimations = function() {
2974 this.autoStop(); // Clear timers
2976 // Stop animation, clear queue, trigger callbacks
2977 if (this.leafEdgeTmp) {
2978 $(this.leafEdgeTmp).stop(false, true);
2980 jQuery.each(this.prefetchedImgs, function() {
2981 $(this).stop(false, true);
2984 // And again since animations also queued in callbacks
2985 if (this.leafEdgeTmp) {
2986 $(this.leafEdgeTmp).stop(false, true);
2988 jQuery.each(this.prefetchedImgs, function() {
2989 $(this).stop(false, true);
2994 // keyboardNavigationIsDisabled(event)
2995 // - returns true if keyboard navigation should be disabled for the event
2996 //______________________________________________________________________________
2997 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2998 if (event.target.tagName == "INPUT") {
3004 // gutterOffsetForIndex
3005 //______________________________________________________________________________
3007 // Returns the gutter offset for the spread containing the given index.
3008 // This function supports RTL
3009 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3011 // To find the offset of the gutter from the middle we calculate our percentage distance
3012 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3013 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3015 // But then again for RTL it's the opposite
3016 if ('rl' == this.pageProgression) {
3024 //______________________________________________________________________________
3025 // Returns the width of the leaf edge div for the page with index given
3026 BookReader.prototype.leafEdgeWidth = function(pindex) {
3027 // $$$ could there be single pixel rounding errors for L vs R?
3028 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3029 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3031 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3035 // jumpIndexForLeftEdgePageX
3036 //______________________________________________________________________________
3037 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3038 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3039 if ('rl' != this.pageProgression) {
3040 // LTR - flipping backward
3041 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3043 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3044 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3048 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3049 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3054 // jumpIndexForRightEdgePageX
3055 //______________________________________________________________________________
3056 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3057 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3058 if ('rl' != this.pageProgression) {
3060 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3061 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3064 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3065 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3070 BookReader.prototype.initToolbar = function(mode, ui) {
3072 $("#BookReader").append("<div id='BRtoolbar'>"
3073 + "<span id='BRtoolbarbuttons' style='float: right'>"
3074 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3075 + "<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>"
3076 + "<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>"
3077 + "<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>"
3078 + "<div class='BRtoolbarmode3' style='display: none'><button class='BRicon rollover book_top' /><button class='BRicon rollover book_up' /> <button class='BRicon rollover book_down' /><button class='BRicon rollover book_bottom' /></div>"
3079 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3083 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3084 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3085 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3086 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3087 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3088 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3089 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3092 + "<span id='#BRbooktitle'>"
3093 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3097 this.updateToolbarZoom(this.reduce); // Pretty format
3099 if (ui == "embed") {
3100 $("#BookReader a.logo").attr("target","_blank");
3103 // $$$ turn this into a member variable
3104 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3106 // We build in mode 2
3109 this.bindToolbarNavHandlers(jToolbar);
3111 // Setup tooltips -- later we could load these from a file for i18n
3112 var titles = { '.logo': 'Go to Archive.org',
3113 '.zoom_in': 'Zoom in',
3114 '.zoom_out': 'Zoom out',
3115 '.one_page_mode': 'One-page view',
3116 '.two_page_mode': 'Two-page view',
3117 '.thumbnail_mode': 'Thumbnail view',
3118 '.print': 'Print this page',
3119 '.embed': 'Embed bookreader',
3120 '.book_left': 'Flip left',
3121 '.book_right': 'Flip right',
3122 '.book_up': 'Page up',
3123 '.book_down': 'Page down',
3126 '.book_top': 'First page',
3127 '.book_bottom': 'Last page'
3129 if ('rl' == this.pageProgression) {
3130 titles['.book_leftmost'] = 'Last page';
3131 titles['.book_rightmost'] = 'First page';
3133 titles['.book_leftmost'] = 'First page';
3134 titles['.book_rightmost'] = 'Last page';
3137 for (var icon in titles) {
3138 jToolbar.find(icon).attr('title', titles[icon]);
3141 // Hide mode buttons and autoplay if 2up is not available
3142 // $$$ if we end up with more than two modes we should show the applicable buttons
3143 if ( !this.canSwitchToMode(this.constMode2up) ) {
3144 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3147 // Switch to requested mode -- binds other click handlers
3148 this.switchToolbarMode(mode);
3153 // switchToolbarMode
3154 //______________________________________________________________________________
3155 // Update the toolbar for the given mode (changes navigation buttons)
3156 // $$$ we should soon split the toolbar out into its own module
3157 BookReader.prototype.switchToolbarMode = function(mode) {
3160 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3161 $('#BRtoolbar .BRtoolbarmode2').hide();
3162 $('#BRtoolbar .BRtoolbarmode3').hide();
3163 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3164 } else if (2 == mode) {
3166 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3167 $('#BRtoolbar .BRtoolbarmode1').hide();
3168 $('#BRtoolbar .BRtoolbarmode3').hide();
3169 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3172 $('#BRtoolbar .BRtoolbarzoom').hide();
3173 $('#BRtoolbar .BRtoolbarmode2').hide();
3174 $('#BRtoolbar .BRtoolbarmode1').hide();
3175 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3179 // bindToolbarNavHandlers
3180 //______________________________________________________________________________
3181 // Binds the toolbar handlers
3182 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3184 var self = this; // closure
3186 jToolbar.find('.book_left').bind('click', function(e) {
3191 jToolbar.find('.book_right').bind('click', function(e) {
3196 jToolbar.find('.book_up').bind('click', function(e) {
3197 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3205 jToolbar.find('.book_down').bind('click', function(e) {
3206 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3214 jToolbar.find('.print').bind('click', function(e) {
3219 jToolbar.find('.embed').bind('click', function(e) {
3220 self.showEmbedCode();
3224 jToolbar.find('.play').bind('click', function(e) {
3229 jToolbar.find('.pause').bind('click', function(e) {
3234 jToolbar.find('.book_top').bind('click', function(e) {
3239 jToolbar.find('.book_bottom').bind('click', function(e) {
3244 jToolbar.find('.book_leftmost').bind('click', function(e) {
3249 jToolbar.find('.book_rightmost').bind('click', function(e) {
3255 // updateToolbarZoom(reduce)
3256 //______________________________________________________________________________
3257 // Update the displayed zoom factor based on reduction factor
3258 BookReader.prototype.updateToolbarZoom = function(reduce) {
3260 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3263 value = (100 / reduce).toFixed(2);
3264 // Strip trailing zeroes and decimal if all zeroes
3265 value = value.replace(/0+$/,'');
3266 value = value.replace(/\.$/,'');
3269 $('#BRzoom').text(value);
3272 // firstDisplayableIndex
3273 //______________________________________________________________________________
3274 // Returns the index of the first visible page, dependent on the mode.
3275 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3276 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3277 BookReader.prototype.firstDisplayableIndex = function() {
3278 if (this.mode != this.constMode2up) {
3282 if ('rl' != this.pageProgression) {
3284 if (this.getPageSide(0) == 'L') {
3291 if (this.getPageSide(0) == 'R') {
3299 // lastDisplayableIndex
3300 //______________________________________________________________________________
3301 // Returns the index of the last visible page, dependent on the mode.
3302 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3303 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3304 BookReader.prototype.lastDisplayableIndex = function() {
3306 var lastIndex = this.numLeafs - 1;
3308 if (this.mode != this.constMode2up) {
3312 if ('rl' != this.pageProgression) {
3314 if (this.getPageSide(lastIndex) == 'R') {
3317 return lastIndex + 1;
3321 if (this.getPageSide(lastIndex) == 'L') {
3324 return lastIndex + 1;
3329 // shortTitle(maximumCharacters)
3331 // Returns a shortened version of the title with the maximum number of characters
3332 BookReader.prototype.shortTitle = function(maximumCharacters) {
3333 if (this.bookTitle.length < maximumCharacters) {
3334 return this.bookTitle;
3337 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3342 // Parameter related functions
3344 // updateFromParams(params)
3346 // Update ourselves from the params object.
3348 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3349 BookReader.prototype.updateFromParams = function(params) {
3350 if ('undefined' != typeof(params.mode)) {
3351 this.switchMode(params.mode);
3355 if ('undefined' != typeof(params.searchTerm)) {
3356 if (this.searchTerm != params.searchTerm) {
3357 this.search(params.searchTerm);
3361 // $$$ process /zoom
3363 // We only respect page if index is not set
3364 if ('undefined' != typeof(params.index)) {
3365 if (params.index != this.currentIndex()) {
3366 this.jumpToIndex(params.index);
3368 } else if ('undefined' != typeof(params.page)) {
3369 // $$$ this assumes page numbers are unique
3370 if (params.page != this.getPageNum(this.currentIndex())) {
3371 this.jumpToPage(params.page);
3375 // $$$ process /region
3376 // $$$ process /highlight
3379 // paramsFromFragment(urlFragment)
3381 // Returns a object with configuration parametes from a URL fragment.
3383 // E.g paramsFromFragment(window.location.hash)
3384 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3385 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3389 // For convenience we allow an initial # character (as from window.location.hash)
3390 // but don't require it
3391 if (urlFragment.substr(0,1) == '#') {
3392 urlFragment = urlFragment.substr(1);
3395 // Simple #nn syntax
3396 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3397 if ( !isNaN(oldStyleLeafNum) ) {
3398 params.index = oldStyleLeafNum;
3400 // Done processing if using old-style syntax
3404 // Split into key-value pairs
3405 var urlArray = urlFragment.split('/');
3407 for (var i = 0; i < urlArray.length; i += 2) {
3408 urlHash[urlArray[i]] = urlArray[i+1];
3412 if ('1up' == urlHash['mode']) {
3413 params.mode = this.constMode1up;
3414 } else if ('2up' == urlHash['mode']) {
3415 params.mode = this.constMode2up;
3416 } else if ('thumb' == urlHash['mode']) {
3417 params.mode = this.constModeThumb;
3421 if ('undefined' != typeof(urlHash['page'])) {
3422 // page was set -- may not be int
3423 params.page = urlHash['page'];
3426 // $$$ process /region
3427 // $$$ process /search
3429 if (urlHash['search'] != undefined) {
3430 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3433 // $$$ process /highlight
3438 // paramsFromCurrent()
3440 // Create a params object from the current parameters.
3441 BookReader.prototype.paramsFromCurrent = function() {
3445 var index = this.currentIndex();
3446 var pageNum = this.getPageNum(index);
3447 if ((pageNum === 0) || pageNum) {
3448 params.page = pageNum;
3451 params.index = index;
3452 params.mode = this.mode;
3458 if (this.searchHighlightVisible()) {
3459 params.searchTerm = this.searchTerm;
3465 // fragmentFromParams(params)
3467 // Create a fragment string from the params object.
3468 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3469 BookReader.prototype.fragmentFromParams = function(params) {
3470 var separator = '/';
3474 if ('undefined' != typeof(params.page)) {
3475 fragments.push('page', params.page);
3477 // Don't have page numbering -- use index instead
3478 fragments.push('page', 'n' + params.index);
3485 if ('undefined' != typeof(params.mode)) {
3486 if (params.mode == this.constMode1up) {
3487 fragments.push('mode', '1up');
3488 } else if (params.mode == this.constMode2up) {
3489 fragments.push('mode', '2up');
3490 } else if (params.mode == this.constModeThumb) {
3491 fragments.push('mode', 'thumb');
3493 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3498 if (params.searchTerm) {
3499 fragments.push('search', params.searchTerm);
3502 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3505 // getPageIndex(pageNum)
3507 // Returns the *highest* index the given page number, or undefined
3508 BookReader.prototype.getPageIndex = function(pageNum) {
3509 var pageIndices = this.getPageIndices(pageNum);
3511 if (pageIndices.length > 0) {
3512 return pageIndices[pageIndices.length - 1];
3518 // getPageIndices(pageNum)
3520 // Returns an array (possibly empty) of the indices with the given page number
3521 BookReader.prototype.getPageIndices = function(pageNum) {
3524 // Check for special "nXX" page number
3525 if (pageNum.slice(0,1) == 'n') {
3527 var pageIntStr = pageNum.slice(1, pageNum.length);
3528 var pageIndex = parseInt(pageIntStr);
3529 indices.push(pageIndex);
3532 // Do nothing... will run through page names and see if one matches
3537 for (i=0; i<this.numLeafs; i++) {
3538 if (this.getPageNum(i) == pageNum) {
3546 // getPageName(index)
3548 // Returns the name of the page as it should be displayed in the user interface
3549 BookReader.prototype.getPageName = function(index) {
3550 return 'Page ' + this.getPageNum(index);
3553 // updateLocationHash
3555 // Update the location hash from the current parameters. Call this instead of manually
3556 // using window.location.replace
3557 BookReader.prototype.updateLocationHash = function() {
3558 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3559 window.location.replace(newHash);
3561 // This is the variable checked in the timer. Only user-generated changes
3562 // to the URL will trigger the event.
3563 this.oldLocationHash = newHash;
3566 // startLocationPolling
3568 // Starts polling of window.location to see hash fragment changes
3569 BookReader.prototype.startLocationPolling = function() {
3570 var self = this; // remember who I am
3571 self.oldLocationHash = window.location.hash;
3573 if (this.locationPollId) {
3574 clearInterval(this.locationPollID);
3575 this.locationPollId = null;
3578 this.locationPollId = setInterval(function() {
3579 var newHash = window.location.hash;
3580 if (newHash != self.oldLocationHash) {
3581 if (newHash != self.oldUserHash) { // Only process new user hash once
3582 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3584 // Queue change if animating
3585 if (self.animating) {
3587 self.animationFinishedCallback = function() {
3588 self.updateFromParams(self.paramsFromFragment(newHash));
3590 } else { // update immediately
3591 self.updateFromParams(self.paramsFromFragment(newHash));
3593 self.oldUserHash = newHash;
3601 // Returns true if we can switch to the requested mode
3602 BookReader.prototype.canSwitchToMode = function(mode) {
3603 if (mode == this.constMode2up) {
3604 // check there are enough pages to display
3605 // $$$ this is a workaround for the mis-feature that we can't display
3606 // short books in 2up mode
3607 if (this.numLeafs < 6) {
3615 // searchHighlightVisible
3617 // Returns true if a search highlight is currently being displayed
3618 BookReader.prototype.searchHighlightVisible = function() {
3619 if (this.constMode2up == this.mode) {
3620 if (this.searchResults[this.twoPage.currentIndexL]
3621 || this.searchResults[this.twoPage.currentIndexR]) {
3625 if (this.searchResults[this.currentIndex()]) {
3632 // getPageBackgroundColor
3634 // Returns a CSS property string for the background color for the given page
3635 // $$$ turn into regular CSS?
3636 BookReader.prototype.getPageBackgroundColor = function(index) {
3637 if (index >= 0 && index < this.numLeafs) {
3639 return this.pageDefaultBackgroundColor;
3647 // Returns the page width for the given index, or first or last page if out of range
3648 BookReader.prototype._getPageWidth = function(index) {
3649 // Synthesize a page width for pages not actually present in book.
3650 // May or may not be the best approach.
3651 // If index is out of range we return the width of first or last page
3652 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3653 return this.getPageWidth(index);
3658 // Returns the page height for the given index, or first or last page if out of range
3659 BookReader.prototype._getPageHeight= function(index) {
3660 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3661 return this.getPageHeight(index);
3666 // Returns the page URI or transparent image if out of range
3667 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3668 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3669 return this.imagesBaseURL + "/transparent.png";
3672 if ('undefined' == typeof(reduce)) {
3673 // reduce not passed in
3674 // $$$ this probably won't work for thumbnail mode
3675 var ratio = this.getPageHeight(index) / this.twoPage.height;
3677 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3680 } else if (ratio < 4) {
3682 } else if (ratio < 8) {
3684 } else if (ratio < 16) {
3686 } else if (ratio < 32) {
3694 return this.getPageURI(index, reduce, rotate);
3697 // Library functions
3699 disableSelect: function(jObject) {
3700 // Bind mouse handlers
3701 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3702 jObject.bind('mousedown', function(e) {
3703 // $$$ check here for right-click and don't disable. Also use jQuery style
3704 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3707 // Special hack for IE7
3708 jObject[0].onselectstart = function(e) { return false; };
3711 clamp: function(value, min, max) {
3712 return Math.min(Math.max(value, min), max);
3715 getIFrameDocument: function(iframe) {
3716 // Adapted from http://xkr.us/articles/dom/iframe-document/
3717 var outer = (iframe.contentWindow || iframe.contentDocument);
3718 return (outer.document || outer);
3721 decodeURIComponentPlus: function(value) {
3722 // Decodes a URI component and converts '+' to ' '
3723 return decodeURIComponent(value).replace(/\+/g, ' ');
3726 encodeURIComponentPlus: function(value) {
3727 // Encodes a URI component and converts ' ' to '+'
3728 return encodeURIComponent(value).replace(/%20/g, '+');
3730 // The final property here must NOT have a comma after it - IE7