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 // Note: #BRpageview must already exist since its width is used to calculate the
1032 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1033 var padding = (thumbnailColumns + 1) * this.padding;
1034 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1035 return parseInt(width);
1038 // quantizeReduce(reduce)
1039 //______________________________________________________________________________
1040 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1041 BookReader.prototype.quantizeReduce = function(reduce) {
1042 var quantized = this.reductionFactors[0];
1043 var distance = Math.abs(reduce - quantized);
1044 for (var i = 1; i < this.reductionFactors.length; i++) {
1045 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1046 if (newDistance < distance) {
1047 distance = newDistance;
1048 quantized = this.reductionFactors[i];
1055 // twoPageNextReduce()
1056 //______________________________________________________________________________
1057 // Returns the next reduction level
1058 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1060 var autofitReduce = this.twoPageGetAutofitReduce();
1062 if (0 == direction) { // autofit
1063 result.autofit = true;
1064 result.reduce = autofitReduce;
1066 } else if (1 == direction) { // zoom in
1067 var newReduce = this.reductionFactors[0];
1069 for (var i = 1; i < this.reductionFactors.length; i++) {
1070 if (this.reductionFactors[i] < reduce) {
1071 newReduce = this.reductionFactors[i];
1075 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1077 result.autofit = true;
1078 result.reduce = autofitReduce;
1080 result.autofit = false;
1081 result.reduce = newReduce;
1084 } else { // zoom out
1085 var lastIndex = this.reductionFactors.length - 1;
1086 var newReduce = this.reductionFactors[lastIndex];
1088 for (var i = lastIndex; i >= 0; i--) {
1089 if (this.reductionFactors[i] > reduce) {
1090 newReduce = this.reductionFactors[i];
1094 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1096 result.autofit = true;
1097 result.reduce = autofitReduce;
1099 result.autofit = false;
1100 result.reduce = newReduce;
1108 //______________________________________________________________________________
1109 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1110 BookReader.prototype.jumpToPage = function(pageNum) {
1112 var pageIndex = this.getPageIndex(pageNum);
1114 if ('undefined' != typeof(pageIndex)) {
1117 this.jumpToIndex(pageIndex);
1118 $('#BRcontainer').attr('scrollTop', leafTop);
1127 //______________________________________________________________________________
1128 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1130 if (2 == this.mode) {
1133 // By checking against min/max we do nothing if requested index
1135 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1136 this.flipBackToIndex(index);
1137 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1138 this.flipFwdToIndex(index);
1141 } else if (3 == this.mode) {
1142 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1152 for (i=0; i<(index+1); i++) {
1153 leafWidth = this.thumbWidth;
1154 if (rightPos + (leafWidth + this.padding) > viewWidth){
1159 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1160 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1161 if (leafIndex==0) { leafTop = bottomPos; }
1162 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1163 rightPos += leafWidth + this.padding;
1166 this.firstIndex=index;
1167 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1170 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1177 for (i=0; i<index; i++) {
1178 h = parseInt(this._getPageHeight(i)/this.reduce);
1179 leafTop += h + this.padding;
1183 //console.log('pageY ' + pageY);
1184 var offset = parseInt( (pageY) / this.reduce);
1185 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1186 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1191 var offset = parseInt( (pageX) / this.reduce);
1192 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1196 //$('#BRcontainer').attr('scrollTop', leafTop);
1197 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1203 //______________________________________________________________________________
1204 BookReader.prototype.switchMode = function(mode) {
1206 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1208 if (mode == this.mode) {
1212 if (!this.canSwitchToMode(mode)) {
1217 this.removeSearchHilites();
1220 this.switchToolbarMode(mode);
1222 // reinstate scale if moving from thumbnail view
1223 if (this.pageScale != this.reduce) {
1224 this.reduce = this.pageScale;
1227 // $$$ TODO preserve center of view when switching between mode
1228 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1231 this.reduce = this.quantizeReduce(this.reduce);
1232 this.prepareOnePageView();
1233 } else if (3 == mode) {
1234 this.reduce = this.quantizeReduce(this.reduce);
1235 this.prepareThumbnailView();
1236 this.jumpToIndex(this.currentIndex());
1238 // $$$ why don't we save autofit?
1239 this.twoPage.autofit = false; // Take zoom level from other mode
1240 this.reduce = this.quantizeReduce(this.reduce);
1241 this.prepareTwoPageView();
1242 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1247 //prepareOnePageView()
1248 //______________________________________________________________________________
1249 BookReader.prototype.prepareOnePageView = function() {
1251 // var startLeaf = this.displayedIndices[0];
1252 var startLeaf = this.currentIndex();
1254 $('#BRcontainer').empty();
1255 $('#BRcontainer').css({
1256 overflowY: 'scroll',
1260 $("#BRcontainer").append("<div id='BRpageview'></div>");
1261 // $$$ keep select enabled for now since disabling it breaks keyboard
1262 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1263 // BookReader.util.disableSelect($('#BRpageview'));
1265 this.resizePageView();
1267 this.jumpToIndex(startLeaf);
1268 this.displayedIndices = [];
1270 this.drawLeafsOnePage();
1273 //prepareThumbnailView()
1274 //______________________________________________________________________________
1275 BookReader.prototype.prepareThumbnailView = function() {
1277 $('#BRcontainer').empty();
1278 $('#BRcontainer').css({
1279 overflowY: 'scroll',
1283 $("#BRcontainer").append("<div id='BRpageview'></div>");
1285 // $$$ keep select enabled for now since disabling it breaks keyboard
1286 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1287 // BookReader.util.disableSelect($('#BRpageview'));
1289 var startLeaf = this.currentIndex();
1290 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1291 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1293 this.resizePageView();
1295 this.displayedRows = [];
1296 this.drawLeafsThumbnail();
1299 // prepareTwoPageView()
1300 //______________________________________________________________________________
1301 // Some decisions about two page view:
1303 // Both pages will be displayed at the same height, even if they were different physical/scanned
1304 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1305 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1306 // aspect ratio to determine the height.
1308 // The two page view div is resized to keep the middle of the book in the middle of the div
1309 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1310 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1311 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1312 $('#BRcontainer').empty();
1313 $('#BRcontainer').css('overflow', 'auto');
1315 // We want to display two facing pages. We may be missing
1316 // one side of the spread because it is the first/last leaf,
1317 // foldouts, missing pages, etc
1319 //var targetLeaf = this.displayedIndices[0];
1320 var targetLeaf = this.firstIndex;
1322 if (targetLeaf < this.firstDisplayableIndex()) {
1323 targetLeaf = this.firstDisplayableIndex();
1326 if (targetLeaf > this.lastDisplayableIndex()) {
1327 targetLeaf = this.lastDisplayableIndex();
1330 //this.twoPage.currentIndexL = null;
1331 //this.twoPage.currentIndexR = null;
1332 //this.pruneUnusedImgs();
1334 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1335 this.twoPage.currentIndexL = currentSpreadIndices[0];
1336 this.twoPage.currentIndexR = currentSpreadIndices[1];
1337 this.firstIndex = this.twoPage.currentIndexL;
1339 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1341 this.pruneUnusedImgs();
1342 this.prefetch(); // Preload images or reload if scaling has changed
1344 //console.dir(this.twoPage);
1346 // Add the two page view
1347 // $$$ Can we get everything set up and then append?
1348 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1350 // $$$ calculate first then set
1351 $('#BRtwopageview').css( {
1352 height: this.twoPage.totalHeight + 'px',
1353 width: this.twoPage.totalWidth + 'px',
1354 position: 'absolute'
1357 // If there will not be scrollbars (e.g. when zooming out) we center the book
1358 // since otherwise the book will be stuck off-center
1359 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1360 centerPercentageX = 0.5;
1362 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1363 centerPercentageY = 0.5;
1366 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1368 this.twoPage.coverDiv = document.createElement('div');
1369 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1370 border: '1px solid rgb(68, 25, 17)',
1371 width: this.twoPage.bookCoverDivWidth + 'px',
1372 height: this.twoPage.bookCoverDivHeight+'px',
1373 visibility: 'visible',
1374 position: 'absolute',
1375 backgroundColor: '#663929',
1376 left: this.twoPage.bookCoverDivLeft + 'px',
1377 top: this.twoPage.bookCoverDivTop+'px',
1378 MozBorderRadiusTopleft: '7px',
1379 MozBorderRadiusTopright: '7px',
1380 MozBorderRadiusBottomright: '7px',
1381 MozBorderRadiusBottomleft: '7px'
1382 }).appendTo('#BRtwopageview');
1384 this.leafEdgeR = document.createElement('div');
1385 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1386 $(this.leafEdgeR).css({
1387 borderStyle: 'solid solid solid none',
1388 borderColor: 'rgb(51, 51, 34)',
1389 borderWidth: '1px 1px 1px 0px',
1390 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1391 width: this.twoPage.leafEdgeWidthR + 'px',
1392 height: this.twoPage.height-1 + 'px',
1394 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1395 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1396 position: 'absolute'
1397 }).appendTo('#BRtwopageview');
1399 this.leafEdgeL = document.createElement('div');
1400 this.leafEdgeL.className = 'leafEdgeL';
1401 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1402 borderStyle: 'solid none solid solid',
1403 borderColor: 'rgb(51, 51, 34)',
1404 borderWidth: '1px 0px 1px 1px',
1405 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1406 width: this.twoPage.leafEdgeWidthL + 'px',
1407 height: this.twoPage.height-1 + 'px',
1408 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1409 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1410 position: 'absolute'
1411 }).appendTo('#BRtwopageview');
1413 div = document.createElement('div');
1414 $(div).attr('id', 'BRbookspine').css({
1415 border: '1px solid rgb(68, 25, 17)',
1416 width: this.twoPage.bookSpineDivWidth+'px',
1417 height: this.twoPage.bookSpineDivHeight+'px',
1418 position: 'absolute',
1419 backgroundColor: 'rgb(68, 25, 17)',
1420 left: this.twoPage.bookSpineDivLeft+'px',
1421 top: this.twoPage.bookSpineDivTop+'px'
1422 }).appendTo('#BRtwopageview');
1424 var self = this; // for closure
1426 /* Flip areas no longer used
1427 this.twoPage.leftFlipArea = document.createElement('div');
1428 this.twoPage.leftFlipArea.className = 'BRfliparea';
1429 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1431 width: this.twoPageFlipAreaWidth() + 'px',
1432 height: this.twoPageFlipAreaHeight() + 'px',
1433 position: 'absolute',
1434 left: this.twoPageLeftFlipAreaLeft() + 'px',
1435 top: this.twoPageFlipAreaTop() + 'px',
1438 }).bind('click', function(e) {
1440 }).bind('mousedown', function(e) {
1442 }).appendTo('#BRtwopageview');
1444 this.twoPage.rightFlipArea = document.createElement('div');
1445 this.twoPage.rightFlipArea.className = 'BRfliparea';
1446 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1448 width: this.twoPageFlipAreaWidth() + 'px',
1449 height: this.twoPageFlipAreaHeight() + 'px',
1450 position: 'absolute',
1451 left: this.twoPageRightFlipAreaLeft() + 'px',
1452 top: this.twoPageFlipAreaTop() + 'px',
1455 }).bind('click', function(e) {
1457 }).bind('mousedown', function(e) {
1459 }).appendTo('#BRtwopageview');
1462 this.prepareTwoPagePopUp();
1464 this.displayedIndices = [];
1466 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1467 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1469 this.drawLeafsTwoPage();
1470 this.updateToolbarZoom(this.reduce);
1474 this.removeSearchHilites();
1475 this.updateSearchHilites();
1479 // prepareTwoPagePopUp()
1481 // This function prepares the "View Page n" popup that shows while the mouse is
1482 // over the left/right "stack of sheets" edges. It also binds the mouse
1483 // events for these divs.
1484 //______________________________________________________________________________
1485 BookReader.prototype.prepareTwoPagePopUp = function() {
1487 this.twoPagePopUp = document.createElement('div');
1488 $(this.twoPagePopUp).css({
1489 border: '1px solid black',
1491 position: 'absolute',
1492 fontFamily: 'sans-serif',
1495 backgroundColor: 'rgb(255, 255, 238)',
1497 }).appendTo('#BRcontainer');
1498 $(this.twoPagePopUp).hide();
1500 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1501 $(e.data.twoPagePopUp).show();
1504 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1505 $(e.data.twoPagePopUp).hide();
1508 $(this.leafEdgeL).bind('click', this, function(e) {
1510 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1511 e.data.jumpToIndex(jumpIndex);
1514 $(this.leafEdgeR).bind('click', this, function(e) {
1516 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1517 e.data.jumpToIndex(jumpIndex);
1520 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1522 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1523 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1525 // $$$ TODO: Make sure popup is positioned so that it is in view
1526 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1527 $(e.data.twoPagePopUp).css({
1528 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1529 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1533 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1535 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1536 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1538 // $$$ TODO: Make sure popup is positioned so that it is in view
1539 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1540 $(e.data.twoPagePopUp).css({
1541 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1542 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1547 // calculateSpreadSize()
1548 //______________________________________________________________________________
1549 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1550 // this.twoPage.currentIndexR
1551 // This function sets this.twoPage.height, twoPage.width
1553 BookReader.prototype.calculateSpreadSize = function() {
1555 var firstIndex = this.twoPage.currentIndexL;
1556 var secondIndex = this.twoPage.currentIndexR;
1557 //console.log('first page is ' + firstIndex);
1559 // Calculate page sizes and total leaf width
1561 if ( this.twoPage.autofit) {
1562 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1564 // set based on reduction factor
1565 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1568 // Both pages together
1569 this.twoPage.height = spreadSize.height;
1570 this.twoPage.width = spreadSize.width;
1573 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1574 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1577 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1578 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1579 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1583 // The width of the book cover div. The combined width of both pages, twice the width
1584 // of the book cover internal padding (2*10) and the page edges
1585 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1586 // The height of the book cover div
1587 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1590 // We calculate the total width and height for the div so that we can make the book
1592 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1593 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1594 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1595 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1596 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1597 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1599 // We want to minimize the unused space in two-up mode (maximize the amount of page
1600 // shown). We give width to the leaf edges and these widths change (though the sum
1601 // of the two remains constant) as we flip through the book. With the book
1602 // cover centered and fixed in the BRcontainer div the page images will meet
1603 // at the "gutter" which is generally offset from the center.
1604 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1605 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1607 // The left edge of the book cover moves depending on the width of the pages
1608 // $$$ change to getter
1609 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1610 // The top edge of the book cover stays a fixed distance from the top
1611 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1614 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1615 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1616 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1619 this.reduce = spreadSize.reduce; // $$$ really set this here?
1622 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1625 // We check which page is closest to a "normal" page and use that to set the height
1626 // for both pages. This means that foldouts and other odd size pages will be displayed
1627 // smaller than the nominal zoom amount.
1628 var canon5Dratio = 1.5;
1631 height: this._getPageHeight(firstIndex),
1632 width: this._getPageWidth(firstIndex)
1636 height: this._getPageHeight(secondIndex),
1637 width: this._getPageWidth(secondIndex)
1640 var firstIndexRatio = first.height / first.width;
1641 var secondIndexRatio = second.height / second.width;
1642 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1645 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1646 ratio = firstIndexRatio;
1647 //console.log('using firstIndexRatio ' + ratio);
1649 ratio = secondIndexRatio;
1650 //console.log('using secondIndexRatio ' + ratio);
1653 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1654 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1655 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1657 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1658 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1660 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1661 ideal.width -= 10; // $$$ fudge factor
1662 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1663 ideal.height -= 20; // fudge factor
1664 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1666 if (ideal.height/ratio <= ideal.width) {
1668 ideal.width = parseInt(ideal.height/ratio);
1671 ideal.height = parseInt(ideal.width*ratio);
1674 // $$$ check this logic with large spreads
1675 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1680 // getSpreadSizeFromReduce()
1681 //______________________________________________________________________________
1682 // Returns the spread size calculated from the reduction factor for the given pages
1683 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1684 var spreadSize = {};
1685 // $$$ Scale this based on reduce?
1686 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1687 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1688 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1690 // $$$ Possibly incorrect -- we should make height "dominant"
1691 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1692 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1693 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1694 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1695 spreadSize.reduce = reduce;
1700 // twoPageGetAutofitReduce()
1701 //______________________________________________________________________________
1702 // Returns the current ideal reduction factor
1703 BookReader.prototype.twoPageGetAutofitReduce = function() {
1704 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1705 return spreadSize.reduce;
1708 // twoPageSetCursor()
1709 //______________________________________________________________________________
1710 // Set the cursor for two page view
1711 BookReader.prototype.twoPageSetCursor = function() {
1712 // console.log('setting cursor');
1713 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1714 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1715 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1716 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1718 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1719 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1724 //______________________________________________________________________________
1725 // Returns the currently active index.
1726 BookReader.prototype.currentIndex = function() {
1727 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1728 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1729 return this.firstIndex; // $$$ TODO page in center of view would be better
1730 } else if (this.mode == this.constMode2up) {
1731 // Only allow indices that are actually present in book
1732 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1734 throw 'currentIndex called for unimplemented mode ' + this.mode;
1739 //______________________________________________________________________________
1740 // Flip the right page over onto the left
1741 BookReader.prototype.right = function() {
1742 if ('rl' != this.pageProgression) {
1752 //______________________________________________________________________________
1753 // Flip to the rightmost page
1754 BookReader.prototype.rightmost = function() {
1755 if ('rl' != this.pageProgression) {
1763 //______________________________________________________________________________
1764 // Flip the left page over onto the right.
1765 BookReader.prototype.left = function() {
1766 if ('rl' != this.pageProgression) {
1776 //______________________________________________________________________________
1777 // Flip to the leftmost page
1778 BookReader.prototype.leftmost = function() {
1779 if ('rl' != this.pageProgression) {
1787 //______________________________________________________________________________
1788 BookReader.prototype.next = function() {
1789 if (2 == this.mode) {
1791 this.flipFwdToIndex(null);
1793 if (this.firstIndex < this.lastDisplayableIndex()) {
1794 this.jumpToIndex(this.firstIndex+1);
1800 //______________________________________________________________________________
1801 BookReader.prototype.prev = function() {
1802 if (2 == this.mode) {
1804 this.flipBackToIndex(null);
1806 if (this.firstIndex >= 1) {
1807 this.jumpToIndex(this.firstIndex-1);
1812 BookReader.prototype.first = function() {
1813 this.jumpToIndex(this.firstDisplayableIndex());
1816 BookReader.prototype.last = function() {
1817 this.jumpToIndex(this.lastDisplayableIndex());
1821 //______________________________________________________________________________
1822 // Scrolls down one screen view
1823 BookReader.prototype.scrollDown = function() {
1824 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1825 $('#BRcontainer').animate(
1826 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1827 450, 'easeInOutQuint'
1836 //______________________________________________________________________________
1837 // Scrolls up one screen view
1838 BookReader.prototype.scrollUp = function() {
1839 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb])) {
1840 $('#BRcontainer').animate(
1841 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1842 450, 'easeInOutQuint'
1851 // flipBackToIndex()
1852 //______________________________________________________________________________
1853 // to flip back one spread, pass index=null
1854 BookReader.prototype.flipBackToIndex = function(index) {
1856 if (1 == this.mode) return;
1858 var leftIndex = this.twoPage.currentIndexL;
1860 if (this.animating) return;
1862 if (null != this.leafEdgeTmp) {
1863 alert('error: leafEdgeTmp should be null!');
1867 if (null == index) {
1868 index = leftIndex-2;
1870 //if (index<0) return;
1872 var previousIndices = this.getSpreadIndices(index);
1874 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1878 this.animating = true;
1880 if ('rl' != this.pageProgression) {
1881 // Assume LTR and we are going backward
1882 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1883 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1885 // RTL and going backward
1886 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1887 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1891 // flipLeftToRight()
1892 //______________________________________________________________________________
1893 // Flips the page on the left towards the page on the right
1894 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1896 var leftLeaf = this.twoPage.currentIndexL;
1898 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1899 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1900 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1902 var currWidthL = this.getPageWidth2UP(leftLeaf);
1903 var newWidthL = this.getPageWidth2UP(newIndexL);
1904 var newWidthR = this.getPageWidth2UP(newIndexR);
1906 var top = this.twoPageTop();
1907 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1909 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1910 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1912 //animation strategy:
1913 // 0. remove search highlight, if any.
1914 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1915 // of the left leaf and where the user clicked in the leaf edge.
1916 // Note that if this function was triggered by left() and not a
1917 // mouse click, the width of leafEdgeTmp is very small (zero px).
1918 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1919 // leftLeaf to width=0.
1920 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1921 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1922 // its new full width.
1923 // 4. After step 3 is finished, do the following:
1924 // - remove leafEdgeTmp from the dom.
1925 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1926 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1927 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1928 // and width=newLeafEdgeWidthL.
1929 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1930 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1931 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1932 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1933 // - prefetch new adjacent leafs.
1934 // - set up click handlers for both new left and right leafs.
1935 // - redraw the search highlight.
1936 // - update the pagenum box and the url.
1939 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1941 this.leafEdgeTmp = document.createElement('div');
1942 $(this.leafEdgeTmp).css({
1943 borderStyle: 'solid none solid solid',
1944 borderColor: 'rgb(51, 51, 34)',
1945 borderWidth: '1px 0px 1px 1px',
1946 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1947 width: leafEdgeTmpW + 'px',
1948 height: this.twoPage.height-1 + 'px',
1949 left: leftEdgeTmpLeft + 'px',
1951 position: 'absolute',
1953 }).appendTo('#BRtwopageview');
1955 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1956 $(this.leafEdgeL).css({
1957 width: newLeafEdgeWidthL+'px',
1958 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1961 // Left gets the offset of the current left leaf from the document
1962 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1963 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1964 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1966 // We change the left leaf to right positioning
1967 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1968 $(this.prefetchedImgs[leftLeaf]).css({
1973 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1974 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1978 this.removeSearchHilites();
1980 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1981 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1983 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1984 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1986 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1987 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1988 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1990 $(self.leafEdgeR).css({
1991 // Moves the right leaf edge
1992 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1993 left: gutter+newWidthR+'px'
1996 $(self.leafEdgeL).css({
1997 // Moves and resizes the left leaf edge
1998 width: newLeafEdgeWidthL+'px',
1999 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2002 // Resizes the brown border div
2003 $(self.twoPage.coverDiv).css({
2004 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2005 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2008 $(self.leafEdgeTmp).remove();
2009 self.leafEdgeTmp = null;
2011 // $$$ TODO refactor with opposite direction flip
2013 self.twoPage.currentIndexL = newIndexL;
2014 self.twoPage.currentIndexR = newIndexR;
2015 self.twoPage.scaledWL = newWidthL;
2016 self.twoPage.scaledWR = newWidthR;
2017 self.twoPage.gutter = gutter;
2019 self.firstIndex = self.twoPage.currentIndexL;
2020 self.displayedIndices = [newIndexL, newIndexR];
2021 self.pruneUnusedImgs();
2023 self.animating = false;
2025 self.updateSearchHilites2UP();
2026 self.updatePageNumBox2UP();
2028 // self.twoPagePlaceFlipAreas(); // No longer used
2029 self.setMouseHandlers2UP();
2030 self.twoPageSetCursor();
2032 if (self.animationFinishedCallback) {
2033 self.animationFinishedCallback();
2034 self.animationFinishedCallback = null;
2042 //______________________________________________________________________________
2043 // Whether we flip left or right is dependent on the page progression
2044 // to flip forward one spread, pass index=null
2045 BookReader.prototype.flipFwdToIndex = function(index) {
2047 if (this.animating) return;
2049 if (null != this.leafEdgeTmp) {
2050 alert('error: leafEdgeTmp should be null!');
2054 if (null == index) {
2055 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2057 if (index > this.lastDisplayableIndex()) return;
2059 this.animating = true;
2061 var nextIndices = this.getSpreadIndices(index);
2063 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2065 if ('rl' != this.pageProgression) {
2066 // We did not specify RTL
2067 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2068 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2071 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2072 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2076 // flipRightToLeft(nextL, nextR, gutter)
2077 // $$$ better not to have to pass gutter in
2078 //______________________________________________________________________________
2079 // Flip from left to right and show the nextL and nextR indices on those sides
2080 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2081 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2082 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2083 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2084 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2086 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2088 var top = this.twoPageTop();
2089 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2091 var middle = this.twoPage.middle;
2092 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2094 this.leafEdgeTmp = document.createElement('div');
2095 $(this.leafEdgeTmp).css({
2096 borderStyle: 'solid none solid solid',
2097 borderColor: 'rgb(51, 51, 34)',
2098 borderWidth: '1px 0px 1px 1px',
2099 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2100 width: leafEdgeTmpW + 'px',
2101 height: this.twoPage.height-1 + 'px',
2102 left: gutter+scaledW+'px',
2104 position: 'absolute',
2106 }).appendTo('#BRtwopageview');
2108 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2109 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2111 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2112 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2113 var newWidthL = this.getPageWidth2UP(newIndexL);
2114 var newWidthR = this.getPageWidth2UP(newIndexR);
2116 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2118 var self = this; // closure-tastic!
2120 var speed = this.flipSpeed;
2122 this.removeSearchHilites();
2124 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2125 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2126 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2127 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2128 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2130 $(self.leafEdgeL).css({
2131 width: newLeafEdgeWidthL+'px',
2132 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2135 // Resizes the book cover
2136 $(self.twoPage.coverDiv).css({
2137 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2138 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2141 $(self.leafEdgeTmp).remove();
2142 self.leafEdgeTmp = null;
2144 self.twoPage.currentIndexL = newIndexL;
2145 self.twoPage.currentIndexR = newIndexR;
2146 self.twoPage.scaledWL = newWidthL;
2147 self.twoPage.scaledWR = newWidthR;
2148 self.twoPage.gutter = gutter;
2150 self.firstIndex = self.twoPage.currentIndexL;
2151 self.displayedIndices = [newIndexL, newIndexR];
2152 self.pruneUnusedImgs();
2154 self.animating = false;
2157 self.updateSearchHilites2UP();
2158 self.updatePageNumBox2UP();
2160 // self.twoPagePlaceFlipAreas(); // No longer used
2161 self.setMouseHandlers2UP();
2162 self.twoPageSetCursor();
2164 if (self.animationFinishedCallback) {
2165 self.animationFinishedCallback();
2166 self.animationFinishedCallback = null;
2172 // setMouseHandlers2UP
2173 //______________________________________________________________________________
2174 BookReader.prototype.setMouseHandlers2UP = function() {
2176 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2181 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2188 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2189 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2196 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2197 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2200 e.data.self.right();
2206 //______________________________________________________________________________
2207 BookReader.prototype.prefetchImg = function(index) {
2208 var pageURI = this._getPageURI(index);
2210 // Load image if not loaded or URI has changed (e.g. due to scaling)
2211 var loadImage = false;
2212 if (undefined == this.prefetchedImgs[index]) {
2213 //console.log('no image for ' + index);
2215 } else if (pageURI != this.prefetchedImgs[index].uri) {
2216 //console.log('uri changed for ' + index);
2221 //console.log('prefetching ' + index);
2222 var img = document.createElement("img");
2224 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2225 this.prefetchedImgs[index] = img;
2230 // prepareFlipLeftToRight()
2232 //______________________________________________________________________________
2234 // Prepare to flip the left page towards the right. This corresponds to moving
2235 // backward when the page progression is left to right.
2236 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2238 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2240 this.prefetchImg(prevL);
2241 this.prefetchImg(prevR);
2243 var height = this._getPageHeight(prevL);
2244 var width = this._getPageWidth(prevL);
2245 var middle = this.twoPage.middle;
2246 var top = this.twoPageTop();
2247 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2249 // The gutter is the dividing line between the left and right pages.
2250 // It is offset from the middle to create the illusion of thickness to the pages
2251 var gutter = middle + this.gutterOffsetForIndex(prevL);
2253 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2254 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2255 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2258 position: 'absolute',
2259 left: gutter-scaledW+'px',
2260 right: '', // clear right property
2262 height: this.twoPage.height,
2263 width: scaledW+'px',
2264 backgroundColor: this.getPageBackgroundColor(prevL),
2265 borderRight: '1px solid black',
2269 $(this.prefetchedImgs[prevL]).css(leftCSS);
2271 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2273 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2276 position: 'absolute',
2280 height: this.twoPage.height,
2282 backgroundColor: this.getPageBackgroundColor(prevR),
2283 borderLeft: '1px solid black',
2287 $(this.prefetchedImgs[prevR]).css(rightCSS);
2289 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2293 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2294 // prepareFlipRightToLeft()
2295 //______________________________________________________________________________
2296 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2298 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2301 this.prefetchImg(nextL);
2302 this.prefetchImg(nextR);
2304 var height = this._getPageHeight(nextR);
2305 var width = this._getPageWidth(nextR);
2306 var middle = this.twoPage.middle;
2307 var top = this.twoPageTop();
2308 var scaledW = this.twoPage.height*width/height;
2310 var gutter = middle + this.gutterOffsetForIndex(nextL);
2312 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2313 $(this.prefetchedImgs[nextR]).css({
2314 position: 'absolute',
2317 backgroundColor: this.getPageBackgroundColor(nextR),
2318 height: this.twoPage.height,
2319 width: scaledW+'px',
2320 borderLeft: '1px solid black',
2324 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2326 height = this._getPageHeight(nextL);
2327 width = this._getPageWidth(nextL);
2328 scaledW = this.twoPage.height*width/height;
2330 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2331 $(this.prefetchedImgs[nextL]).css({
2332 position: 'absolute',
2333 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2335 backgroundColor: this.getPageBackgroundColor(nextL),
2336 height: this.twoPage.height,
2337 width: 0+'px', // Start at 0 width, then grow to the left
2338 borderRight: '1px solid black',
2342 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2346 // getNextLeafs() -- NOT RTL AWARE
2347 //______________________________________________________________________________
2348 // BookReader.prototype.getNextLeafs = function(o) {
2349 // //TODO: we might have two left or two right leafs in a row (damaged book)
2350 // //For now, assume that leafs are contiguous.
2352 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2353 // o.L = this.twoPage.currentIndexL+2;
2354 // o.R = this.twoPage.currentIndexL+3;
2357 // getprevLeafs() -- NOT RTL AWARE
2358 //______________________________________________________________________________
2359 // BookReader.prototype.getPrevLeafs = function(o) {
2360 // //TODO: we might have two left or two right leafs in a row (damaged book)
2361 // //For now, assume that leafs are contiguous.
2363 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2364 // o.L = this.twoPage.currentIndexL-2;
2365 // o.R = this.twoPage.currentIndexL-1;
2368 // pruneUnusedImgs()
2369 //______________________________________________________________________________
2370 BookReader.prototype.pruneUnusedImgs = function() {
2371 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2372 for (var key in this.prefetchedImgs) {
2373 //console.log('key is ' + key);
2374 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2375 //console.log('removing key '+ key);
2376 $(this.prefetchedImgs[key]).remove();
2378 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2379 //console.log('deleting key '+ key);
2380 delete this.prefetchedImgs[key];
2386 //______________________________________________________________________________
2387 BookReader.prototype.prefetch = function() {
2389 // prefetch visible pages first
2390 this.prefetchImg(this.twoPage.currentIndexL);
2391 this.prefetchImg(this.twoPage.currentIndexR);
2393 var adjacentPagesToLoad = 3;
2395 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2396 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2398 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2399 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2401 // Load images spreading out from current
2402 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2403 var goingDown = lowCurrent - i;
2404 if (goingDown >= start) {
2405 this.prefetchImg(goingDown);
2407 var goingUp = highCurrent + i;
2408 if (goingUp <= end) {
2409 this.prefetchImg(goingUp);
2414 var lim = this.twoPage.currentIndexL-4;
2416 lim = Math.max(lim, 0);
2417 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2418 this.prefetchImg(i);
2421 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2422 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2423 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2424 this.prefetchImg(i);
2430 // getPageWidth2UP()
2431 //______________________________________________________________________________
2432 BookReader.prototype.getPageWidth2UP = function(index) {
2433 // We return the width based on the dominant height
2434 var height = this._getPageHeight(index);
2435 var width = this._getPageWidth(index);
2436 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2440 //______________________________________________________________________________
2441 BookReader.prototype.search = function(term) {
2442 term = term.replace(/\//g, ' '); // strip slashes
2443 this.searchTerm = term;
2444 $('#BookReaderSearchScript').remove();
2445 var script = document.createElement("script");
2446 script.setAttribute('id', 'BookReaderSearchScript');
2447 script.setAttribute("type", "text/javascript");
2448 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2449 document.getElementsByTagName('head')[0].appendChild(script);
2450 $('#BookReaderSearchBox').val(term);
2451 $('#BookReaderSearchResults').html('Searching...');
2454 // BRSearchCallback()
2455 //______________________________________________________________________________
2456 BookReader.prototype.BRSearchCallback = function(txt) {
2458 if (jQuery.browser.msie) {
2459 var dom=new ActiveXObject("Microsoft.XMLDOM");
2463 var parser = new DOMParser();
2464 var dom = parser.parseFromString(txt, "text/xml");
2467 $('#BookReaderSearchResults').empty();
2468 $('#BookReaderSearchResults').append('<ul>');
2470 for (var key in this.searchResults) {
2471 if (null != this.searchResults[key].div) {
2472 $(this.searchResults[key].div).remove();
2474 delete this.searchResults[key];
2477 var pages = dom.getElementsByTagName('PAGE');
2479 if (0 == pages.length) {
2480 // $$$ it would be nice to echo the (sanitized) search result here
2481 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2483 for (var i = 0; i < pages.length; i++){
2484 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2487 var re = new RegExp (/_(\d{4})\.djvu/);
2488 var reMatch = re.exec(pages[i].getAttribute('file'));
2489 var index = parseInt(reMatch[1], 10);
2490 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2492 var children = pages[i].childNodes;
2494 for (var j=0; j<children.length; j++) {
2495 //console.log(j + ' - ' + children[j].nodeName);
2496 //console.log(children[j].firstChild.nodeValue);
2497 if ('CONTEXT' == children[j].nodeName) {
2498 context += children[j].firstChild.nodeValue;
2499 } else if ('WORD' == children[j].nodeName) {
2500 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2502 var index = this.leafNumToIndex(index);
2503 if (null != index) {
2504 //coordinates are [left, bottom, right, top, [baseline]]
2505 //we'll skip baseline for now...
2506 var coords = children[j].getAttribute('coords').split(',',4);
2507 if (4 == coords.length) {
2508 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2513 var pageName = this.getPageName(index);
2514 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2515 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2516 //TODO: remove hardcoded instance name
2517 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2520 $('#BookReaderSearchResults').append('</ul>');
2522 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2523 $('#BookReaderSearchBox').val(this.searchTerm);
2525 this.updateSearchHilites();
2528 // updateSearchHilites()
2529 //______________________________________________________________________________
2530 BookReader.prototype.updateSearchHilites = function() {
2531 if (2 == this.mode) {
2532 this.updateSearchHilites2UP();
2534 this.updateSearchHilites1UP();
2538 // showSearchHilites1UP()
2539 //______________________________________________________________________________
2540 BookReader.prototype.updateSearchHilites1UP = function() {
2542 for (var key in this.searchResults) {
2544 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2545 var result = this.searchResults[key];
2546 if(null == result.div) {
2547 result.div = document.createElement('div');
2548 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2549 //console.log('appending ' + key);
2552 width: (result.r-result.l)/this.reduce + 'px',
2553 height: (result.b-result.t)/this.reduce + 'px',
2554 left: (result.l)/this.reduce + 'px',
2555 top: (result.t)/this.reduce +'px'
2559 //console.log(key + ' not displayed');
2560 this.searchResults[key].div=null;
2566 //______________________________________________________________________________
2567 // Returns the position of the gutter (line between the page images)
2568 BookReader.prototype.twoPageGutter = function() {
2569 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2573 //______________________________________________________________________________
2574 // Returns the offset for the top of the page images
2575 BookReader.prototype.twoPageTop = function() {
2576 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2579 // twoPageCoverWidth()
2580 //______________________________________________________________________________
2581 // Returns the width of the cover div given the total page width
2582 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2583 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2586 // twoPageGetViewCenter()
2587 //______________________________________________________________________________
2588 // Returns the percentage offset into twopageview div at the center of container div
2589 // { percentageX: float, percentageY: float }
2590 BookReader.prototype.twoPageGetViewCenter = function() {
2593 var containerOffset = $('#BRcontainer').offset();
2594 var viewOffset = $('#BRtwopageview').offset();
2595 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2596 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2601 // twoPageCenterView(percentageX, percentageY)
2602 //______________________________________________________________________________
2603 // Centers the point given by percentage from left,top of twopageview
2604 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2605 if ('undefined' == typeof(percentageX)) {
2608 if ('undefined' == typeof(percentageY)) {
2612 var viewWidth = $('#BRtwopageview').width();
2613 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2614 var intoViewX = percentageX * viewWidth;
2616 var viewHeight = $('#BRtwopageview').height();
2617 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2618 var intoViewY = percentageY * viewHeight;
2620 if (viewWidth < containerClientWidth) {
2621 // Can fit width without scrollbars - center by adjusting offset
2622 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2624 // Need to scroll to center
2625 $('#BRtwopageview').css('left', 0);
2626 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2629 if (viewHeight < containerClientHeight) {
2630 // Fits with scrollbars - add offset
2631 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2633 $('#BRtwopageview').css('top', 0);
2634 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2638 // twoPageFlipAreaHeight
2639 //______________________________________________________________________________
2640 // Returns the integer height of the click-to-flip areas at the edges of the book
2641 BookReader.prototype.twoPageFlipAreaHeight = function() {
2642 return parseInt(this.twoPage.height);
2645 // twoPageFlipAreaWidth
2646 //______________________________________________________________________________
2647 // Returns the integer width of the flip areas
2648 BookReader.prototype.twoPageFlipAreaWidth = function() {
2649 var max = 100; // $$$ TODO base on view width?
2652 var width = this.twoPage.width * 0.15;
2653 return parseInt(BookReader.util.clamp(width, min, max));
2656 // twoPageFlipAreaTop
2657 //______________________________________________________________________________
2658 // Returns integer top offset for flip areas
2659 BookReader.prototype.twoPageFlipAreaTop = function() {
2660 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2663 // twoPageLeftFlipAreaLeft
2664 //______________________________________________________________________________
2665 // Left offset for left flip area
2666 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2667 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2670 // twoPageRightFlipAreaLeft
2671 //______________________________________________________________________________
2672 // Left offset for right flip area
2673 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2674 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2677 // twoPagePlaceFlipAreas
2678 //______________________________________________________________________________
2679 // Readjusts position of flip areas based on current layout
2680 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2681 // We don't set top since it shouldn't change relative to view
2682 $(this.twoPage.leftFlipArea).css({
2683 left: this.twoPageLeftFlipAreaLeft() + 'px',
2684 width: this.twoPageFlipAreaWidth() + 'px'
2686 $(this.twoPage.rightFlipArea).css({
2687 left: this.twoPageRightFlipAreaLeft() + 'px',
2688 width: this.twoPageFlipAreaWidth() + 'px'
2692 // showSearchHilites2UP()
2693 //______________________________________________________________________________
2694 BookReader.prototype.updateSearchHilites2UP = function() {
2696 for (var key in this.searchResults) {
2697 key = parseInt(key, 10);
2698 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2699 var result = this.searchResults[key];
2700 if(null == result.div) {
2701 result.div = document.createElement('div');
2702 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2703 //console.log('appending ' + key);
2706 // We calculate the reduction factor for the specific page because it can be different
2707 // for each page in the spread
2708 var height = this._getPageHeight(key);
2709 var width = this._getPageWidth(key)
2710 var reduce = this.twoPage.height/height;
2711 var scaledW = parseInt(width*reduce);
2713 var gutter = this.twoPageGutter();
2715 if ('L' == this.getPageSide(key)) {
2716 pageL = gutter-scaledW;
2720 var pageT = this.twoPageTop();
2723 width: (result.r-result.l)*reduce + 'px',
2724 height: (result.b-result.t)*reduce + 'px',
2725 left: pageL+(result.l)*reduce + 'px',
2726 top: pageT+(result.t)*reduce +'px'
2730 //console.log(key + ' not displayed');
2731 if (null != this.searchResults[key].div) {
2732 //console.log('removing ' + key);
2733 $(this.searchResults[key].div).remove();
2735 this.searchResults[key].div=null;
2740 // removeSearchHilites()
2741 //______________________________________________________________________________
2742 BookReader.prototype.removeSearchHilites = function() {
2743 for (var key in this.searchResults) {
2744 if (null != this.searchResults[key].div) {
2745 $(this.searchResults[key].div).remove();
2746 this.searchResults[key].div=null;
2752 //______________________________________________________________________________
2753 BookReader.prototype.printPage = function() {
2754 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2756 /* iframe implementation
2758 if (null != this.printPopup) { // check if already showing
2761 this.printPopup = document.createElement("div");
2762 $(this.printPopup).css({
2763 position: 'absolute',
2765 left: ($('#BRcontainer').width()-400)/2 + 'px',
2768 border: "3px double #999999",
2770 backgroundColor: "#fff"
2771 }).appendTo('#BookReader');
2774 if (this.constMode1up == this.mode) {
2775 indexToPrint = this.firstIndex;
2777 indexToPrint = this.twoPage.currentIndexL;
2780 this.indexToPrint = indexToPrint;
2782 var htmlStr = '<div style="text-align: center;">';
2783 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>';
2784 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2785 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2786 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2787 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2788 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2790 htmlStr += '</div>';
2791 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2792 htmlStr += '</div>';
2794 this.printPopup.innerHTML = htmlStr;
2796 var iframe = document.createElement('iframe');
2797 iframe.id = 'printFrame';
2798 iframe.name = 'printFrame';
2799 iframe.width = '233px'; // 8.5 x 11 aspect
2800 iframe.height = '300px';
2802 var self = this; // closure
2804 $(iframe).load(function() {
2805 var doc = BookReader.util.getIFrameDocument(this);
2806 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2809 $('#printDiv').prepend(iframe);
2813 // Get print URI from current indices and mode
2814 BookReader.prototype.getPrintURI = function() {
2816 if (this.constMode2up == this.mode) {
2817 indexToPrint = this.twoPage.currentIndexL;
2819 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2822 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2823 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2824 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2826 if (this.constMode2up == this.mode) {
2827 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2828 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2829 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2831 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2834 return '/bookreader/print.php?' + options;
2837 /* iframe implementation
2838 BookReader.prototype.getPrintFrameContent = function(index) {
2839 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2840 // 8.5x11 so we should end up not overflowing on either paper size.
2841 var paperAspect = 8.5 / 11;
2842 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2846 // Rotate if possible and appropriate, to get larger image size on printed page
2847 if (this.canRotatePage(index)) {
2848 if (imageAspect > 1 && imageAspect > paperAspect) {
2849 // more wide than square, and more wide than paper
2851 imageAspect = 1/imageAspect;
2856 if (imageAspect > paperAspect) {
2857 // wider than paper, fit width
2858 fitAttrs = 'width="95%"';
2860 // taller than paper, fit height
2861 fitAttrs = 'height="95%"';
2864 var imageURL = this._getPageURI(index, 1, rotate);
2865 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2866 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2867 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2868 iframeStr += '</div>';
2869 iframeStr += '</body></html>';
2874 BookReader.prototype.updatePrintFrame = function(delta) {
2875 var newIndex = this.indexToPrint + delta;
2876 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2877 if (newIndex == this.indexToPrint) {
2880 this.indexToPrint = newIndex;
2881 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2882 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2887 //______________________________________________________________________________
2888 BookReader.prototype.showEmbedCode = function() {
2889 if (null != this.embedPopup) { // check if already showing
2893 this.embedPopup = document.createElement("div");
2894 $(this.embedPopup).css({
2895 position: 'absolute',
2897 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2900 border: "3px double #999999",
2902 backgroundColor: "#fff"
2903 }).appendTo('#BookReader');
2905 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2906 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>';
2907 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2908 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2910 this.embedPopup.innerHTML = htmlStr;
2911 $(this.embedPopup).find('input').bind('click', function() {
2917 //______________________________________________________________________________
2918 BookReader.prototype.autoToggle = function() {
2920 var bComingFrom1up = false;
2921 if (2 != this.mode) {
2922 bComingFrom1up = true;
2926 // Change to autofit if book is too large
2927 if (this.reduce < this.twoPageGetAutofitReduce()) {
2932 if (null == this.autoTimer) {
2933 this.flipSpeed = 2000;
2935 // $$$ Draw events currently cause layout problems when they occur during animation.
2936 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2937 // we workaround for now by not triggering immediate animation in that case.
2938 // See https://bugs.launchpad.net/gnubook/+bug/328327
2939 if (('rl' == this.pageProgression) && bComingFrom1up) {
2940 // don't flip immediately -- wait until timer fires
2943 this.flipFwdToIndex();
2946 $('#BRtoolbar .play').hide();
2947 $('#BRtoolbar .pause').show();
2948 this.autoTimer=setInterval(function(){
2949 if (self.animating) {return;}
2951 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2952 self.flipBackToIndex(1); // $$$ really what we want?
2954 self.flipFwdToIndex();
2963 //______________________________________________________________________________
2964 // Stop autoplay mode, allowing animations to finish
2965 BookReader.prototype.autoStop = function() {
2966 if (null != this.autoTimer) {
2967 clearInterval(this.autoTimer);
2968 this.flipSpeed = 'fast';
2969 $('#BRtoolbar .pause').hide();
2970 $('#BRtoolbar .play').show();
2971 this.autoTimer = null;
2975 // stopFlipAnimations
2976 //______________________________________________________________________________
2977 // Immediately stop flip animations. Callbacks are triggered.
2978 BookReader.prototype.stopFlipAnimations = function() {
2980 this.autoStop(); // Clear timers
2982 // Stop animation, clear queue, trigger callbacks
2983 if (this.leafEdgeTmp) {
2984 $(this.leafEdgeTmp).stop(false, true);
2986 jQuery.each(this.prefetchedImgs, function() {
2987 $(this).stop(false, true);
2990 // And again since animations also queued in callbacks
2991 if (this.leafEdgeTmp) {
2992 $(this.leafEdgeTmp).stop(false, true);
2994 jQuery.each(this.prefetchedImgs, function() {
2995 $(this).stop(false, true);
3000 // keyboardNavigationIsDisabled(event)
3001 // - returns true if keyboard navigation should be disabled for the event
3002 //______________________________________________________________________________
3003 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3004 if (event.target.tagName == "INPUT") {
3010 // gutterOffsetForIndex
3011 //______________________________________________________________________________
3013 // Returns the gutter offset for the spread containing the given index.
3014 // This function supports RTL
3015 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3017 // To find the offset of the gutter from the middle we calculate our percentage distance
3018 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3019 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3021 // But then again for RTL it's the opposite
3022 if ('rl' == this.pageProgression) {
3030 //______________________________________________________________________________
3031 // Returns the width of the leaf edge div for the page with index given
3032 BookReader.prototype.leafEdgeWidth = function(pindex) {
3033 // $$$ could there be single pixel rounding errors for L vs R?
3034 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3035 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3037 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3041 // jumpIndexForLeftEdgePageX
3042 //______________________________________________________________________________
3043 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3044 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3045 if ('rl' != this.pageProgression) {
3046 // LTR - flipping backward
3047 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3049 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3050 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3054 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3055 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3060 // jumpIndexForRightEdgePageX
3061 //______________________________________________________________________________
3062 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3063 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3064 if ('rl' != this.pageProgression) {
3066 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3067 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3070 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3071 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3076 BookReader.prototype.initToolbar = function(mode, ui) {
3078 $("#BookReader").append("<div id='BRtoolbar'>"
3079 + "<span id='BRtoolbarbuttons' style='float: right'>"
3080 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3081 + "<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>"
3082 + "<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>"
3083 + "<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>"
3084 + "<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>"
3085 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3089 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3090 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3091 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3092 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3093 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3094 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3095 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3098 + "<span id='#BRbooktitle'>"
3099 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3103 this.updateToolbarZoom(this.reduce); // Pretty format
3105 if (ui == "embed") {
3106 $("#BookReader a.logo").attr("target","_blank");
3109 // $$$ turn this into a member variable
3110 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3112 // We build in mode 2
3115 this.bindToolbarNavHandlers(jToolbar);
3117 // Setup tooltips -- later we could load these from a file for i18n
3118 var titles = { '.logo': 'Go to Archive.org',
3119 '.zoom_in': 'Zoom in',
3120 '.zoom_out': 'Zoom out',
3121 '.one_page_mode': 'One-page view',
3122 '.two_page_mode': 'Two-page view',
3123 '.thumbnail_mode': 'Thumbnail view',
3124 '.print': 'Print this page',
3125 '.embed': 'Embed bookreader',
3126 '.book_left': 'Flip left',
3127 '.book_right': 'Flip right',
3128 '.book_up': 'Page up',
3129 '.book_down': 'Page down',
3132 '.book_top': 'First page',
3133 '.book_bottom': 'Last page'
3135 if ('rl' == this.pageProgression) {
3136 titles['.book_leftmost'] = 'Last page';
3137 titles['.book_rightmost'] = 'First page';
3139 titles['.book_leftmost'] = 'First page';
3140 titles['.book_rightmost'] = 'Last page';
3143 for (var icon in titles) {
3144 jToolbar.find(icon).attr('title', titles[icon]);
3147 // Hide mode buttons and autoplay if 2up is not available
3148 // $$$ if we end up with more than two modes we should show the applicable buttons
3149 if ( !this.canSwitchToMode(this.constMode2up) ) {
3150 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3153 // Switch to requested mode -- binds other click handlers
3154 this.switchToolbarMode(mode);
3159 // switchToolbarMode
3160 //______________________________________________________________________________
3161 // Update the toolbar for the given mode (changes navigation buttons)
3162 // $$$ we should soon split the toolbar out into its own module
3163 BookReader.prototype.switchToolbarMode = function(mode) {
3166 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3167 $('#BRtoolbar .BRtoolbarmode2').hide();
3168 $('#BRtoolbar .BRtoolbarmode3').hide();
3169 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3170 } else if (2 == mode) {
3172 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3173 $('#BRtoolbar .BRtoolbarmode1').hide();
3174 $('#BRtoolbar .BRtoolbarmode3').hide();
3175 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3178 $('#BRtoolbar .BRtoolbarzoom').hide();
3179 $('#BRtoolbar .BRtoolbarmode2').hide();
3180 $('#BRtoolbar .BRtoolbarmode1').hide();
3181 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3185 // bindToolbarNavHandlers
3186 //______________________________________________________________________________
3187 // Binds the toolbar handlers
3188 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3190 var self = this; // closure
3192 jToolbar.find('.book_left').bind('click', function(e) {
3197 jToolbar.find('.book_right').bind('click', function(e) {
3202 jToolbar.find('.book_up').bind('click', function(e) {
3203 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3211 jToolbar.find('.book_down').bind('click', function(e) {
3212 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb])) {
3220 jToolbar.find('.print').bind('click', function(e) {
3225 jToolbar.find('.embed').bind('click', function(e) {
3226 self.showEmbedCode();
3230 jToolbar.find('.play').bind('click', function(e) {
3235 jToolbar.find('.pause').bind('click', function(e) {
3240 jToolbar.find('.book_top').bind('click', function(e) {
3245 jToolbar.find('.book_bottom').bind('click', function(e) {
3250 jToolbar.find('.book_leftmost').bind('click', function(e) {
3255 jToolbar.find('.book_rightmost').bind('click', function(e) {
3261 // updateToolbarZoom(reduce)
3262 //______________________________________________________________________________
3263 // Update the displayed zoom factor based on reduction factor
3264 BookReader.prototype.updateToolbarZoom = function(reduce) {
3266 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3269 value = (100 / reduce).toFixed(2);
3270 // Strip trailing zeroes and decimal if all zeroes
3271 value = value.replace(/0+$/,'');
3272 value = value.replace(/\.$/,'');
3275 $('#BRzoom').text(value);
3278 // firstDisplayableIndex
3279 //______________________________________________________________________________
3280 // Returns the index of the first visible page, dependent on the mode.
3281 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3282 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3283 BookReader.prototype.firstDisplayableIndex = function() {
3284 if (this.mode != this.constMode2up) {
3288 if ('rl' != this.pageProgression) {
3290 if (this.getPageSide(0) == 'L') {
3297 if (this.getPageSide(0) == 'R') {
3305 // lastDisplayableIndex
3306 //______________________________________________________________________________
3307 // Returns the index of the last visible page, dependent on the mode.
3308 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3309 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3310 BookReader.prototype.lastDisplayableIndex = function() {
3312 var lastIndex = this.numLeafs - 1;
3314 if (this.mode != this.constMode2up) {
3318 if ('rl' != this.pageProgression) {
3320 if (this.getPageSide(lastIndex) == 'R') {
3323 return lastIndex + 1;
3327 if (this.getPageSide(lastIndex) == 'L') {
3330 return lastIndex + 1;
3335 // shortTitle(maximumCharacters)
3337 // Returns a shortened version of the title with the maximum number of characters
3338 BookReader.prototype.shortTitle = function(maximumCharacters) {
3339 if (this.bookTitle.length < maximumCharacters) {
3340 return this.bookTitle;
3343 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3348 // Parameter related functions
3350 // updateFromParams(params)
3352 // Update ourselves from the params object.
3354 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3355 BookReader.prototype.updateFromParams = function(params) {
3356 if ('undefined' != typeof(params.mode)) {
3357 this.switchMode(params.mode);
3361 if ('undefined' != typeof(params.searchTerm)) {
3362 if (this.searchTerm != params.searchTerm) {
3363 this.search(params.searchTerm);
3367 // $$$ process /zoom
3369 // We only respect page if index is not set
3370 if ('undefined' != typeof(params.index)) {
3371 if (params.index != this.currentIndex()) {
3372 this.jumpToIndex(params.index);
3374 } else if ('undefined' != typeof(params.page)) {
3375 // $$$ this assumes page numbers are unique
3376 if (params.page != this.getPageNum(this.currentIndex())) {
3377 this.jumpToPage(params.page);
3381 // $$$ process /region
3382 // $$$ process /highlight
3385 // paramsFromFragment(urlFragment)
3387 // Returns a object with configuration parametes from a URL fragment.
3389 // E.g paramsFromFragment(window.location.hash)
3390 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3391 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3395 // For convenience we allow an initial # character (as from window.location.hash)
3396 // but don't require it
3397 if (urlFragment.substr(0,1) == '#') {
3398 urlFragment = urlFragment.substr(1);
3401 // Simple #nn syntax
3402 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3403 if ( !isNaN(oldStyleLeafNum) ) {
3404 params.index = oldStyleLeafNum;
3406 // Done processing if using old-style syntax
3410 // Split into key-value pairs
3411 var urlArray = urlFragment.split('/');
3413 for (var i = 0; i < urlArray.length; i += 2) {
3414 urlHash[urlArray[i]] = urlArray[i+1];
3418 if ('1up' == urlHash['mode']) {
3419 params.mode = this.constMode1up;
3420 } else if ('2up' == urlHash['mode']) {
3421 params.mode = this.constMode2up;
3422 } else if ('thumb' == urlHash['mode']) {
3423 params.mode = this.constModeThumb;
3427 if ('undefined' != typeof(urlHash['page'])) {
3428 // page was set -- may not be int
3429 params.page = urlHash['page'];
3432 // $$$ process /region
3433 // $$$ process /search
3435 if (urlHash['search'] != undefined) {
3436 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3439 // $$$ process /highlight
3444 // paramsFromCurrent()
3446 // Create a params object from the current parameters.
3447 BookReader.prototype.paramsFromCurrent = function() {
3451 var index = this.currentIndex();
3452 var pageNum = this.getPageNum(index);
3453 if ((pageNum === 0) || pageNum) {
3454 params.page = pageNum;
3457 params.index = index;
3458 params.mode = this.mode;
3464 if (this.searchHighlightVisible()) {
3465 params.searchTerm = this.searchTerm;
3471 // fragmentFromParams(params)
3473 // Create a fragment string from the params object.
3474 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3475 BookReader.prototype.fragmentFromParams = function(params) {
3476 var separator = '/';
3480 if ('undefined' != typeof(params.page)) {
3481 fragments.push('page', params.page);
3483 // Don't have page numbering -- use index instead
3484 fragments.push('page', 'n' + params.index);
3491 if ('undefined' != typeof(params.mode)) {
3492 if (params.mode == this.constMode1up) {
3493 fragments.push('mode', '1up');
3494 } else if (params.mode == this.constMode2up) {
3495 fragments.push('mode', '2up');
3496 } else if (params.mode == this.constModeThumb) {
3497 fragments.push('mode', 'thumb');
3499 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3504 if (params.searchTerm) {
3505 fragments.push('search', params.searchTerm);
3508 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3511 // getPageIndex(pageNum)
3513 // Returns the *highest* index the given page number, or undefined
3514 BookReader.prototype.getPageIndex = function(pageNum) {
3515 var pageIndices = this.getPageIndices(pageNum);
3517 if (pageIndices.length > 0) {
3518 return pageIndices[pageIndices.length - 1];
3524 // getPageIndices(pageNum)
3526 // Returns an array (possibly empty) of the indices with the given page number
3527 BookReader.prototype.getPageIndices = function(pageNum) {
3530 // Check for special "nXX" page number
3531 if (pageNum.slice(0,1) == 'n') {
3533 var pageIntStr = pageNum.slice(1, pageNum.length);
3534 var pageIndex = parseInt(pageIntStr);
3535 indices.push(pageIndex);
3538 // Do nothing... will run through page names and see if one matches
3543 for (i=0; i<this.numLeafs; i++) {
3544 if (this.getPageNum(i) == pageNum) {
3552 // getPageName(index)
3554 // Returns the name of the page as it should be displayed in the user interface
3555 BookReader.prototype.getPageName = function(index) {
3556 return 'Page ' + this.getPageNum(index);
3559 // updateLocationHash
3561 // Update the location hash from the current parameters. Call this instead of manually
3562 // using window.location.replace
3563 BookReader.prototype.updateLocationHash = function() {
3564 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3565 window.location.replace(newHash);
3567 // This is the variable checked in the timer. Only user-generated changes
3568 // to the URL will trigger the event.
3569 this.oldLocationHash = newHash;
3572 // startLocationPolling
3574 // Starts polling of window.location to see hash fragment changes
3575 BookReader.prototype.startLocationPolling = function() {
3576 var self = this; // remember who I am
3577 self.oldLocationHash = window.location.hash;
3579 if (this.locationPollId) {
3580 clearInterval(this.locationPollID);
3581 this.locationPollId = null;
3584 this.locationPollId = setInterval(function() {
3585 var newHash = window.location.hash;
3586 if (newHash != self.oldLocationHash) {
3587 if (newHash != self.oldUserHash) { // Only process new user hash once
3588 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3590 // Queue change if animating
3591 if (self.animating) {
3593 self.animationFinishedCallback = function() {
3594 self.updateFromParams(self.paramsFromFragment(newHash));
3596 } else { // update immediately
3597 self.updateFromParams(self.paramsFromFragment(newHash));
3599 self.oldUserHash = newHash;
3607 // Returns true if we can switch to the requested mode
3608 BookReader.prototype.canSwitchToMode = function(mode) {
3609 if (mode == this.constMode2up) {
3610 // check there are enough pages to display
3611 // $$$ this is a workaround for the mis-feature that we can't display
3612 // short books in 2up mode
3613 if (this.numLeafs < 6) {
3621 // searchHighlightVisible
3623 // Returns true if a search highlight is currently being displayed
3624 BookReader.prototype.searchHighlightVisible = function() {
3625 if (this.constMode2up == this.mode) {
3626 if (this.searchResults[this.twoPage.currentIndexL]
3627 || this.searchResults[this.twoPage.currentIndexR]) {
3631 if (this.searchResults[this.currentIndex()]) {
3638 // getPageBackgroundColor
3640 // Returns a CSS property string for the background color for the given page
3641 // $$$ turn into regular CSS?
3642 BookReader.prototype.getPageBackgroundColor = function(index) {
3643 if (index >= 0 && index < this.numLeafs) {
3645 return this.pageDefaultBackgroundColor;
3653 // Returns the page width for the given index, or first or last page if out of range
3654 BookReader.prototype._getPageWidth = function(index) {
3655 // Synthesize a page width for pages not actually present in book.
3656 // May or may not be the best approach.
3657 // If index is out of range we return the width of first or last page
3658 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3659 return this.getPageWidth(index);
3664 // Returns the page height for the given index, or first or last page if out of range
3665 BookReader.prototype._getPageHeight= function(index) {
3666 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3667 return this.getPageHeight(index);
3672 // Returns the page URI or transparent image if out of range
3673 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3674 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3675 return this.imagesBaseURL + "/transparent.png";
3678 if ('undefined' == typeof(reduce)) {
3679 // reduce not passed in
3680 // $$$ this probably won't work for thumbnail mode
3681 var ratio = this.getPageHeight(index) / this.twoPage.height;
3683 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3686 } else if (ratio < 4) {
3688 } else if (ratio < 8) {
3690 } else if (ratio < 16) {
3692 } else if (ratio < 32) {
3700 return this.getPageURI(index, reduce, rotate);
3703 // Library functions
3705 disableSelect: function(jObject) {
3706 // Bind mouse handlers
3707 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3708 jObject.bind('mousedown', function(e) {
3709 // $$$ check here for right-click and don't disable. Also use jQuery style
3710 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3713 // Special hack for IE7
3714 jObject[0].onselectstart = function(e) { return false; };
3717 clamp: function(value, min, max) {
3718 return Math.min(Math.max(value, min), max);
3721 getIFrameDocument: function(iframe) {
3722 // Adapted from http://xkr.us/articles/dom/iframe-document/
3723 var outer = (iframe.contentWindow || iframe.contentDocument);
3724 return (outer.document || outer);
3727 decodeURIComponentPlus: function(value) {
3728 // Decodes a URI component and converts '+' to ' '
3729 return decodeURIComponent(value).replace(/\+/g, ' ');
3732 encodeURIComponentPlus: function(value) {
3733 // Encodes a URI component and converts ' ' to '+'
3734 return encodeURIComponent(value).replace(/%20/g, '+');
3736 // The final property here must NOT have a comma after it - IE7