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 = 2; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.thumbMaxLoading = 4; // number of thumbnails to load at once
49 this.displayedRows=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
88 // Object to hold parameters related to 2up mode
90 coverInternalPadding: 10, // Width of cover
91 coverExternalPadding: 10, // Padding outside of cover
92 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
96 // Background color for pages (e.g. when loading page image)
97 // $$$ TODO dynamically calculate based on page images
98 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
104 //______________________________________________________________________________
105 BookReader.prototype.init = function() {
107 var startIndex = undefined;
108 this.pageScale = this.reduce; // preserve current reduce
110 // Find start index and mode if set in location hash
111 var params = this.paramsFromFragment(window.location.hash);
113 if ('undefined' != typeof(params.index)) {
114 startIndex = params.index;
115 } else if ('undefined' != typeof(params.page)) {
116 startIndex = this.getPageIndex(params.page);
119 if ('undefined' == typeof(startIndex)) {
120 if ('undefined' != typeof(this.titleLeaf)) {
121 startIndex = this.leafNumToIndex(this.titleLeaf);
125 if ('undefined' == typeof(startIndex)) {
129 if ('undefined' != typeof(params.mode)) {
130 this.mode = params.mode;
133 // Set document title -- may have already been set in enclosing html for
134 // search engine visibility
135 document.title = this.shortTitle(50);
137 // Sanitize parameters
138 if ( !this.canSwitchToMode( this.mode ) ) {
139 this.mode = this.constMode1up;
142 $("#BookReader").empty();
143 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
144 $("#BookReader").append("<div id='BRcontainer'></div>");
145 $("#BRcontainer").append("<div id='BRpageview'></div>");
147 $("#BRcontainer").bind('scroll', this, function(e) {
151 this.setupKeyListeners();
152 this.startLocationPolling();
154 $(window).bind('resize', this, function(e) {
155 //console.log('resize!');
156 if (1 == e.data.mode) {
157 //console.log('centering 1page view');
158 e.data.centerPageView();
159 $('#BRpageview').empty()
160 e.data.displayedIndices = [];
161 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
163 } else if (3 == e.data.mode){
164 e.data.prepareThumbnailView();
166 //console.log('drawing 2 page view');
168 // We only need to prepare again in autofit (size of spread changes)
169 if (e.data.twoPage.autofit) {
170 e.data.prepareTwoPageView();
172 // Re-center if the scrollbars have disappeared
173 var center = e.data.twoPageGetViewCenter();
174 var doRecenter = false;
175 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
176 center.percentageX = 0.5;
179 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
180 center.percentageY = 0.5;
184 e.data.twoPageCenterView(center.percentageX, center.percentageY);
190 $('.BRpagediv1up').bind('mousedown', this, function(e) {
191 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
192 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
196 // $$$ refactor this so it's enough to set the first index and call preparePageView
197 // (get rid of mode-specific logic at this point)
198 if (1 == this.mode) {
199 this.resizePageView();
200 this.firstIndex = startIndex;
201 this.jumpToIndex(startIndex);
202 } else if (3 == this.mode) {
203 this.firstIndex = startIndex;
204 this.prepareThumbnailView();
205 this.jumpToIndex(startIndex);
207 //this.resizePageView();
209 this.displayedIndices=[0];
210 this.firstIndex = startIndex;
211 this.displayedIndices = [this.firstIndex];
212 //console.log('titleLeaf: %d', this.titleLeaf);
213 //console.log('displayedIndices: %s', this.displayedIndices);
214 this.prepareTwoPageView();
217 // Enact other parts of initial params
218 this.updateFromParams(params);
221 BookReader.prototype.setupKeyListeners = function() {
234 // We use document here instead of window to avoid a bug in jQuery on IE7
235 $(document).keydown(function(e) {
237 // Keyboard navigation
238 if (!self.keyboardNavigationIsDisabled(e)) {
242 // In 1up mode page scrolling is handled by browser
243 if (2 == self.mode) {
250 if (2 == self.mode) {
264 if (2 == self.mode) {
270 if (2 == self.mode) {
281 //______________________________________________________________________________
282 BookReader.prototype.drawLeafs = function() {
283 if (1 == this.mode) {
284 this.drawLeafsOnePage();
285 } else if (3 == this.mode) {
286 this.drawLeafsThumbnail();
288 this.drawLeafsTwoPage();
294 //______________________________________________________________________________
295 BookReader.prototype.setDragHandler = function(div) {
296 div.dragging = false;
298 $(div).unbind('mousedown').bind('mousedown', function(e) {
301 //console.log('mousedown at ' + e.pageY);
303 this.dragging = true;
304 this.prevMouseX = e.pageX;
305 this.prevMouseY = e.pageY;
307 var startX = e.pageX;
308 var startY = e.pageY;
309 var startTop = $('#BRcontainer').attr('scrollTop');
310 var startLeft = $('#BRcontainer').attr('scrollLeft');
314 $(div).unbind('mousemove').bind('mousemove', function(ee) {
317 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
319 var offsetX = ee.pageX - this.prevMouseX;
320 var offsetY = ee.pageY - this.prevMouseY;
323 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
324 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
327 this.prevMouseX = ee.pageX;
328 this.prevMouseY = ee.pageY;
332 $(div).unbind('mouseup').bind('mouseup', function(ee) {
334 //console.log('mouseup');
336 this.dragging = false;
339 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
341 //console.log('mouseleave');
343 this.dragging = false;
346 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
348 //console.log('mouseenter');
350 this.dragging = false;
354 // setDragHandler2UP()
355 //______________________________________________________________________________
356 BookReader.prototype.setDragHandler2UP = function(div) {
357 div.dragging = false;
359 $(div).unbind('mousedown').bind('mousedown', function(e) {
362 //console.log('mousedown at ' + e.pageY);
364 this.dragStart = {x: e.pageX, y: e.pageY };
365 this.mouseDown = true;
366 this.dragging = false; // wait until drag distance
367 this.prevMouseX = e.pageX;
368 this.prevMouseY = e.pageY;
370 var startX = e.pageX;
371 var startY = e.pageY;
372 var startTop = $('#BRcontainer').attr('scrollTop');
373 var startLeft = $('#BRcontainer').attr('scrollLeft');
377 $(div).unbind('mousemove').bind('mousemove', function(ee) {
380 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
382 var offsetX = ee.pageX - this.prevMouseX;
383 var offsetY = ee.pageY - this.prevMouseY;
385 var minDragDistance = 5; // $$$ constant
387 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
389 if (this.mouseDown && (distance > minDragDistance)) {
390 //console.log('drag start!');
392 this.dragging = true;
396 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
397 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
398 this.prevMouseX = ee.pageX;
399 this.prevMouseY = ee.pageY;
406 $(div).unbind('mouseup').bind('mouseup', function(ee) {
408 //console.log('mouseup');
410 this.dragging = false;
411 this.mouseDown = false;
416 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
418 //console.log('mouseleave');
420 this.dragging = false;
421 this.mouseDown = false;
424 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
426 //console.log('mouseenter');
428 this.dragging = false;
429 this.mouseDown = false;
433 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
434 //console.log('setting handler');
435 //console.log(element.tagName);
437 $(element).unbind('click').bind('click', data, function(e) {
440 //console.log('click!');
442 if (this.mouseDown && (!this.dragging)) {
443 //console.log('click not dragging!');
447 this.dragging = false;
448 this.mouseDown = false;
452 // drawLeafsOnePage()
453 //______________________________________________________________________________
454 BookReader.prototype.drawLeafsOnePage = function() {
455 //alert('drawing leafs!');
459 var scrollTop = $('#BRcontainer').attr('scrollTop');
460 var scrollBottom = scrollTop + $('#BRcontainer').height();
461 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
463 var indicesToDisplay = [];
468 for (i=0; i<this.numLeafs; i++) {
469 var height = parseInt(this._getPageHeight(i)/this.reduce);
471 leafBottom += height;
472 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
473 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
474 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
475 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
476 if (topInView | bottomInView | middleInView) {
477 //console.log('displayed: ' + this.displayedIndices);
478 //console.log('to display: ' + i);
479 indicesToDisplay.push(i);
481 leafTop += height +10;
485 var firstIndexToDraw = indicesToDisplay[0];
486 this.firstIndex = firstIndexToDraw;
488 // Update hash, but only if we're currently displaying a leaf
489 // Hack that fixes #365790
490 if (this.displayedIndices.length > 0) {
491 this.updateLocationHash();
494 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
496 indicesToDisplay.unshift(firstIndexToDraw);
499 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
500 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
501 indicesToDisplay.push(lastIndexToDraw+1);
506 for (i=0; i<firstIndexToDraw; i++) {
507 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
510 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
511 var viewWidth = $('#BRcontainer').attr('scrollWidth');
514 for (i=0; i<indicesToDisplay.length; i++) {
515 var index = indicesToDisplay[i];
516 var height = parseInt(this._getPageHeight(index)/this.reduce);
518 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
519 var width = parseInt(this._getPageWidth(index)/this.reduce);
520 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
521 var div = document.createElement("div");
522 div.className = 'BRpagediv1up';
523 div.id = 'pagediv'+index;
524 div.style.position = "absolute";
525 $(div).css('top', leafTop + 'px');
526 var left = (viewWidth-width)>>1;
527 if (left<0) left = 0;
528 $(div).css('left', left+'px');
529 $(div).css('width', width+'px');
530 $(div).css('height', height+'px');
531 //$(div).text('loading...');
533 this.setDragHandler(div);
535 $('#BRpageview').append(div);
537 var img = document.createElement("img");
538 img.src = this._getPageURI(index, this.reduce, 0);
539 $(img).css('width', width+'px');
540 $(img).css('height', height+'px');
544 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
547 leafTop += height +10;
551 for (i=0; i<this.displayedIndices.length; i++) {
552 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
553 var index = this.displayedIndices[i];
554 //console.log('Removing leaf ' + index);
555 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
556 $('#pagediv'+index).remove();
558 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
562 this.displayedIndices = indicesToDisplay.slice();
563 this.updateSearchHilites();
565 if (null != this.getPageNum(firstIndexToDraw)) {
566 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
568 $("#BRpagenum").val('');
571 this.updateToolbarZoom(this.reduce);
575 // drawLeafsThumbnail()
576 //______________________________________________________________________________
577 BookReader.prototype.drawLeafsThumbnail = function() {
578 //alert('drawing leafs!');
581 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
583 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
597 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
598 for (i=0; i<this.numLeafs; i++) {
599 leafWidth = this.thumbWidth;
600 if (rightPos + (leafWidth + this.padding) > viewWidth){
606 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
607 if (leafMap[currentRow].leafs===undefined) {
608 leafMap[currentRow].leafs = [];
609 leafMap[currentRow].height = 0;
610 leafMap[currentRow].top = 0;
612 leafMap[currentRow].leafs[leafIndex] = {};
613 leafMap[currentRow].leafs[leafIndex].num = i;
614 leafMap[currentRow].leafs[leafIndex].left = rightPos;
616 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
617 if (leafHeight > leafMap[currentRow].height) {
618 leafMap[currentRow].height = leafHeight;
620 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
621 rightPos += leafWidth + this.padding;
622 if (rightPos > maxRight) { maxRight = rightPos; }
626 // reset the bottom position based on thumbnails
627 $('#BRpageview').height(bottomPos);
629 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
630 var scrollTop = $('#BRcontainer').attr('scrollTop');
631 var scrollBottom = scrollTop + $('#BRcontainer').height();
635 var rowsToDisplay = [];
637 // Determine the thumbnails in view
638 for (i=0; i<leafMap.length; i++) {
639 leafBottom += this.padding + leafMap[i].height;
640 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
641 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
642 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
643 if (topInView | bottomInView | middleInView) {
644 //console.log('row to display: ' + j);
645 rowsToDisplay.push(i);
647 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
648 leafTop = leafBottom;
651 // create a buffer of preloaded rows before and after the visible rows
652 var firstRow = rowsToDisplay[0];
653 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
654 for (i=1; i<this.thumbRowBuffer+1; i++) {
655 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
657 for (i=1; i<this.thumbRowBuffer+1; i++) {
658 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
661 // Update hash, but only if we're currently displaying a leaf
662 // Hack that fixes #365790
663 if (this.displayedRows.length > 0) {
664 this.updateLocationHash();
667 // Create the thumbnail divs and images (lazy loaded)
676 for (i=0; i<rowsToDisplay.length; i++) {
677 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
678 row = rowsToDisplay[i];
680 for (j=0; j<leafMap[row].leafs.length; j++) {
682 leaf = leafMap[row].leafs[j].num;
684 leafWidth = this.thumbWidth;
685 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
686 leafTop = leafMap[row].top;
687 left = leafMap[row].leafs[index].left + pageViewBuffer;
688 if ('rl' == this.pageProgression){
689 left = viewWidth - leafWidth - left;
692 div = document.createElement("div");
693 div.id = 'pagediv'+leaf;
694 div.style.position = "absolute";
695 div.className = "BRpagedivthumb";
697 left += this.padding;
698 $(div).css('top', leafTop + 'px');
699 $(div).css('left', left+'px');
700 $(div).css('width', leafWidth+'px');
701 $(div).css('height', leafHeight+'px');
702 //$(div).text('loading...');
704 // link to page in single page mode
705 link = document.createElement("a");
706 $(link).data('leaf', leaf);
707 $(link).bind('click', function(event) {
708 self.firstIndex = $(this).data('leaf');
709 self.switchMode(self.constMode1up);
710 event.preventDefault();
713 // $$$ we don't actually go to this URL (click is handled in handler above)
714 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
717 $('#BRpageview').append(div);
719 img = document.createElement("img");
720 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
722 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
723 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
724 .addClass('BRlazyload')
725 // Store the URL of the image that will replace this one
726 .data('srcURL', this._getPageURI(leaf, thumbReduce));
728 //console.log('displaying thumbnail: ' + leaf);
733 // remove previous highlights
734 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
736 // highlight current page
737 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
739 // Remove thumbnails that are not to be displayed
741 for (i=0; i<this.displayedRows.length; i++) {
742 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
743 row = this.displayedRows[i];
745 // $$$ Safari doesn't like the comprehension
746 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
747 //console.log('Removing row ' + row + ' ' + rowLeafs);
749 for (k=0; k<leafMap[row].leafs.length; k++) {
750 index = leafMap[row].leafs[k].num;
751 //console.log('Removing leaf ' + index);
752 $('#pagediv'+index).remove();
756 var mRow = this.displayedRows[i];
757 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
758 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
763 this.displayedRows = rowsToDisplay.slice();
765 this.lazyLoadThumbnails();
767 // Update page number box. $$$ refactor to function
768 if (null !== this.getPageNum(this.currentIndex())) {
769 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
771 $("#BRpagenum").val('');
774 this.updateToolbarZoom(this.reduce);
777 BookReader.prototype.lazyLoadThumbnails = function() {
779 // console.log('lazy load');
781 // We check the complete property since load may not be fired if loading from the cache
782 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
784 var loading = $('.BRlazyloading').length;
785 var toLoad = this.thumbMaxLoading - loading;
787 // console.log(' ' + loading + ' thumbnails loading');
788 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
793 // $$$ TODO load those near top (but not beyond) page view first
794 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
795 self.lazyLoadImage(this);
800 BookReader.prototype.lazyLoadImage = function (dummyImage) {
801 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
803 var img = new Image();
807 .addClass('BRlazyloading')
808 .one('load', function() {
809 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
811 $(this).removeClass('BRlazyloading');
813 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
814 // we call the function after a slight delay. Also the img.complete property
815 // is not yet set in IE8 inside this onload handler
816 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
818 .one('error', function() {
819 // Remove class so we no longer count as loading
820 $(this).removeClass('BRlazyloading');
822 .attr( { width: $(dummyImage).width(),
823 height: $(dummyImage).height(),
824 src: $(dummyImage).data('srcURL')
827 // replace with the new img
828 $(dummyImage).before(img).remove();
830 img = null; // tidy up closure
834 // drawLeafsTwoPage()
835 //______________________________________________________________________________
836 BookReader.prototype.drawLeafsTwoPage = function() {
837 var scrollTop = $('#BRtwopageview').attr('scrollTop');
838 var scrollBottom = scrollTop + $('#BRtwopageview').height();
840 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
842 var indexL = this.twoPage.currentIndexL;
844 var heightL = this._getPageHeight(indexL);
845 var widthL = this._getPageWidth(indexL);
847 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
848 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
849 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
850 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
851 //console.log(leafEdgeWidthL);
853 var middle = this.twoPage.middle; // $$$ getter instead?
854 var top = this.twoPageTop();
855 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
857 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
858 this.twoPage.gutter = this.twoPageGutter();
860 this.prefetchImg(indexL);
861 $(this.prefetchedImgs[indexL]).css({
862 position: 'absolute',
863 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
866 backgroundColor: this.getPageBackgroundColor(indexL),
867 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
868 width: this.twoPage.scaledWL + 'px',
869 borderRight: '1px solid black',
871 }).appendTo('#BRtwopageview');
873 var indexR = this.twoPage.currentIndexR;
874 var heightR = this._getPageHeight(indexR);
875 var widthR = this._getPageWidth(indexR);
877 // $$$ should use getwidth2up?
878 //var scaledWR = this.twoPage.height*widthR/heightR;
879 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
880 this.prefetchImg(indexR);
881 $(this.prefetchedImgs[indexR]).css({
882 position: 'absolute',
883 left: this.twoPage.gutter+'px',
886 backgroundColor: this.getPageBackgroundColor(indexR),
887 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
888 width: this.twoPage.scaledWR + 'px',
889 borderLeft: '1px solid black',
891 }).appendTo('#BRtwopageview');
894 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
895 this.setMouseHandlers2UP();
896 this.twoPageSetCursor();
898 this.updatePageNumBox2UP();
899 this.updateToolbarZoom(this.reduce);
901 // this.twoPagePlaceFlipAreas(); // No longer used
905 // updatePageNumBox2UP
906 //______________________________________________________________________________
907 BookReader.prototype.updatePageNumBox2UP = function() {
908 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
909 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
911 $("#BRpagenum").val('');
913 this.updateLocationHash();
917 //______________________________________________________________________________
918 BookReader.prototype.loadLeafs = function() {
922 if (null == this.timer) {
923 this.timer=setTimeout(function(){self.drawLeafs()},250);
925 clearTimeout(this.timer);
926 this.timer=setTimeout(function(){self.drawLeafs()},250);
932 // Pass 1 to zoom in, anything else to zoom out
933 //______________________________________________________________________________
934 BookReader.prototype.zoom = function(direction) {
936 case this.constMode1up:
937 return this.zoom1up(direction);
938 case this.constMode2up:
939 return this.zoom2up(direction);
940 case this.constModeThumb:
941 return this.zoomThumb(direction);
946 //______________________________________________________________________________
947 BookReader.prototype.zoom1up = function(dir) {
949 if (2 == this.mode) { //can only zoom in 1-page mode
954 // $$$ with flexible zoom we could "snap" to /2 page reductions
955 // for better scaling
957 if (this.reduce <= 0.5) return;
958 this.reduce*=0.5; //zoom in
960 if (this.reduce >= 8) return;
961 this.reduce*=2; //zoom out
964 this.pageScale = this.reduce; // preserve current reduce
965 this.resizePageView();
967 $('#BRpageview').empty()
968 this.displayedIndices = [];
971 this.updateToolbarZoom(this.reduce);
973 // Recalculate search hilites
974 this.removeSearchHilites();
975 this.updateSearchHilites();
980 //______________________________________________________________________________
981 BookReader.prototype.resizePageView = function() {
983 // $$$ This code assumes 1up mode
984 // e.g. does not preserve position in thumbnail mode
985 // See http://bugs.launchpad.net/bookreader/+bug/552972
989 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
990 var viewWidth = $('#BRcontainer').attr('clientWidth');
992 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
993 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
994 var oldPageViewHeight = $('#BRpageview').height();
995 var oldPageViewWidth = $('#BRpageview').width();
997 var oldCenterY = this.centerY1up();
998 var oldCenterX = this.centerX1up();
1000 if (0 != oldPageViewHeight) {
1001 var scrollRatio = oldCenterY / oldPageViewHeight;
1003 var scrollRatio = 0;
1006 for (i=0; i<this.numLeafs; i++) {
1007 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
1008 var width = parseInt(this._getPageWidth(i)/this.reduce);
1009 if (width>viewWidth) viewWidth=width;
1011 $('#BRpageview').height(viewHeight);
1012 $('#BRpageview').width(viewWidth);
1014 var newCenterY = scrollRatio*viewHeight;
1015 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
1016 $('#BRcontainer').attr('scrollTop', newTop);
1018 // We use clientWidth here to avoid miscalculating due to scroll bar
1019 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
1020 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
1021 newLeft = Math.max(newLeft, 0);
1022 $('#BRcontainer').attr('scrollLeft', newLeft);
1023 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
1025 //this.centerPageView();
1028 // $$$ jump to index here? index is not preserved when resizing in thumb mode
1030 // Not really needed until there is 1up autofit
1031 this.removeSearchHilites();
1032 this.updateSearchHilites();
1036 //______________________________________________________________________________
1037 // Returns the current offset of the viewport center in scaled document coordinates.
1038 BookReader.prototype.centerX1up = function() {
1040 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
1041 centerX = $('#BRpageview').width();
1043 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
1045 centerX = Math.floor(centerX);
1050 //______________________________________________________________________________
1051 // Returns the current offset of the viewport center in scaled document coordinates.
1052 BookReader.prototype.centerY1up = function() {
1053 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1054 return Math.floor(centerY);
1058 //______________________________________________________________________________
1059 BookReader.prototype.centerPageView = function() {
1061 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1062 var clientWidth = $('#BRcontainer').attr('clientWidth');
1063 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1064 if (scrollWidth > clientWidth) {
1065 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1070 // zoom2up(direction)
1071 //______________________________________________________________________________
1072 BookReader.prototype.zoom2up = function(direction) {
1074 // Hard stop autoplay
1075 this.stopFlipAnimations();
1077 // Get new zoom state
1078 var newZoom = this.twoPageNextReduce(this.reduce, direction);
1079 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
1082 this.twoPage.autofit = newZoom.autofit;
1083 this.reduce = newZoom.reduce;
1084 this.pageScale = this.reduce; // preserve current reduce
1086 // Preserve view center position
1087 var oldCenter = this.twoPageGetViewCenter();
1089 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1090 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1091 if (1 == direction) {
1092 for (var img in this.prefetchedImgs) {
1093 delete this.prefetchedImgs[img];
1097 // Prepare view with new center to minimize visual glitches
1098 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1101 BookReader.prototype.zoomThumb = function(direction) {
1102 var oldColumns = this.thumbColumns;
1103 switch (direction) {
1105 this.thumbColumns += 1;
1108 this.thumbColumns -= 1;
1113 if (this.thumbColumns < 2) {
1114 this.thumbColumns = 2;
1115 } else if (this.thumbColumns > 8) {
1116 this.thumbColumns = 8;
1119 if (this.thumbColumns != oldColumns) {
1120 this.prepareThumbnailView();
1121 this.jumpToIndex(this.currentIndex());
1125 // Returns the width per thumbnail to display the requested number of columns
1126 // Note: #BRpageview must already exist since its width is used to calculate the
1128 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1129 var padding = (thumbnailColumns + 1) * this.padding;
1130 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1131 return parseInt(width);
1134 // quantizeReduce(reduce)
1135 //______________________________________________________________________________
1136 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1137 BookReader.prototype.quantizeReduce = function(reduce) {
1138 var quantized = this.reductionFactors[0];
1139 var distance = Math.abs(reduce - quantized);
1140 for (var i = 1; i < this.reductionFactors.length; i++) {
1141 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1142 if (newDistance < distance) {
1143 distance = newDistance;
1144 quantized = this.reductionFactors[i];
1151 // twoPageNextReduce()
1152 //______________________________________________________________________________
1153 // Returns the next reduction level
1154 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1156 var autofitReduce = this.twoPageGetAutofitReduce();
1158 if (0 == direction) { // autofit
1159 result.autofit = true;
1160 result.reduce = autofitReduce;
1162 } else if (1 == direction) { // zoom in
1163 var newReduce = this.reductionFactors[0];
1165 for (var i = 1; i < this.reductionFactors.length; i++) {
1166 if (this.reductionFactors[i] < reduce) {
1167 newReduce = this.reductionFactors[i];
1171 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1173 result.autofit = true;
1174 result.reduce = autofitReduce;
1176 result.autofit = false;
1177 result.reduce = newReduce;
1180 } else { // zoom out
1181 var lastIndex = this.reductionFactors.length - 1;
1182 var newReduce = this.reductionFactors[lastIndex];
1184 for (var i = lastIndex; i >= 0; i--) {
1185 if (this.reductionFactors[i] > reduce) {
1186 newReduce = this.reductionFactors[i];
1190 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1192 result.autofit = true;
1193 result.reduce = autofitReduce;
1195 result.autofit = false;
1196 result.reduce = newReduce;
1204 //______________________________________________________________________________
1205 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1206 BookReader.prototype.jumpToPage = function(pageNum) {
1208 var pageIndex = this.getPageIndex(pageNum);
1210 if ('undefined' != typeof(pageIndex)) {
1213 this.jumpToIndex(pageIndex);
1214 $('#BRcontainer').attr('scrollTop', leafTop);
1223 //______________________________________________________________________________
1224 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1226 if (2 == this.mode) {
1229 // By checking against min/max we do nothing if requested index
1231 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1232 this.flipBackToIndex(index);
1233 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1234 this.flipFwdToIndex(index);
1237 } else if (3 == this.mode) {
1238 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1248 for (i=0; i<(index+1); i++) {
1249 leafWidth = this.thumbWidth;
1250 if (rightPos + (leafWidth + this.padding) > viewWidth){
1255 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1256 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1257 if (leafIndex==0) { leafTop = bottomPos; }
1258 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1259 rightPos += leafWidth + this.padding;
1262 this.firstIndex=index;
1263 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1266 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1273 for (i=0; i<index; i++) {
1274 h = parseInt(this._getPageHeight(i)/this.reduce);
1275 leafTop += h + this.padding;
1279 //console.log('pageY ' + pageY);
1280 var offset = parseInt( (pageY) / this.reduce);
1281 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1282 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1287 var offset = parseInt( (pageX) / this.reduce);
1288 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1292 //$('#BRcontainer').attr('scrollTop', leafTop);
1293 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1299 //______________________________________________________________________________
1300 BookReader.prototype.switchMode = function(mode) {
1302 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1304 if (mode == this.mode) {
1308 if (!this.canSwitchToMode(mode)) {
1313 this.removeSearchHilites();
1316 this.switchToolbarMode(mode);
1318 // reinstate scale if moving from thumbnail view
1319 if (this.pageScale != this.reduce) {
1320 this.reduce = this.pageScale;
1323 // $$$ TODO preserve center of view when switching between mode
1324 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1327 this.reduce = this.quantizeReduce(this.reduce);
1328 this.prepareOnePageView();
1329 } else if (3 == mode) {
1330 this.reduce = this.quantizeReduce(this.reduce);
1331 this.prepareThumbnailView();
1332 this.jumpToIndex(this.currentIndex());
1334 // $$$ why don't we save autofit?
1335 this.twoPage.autofit = false; // Take zoom level from other mode
1336 this.reduce = this.quantizeReduce(this.reduce);
1337 this.prepareTwoPageView();
1338 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1343 //prepareOnePageView()
1344 //______________________________________________________________________________
1345 BookReader.prototype.prepareOnePageView = function() {
1347 // var startLeaf = this.displayedIndices[0];
1348 var startLeaf = this.currentIndex();
1350 $('#BRcontainer').empty();
1351 $('#BRcontainer').css({
1352 overflowY: 'scroll',
1356 $("#BRcontainer").append("<div id='BRpageview'></div>");
1357 // $$$ keep select enabled for now since disabling it breaks keyboard
1358 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1359 // BookReader.util.disableSelect($('#BRpageview'));
1361 this.resizePageView();
1363 this.jumpToIndex(startLeaf);
1364 this.displayedIndices = [];
1366 this.drawLeafsOnePage();
1369 //prepareThumbnailView()
1370 //______________________________________________________________________________
1371 BookReader.prototype.prepareThumbnailView = function() {
1373 $('#BRcontainer').empty();
1374 $('#BRcontainer').css({
1375 overflowY: 'scroll',
1379 $("#BRcontainer").append("<div id='BRpageview'></div>");
1381 // $$$ keep select enabled for now since disabling it breaks keyboard
1382 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1383 // BookReader.util.disableSelect($('#BRpageview'));
1385 var startLeaf = this.currentIndex();
1386 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1387 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1389 this.resizePageView();
1391 this.displayedRows = [];
1393 // $$$ resizePageView will do a delayed load -- this will make it happen faster
1394 this.drawLeafsThumbnail();
1397 // prepareTwoPageView()
1398 //______________________________________________________________________________
1399 // Some decisions about two page view:
1401 // Both pages will be displayed at the same height, even if they were different physical/scanned
1402 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1403 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1404 // aspect ratio to determine the height.
1406 // The two page view div is resized to keep the middle of the book in the middle of the div
1407 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1408 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1409 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1410 $('#BRcontainer').empty();
1411 $('#BRcontainer').css('overflow', 'auto');
1413 // We want to display two facing pages. We may be missing
1414 // one side of the spread because it is the first/last leaf,
1415 // foldouts, missing pages, etc
1417 //var targetLeaf = this.displayedIndices[0];
1418 var targetLeaf = this.firstIndex;
1420 if (targetLeaf < this.firstDisplayableIndex()) {
1421 targetLeaf = this.firstDisplayableIndex();
1424 if (targetLeaf > this.lastDisplayableIndex()) {
1425 targetLeaf = this.lastDisplayableIndex();
1428 //this.twoPage.currentIndexL = null;
1429 //this.twoPage.currentIndexR = null;
1430 //this.pruneUnusedImgs();
1432 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1433 this.twoPage.currentIndexL = currentSpreadIndices[0];
1434 this.twoPage.currentIndexR = currentSpreadIndices[1];
1435 this.firstIndex = this.twoPage.currentIndexL;
1437 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1439 this.pruneUnusedImgs();
1440 this.prefetch(); // Preload images or reload if scaling has changed
1442 //console.dir(this.twoPage);
1444 // Add the two page view
1445 // $$$ Can we get everything set up and then append?
1446 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1448 // $$$ calculate first then set
1449 $('#BRtwopageview').css( {
1450 height: this.twoPage.totalHeight + 'px',
1451 width: this.twoPage.totalWidth + 'px',
1452 position: 'absolute'
1455 // If there will not be scrollbars (e.g. when zooming out) we center the book
1456 // since otherwise the book will be stuck off-center
1457 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1458 centerPercentageX = 0.5;
1460 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1461 centerPercentageY = 0.5;
1464 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1466 this.twoPage.coverDiv = document.createElement('div');
1467 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1468 border: '1px solid rgb(68, 25, 17)',
1469 width: this.twoPage.bookCoverDivWidth + 'px',
1470 height: this.twoPage.bookCoverDivHeight+'px',
1471 visibility: 'visible',
1472 position: 'absolute',
1473 backgroundColor: '#663929',
1474 left: this.twoPage.bookCoverDivLeft + 'px',
1475 top: this.twoPage.bookCoverDivTop+'px',
1476 MozBorderRadiusTopleft: '7px',
1477 MozBorderRadiusTopright: '7px',
1478 MozBorderRadiusBottomright: '7px',
1479 MozBorderRadiusBottomleft: '7px'
1480 }).appendTo('#BRtwopageview');
1482 this.leafEdgeR = document.createElement('div');
1483 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1484 $(this.leafEdgeR).css({
1485 borderStyle: 'solid solid solid none',
1486 borderColor: 'rgb(51, 51, 34)',
1487 borderWidth: '1px 1px 1px 0px',
1488 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1489 width: this.twoPage.leafEdgeWidthR + 'px',
1490 height: this.twoPage.height-1 + 'px',
1492 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1493 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1494 position: 'absolute'
1495 }).appendTo('#BRtwopageview');
1497 this.leafEdgeL = document.createElement('div');
1498 this.leafEdgeL.className = 'leafEdgeL';
1499 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1500 borderStyle: 'solid none solid solid',
1501 borderColor: 'rgb(51, 51, 34)',
1502 borderWidth: '1px 0px 1px 1px',
1503 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1504 width: this.twoPage.leafEdgeWidthL + 'px',
1505 height: this.twoPage.height-1 + 'px',
1506 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1507 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1508 position: 'absolute'
1509 }).appendTo('#BRtwopageview');
1511 div = document.createElement('div');
1512 $(div).attr('id', 'BRbookspine').css({
1513 border: '1px solid rgb(68, 25, 17)',
1514 width: this.twoPage.bookSpineDivWidth+'px',
1515 height: this.twoPage.bookSpineDivHeight+'px',
1516 position: 'absolute',
1517 backgroundColor: 'rgb(68, 25, 17)',
1518 left: this.twoPage.bookSpineDivLeft+'px',
1519 top: this.twoPage.bookSpineDivTop+'px'
1520 }).appendTo('#BRtwopageview');
1522 var self = this; // for closure
1524 /* Flip areas no longer used
1525 this.twoPage.leftFlipArea = document.createElement('div');
1526 this.twoPage.leftFlipArea.className = 'BRfliparea';
1527 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1529 width: this.twoPageFlipAreaWidth() + 'px',
1530 height: this.twoPageFlipAreaHeight() + 'px',
1531 position: 'absolute',
1532 left: this.twoPageLeftFlipAreaLeft() + 'px',
1533 top: this.twoPageFlipAreaTop() + 'px',
1536 }).bind('click', function(e) {
1538 }).bind('mousedown', function(e) {
1540 }).appendTo('#BRtwopageview');
1542 this.twoPage.rightFlipArea = document.createElement('div');
1543 this.twoPage.rightFlipArea.className = 'BRfliparea';
1544 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1546 width: this.twoPageFlipAreaWidth() + 'px',
1547 height: this.twoPageFlipAreaHeight() + 'px',
1548 position: 'absolute',
1549 left: this.twoPageRightFlipAreaLeft() + 'px',
1550 top: this.twoPageFlipAreaTop() + 'px',
1553 }).bind('click', function(e) {
1555 }).bind('mousedown', function(e) {
1557 }).appendTo('#BRtwopageview');
1560 this.prepareTwoPagePopUp();
1562 this.displayedIndices = [];
1564 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1565 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1567 this.drawLeafsTwoPage();
1568 this.updateToolbarZoom(this.reduce);
1572 this.removeSearchHilites();
1573 this.updateSearchHilites();
1577 // prepareTwoPagePopUp()
1579 // This function prepares the "View Page n" popup that shows while the mouse is
1580 // over the left/right "stack of sheets" edges. It also binds the mouse
1581 // events for these divs.
1582 //______________________________________________________________________________
1583 BookReader.prototype.prepareTwoPagePopUp = function() {
1585 this.twoPagePopUp = document.createElement('div');
1586 $(this.twoPagePopUp).css({
1587 border: '1px solid black',
1589 position: 'absolute',
1590 fontFamily: 'sans-serif',
1593 backgroundColor: 'rgb(255, 255, 238)',
1595 }).appendTo('#BRcontainer');
1596 $(this.twoPagePopUp).hide();
1598 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1599 $(e.data.twoPagePopUp).show();
1602 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1603 $(e.data.twoPagePopUp).hide();
1606 $(this.leafEdgeL).bind('click', this, function(e) {
1608 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1609 e.data.jumpToIndex(jumpIndex);
1612 $(this.leafEdgeR).bind('click', this, function(e) {
1614 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1615 e.data.jumpToIndex(jumpIndex);
1618 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1620 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1621 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1623 // $$$ TODO: Make sure popup is positioned so that it is in view
1624 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1625 $(e.data.twoPagePopUp).css({
1626 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1627 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1631 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1633 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1634 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1636 // $$$ TODO: Make sure popup is positioned so that it is in view
1637 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1638 $(e.data.twoPagePopUp).css({
1639 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1640 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1645 // calculateSpreadSize()
1646 //______________________________________________________________________________
1647 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1648 // this.twoPage.currentIndexR
1649 // This function sets this.twoPage.height, twoPage.width
1651 BookReader.prototype.calculateSpreadSize = function() {
1653 var firstIndex = this.twoPage.currentIndexL;
1654 var secondIndex = this.twoPage.currentIndexR;
1655 //console.log('first page is ' + firstIndex);
1657 // Calculate page sizes and total leaf width
1659 if ( this.twoPage.autofit) {
1660 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1662 // set based on reduction factor
1663 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1666 // Both pages together
1667 this.twoPage.height = spreadSize.height;
1668 this.twoPage.width = spreadSize.width;
1671 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1672 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1675 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1676 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1677 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1681 // The width of the book cover div. The combined width of both pages, twice the width
1682 // of the book cover internal padding (2*10) and the page edges
1683 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1684 // The height of the book cover div
1685 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1688 // We calculate the total width and height for the div so that we can make the book
1690 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1691 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1692 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1693 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1694 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1695 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1697 // We want to minimize the unused space in two-up mode (maximize the amount of page
1698 // shown). We give width to the leaf edges and these widths change (though the sum
1699 // of the two remains constant) as we flip through the book. With the book
1700 // cover centered and fixed in the BRcontainer div the page images will meet
1701 // at the "gutter" which is generally offset from the center.
1702 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1703 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1705 // The left edge of the book cover moves depending on the width of the pages
1706 // $$$ change to getter
1707 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1708 // The top edge of the book cover stays a fixed distance from the top
1709 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1712 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1713 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1714 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1717 this.reduce = spreadSize.reduce; // $$$ really set this here?
1720 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1723 // We check which page is closest to a "normal" page and use that to set the height
1724 // for both pages. This means that foldouts and other odd size pages will be displayed
1725 // smaller than the nominal zoom amount.
1726 var canon5Dratio = 1.5;
1729 height: this._getPageHeight(firstIndex),
1730 width: this._getPageWidth(firstIndex)
1734 height: this._getPageHeight(secondIndex),
1735 width: this._getPageWidth(secondIndex)
1738 var firstIndexRatio = first.height / first.width;
1739 var secondIndexRatio = second.height / second.width;
1740 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1743 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1744 ratio = firstIndexRatio;
1745 //console.log('using firstIndexRatio ' + ratio);
1747 ratio = secondIndexRatio;
1748 //console.log('using secondIndexRatio ' + ratio);
1751 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1752 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1753 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1755 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1756 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1758 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1759 ideal.width -= 10; // $$$ fudge factor
1760 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1761 ideal.height -= 20; // fudge factor
1762 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1764 if (ideal.height/ratio <= ideal.width) {
1766 ideal.width = parseInt(ideal.height/ratio);
1769 ideal.height = parseInt(ideal.width*ratio);
1772 // $$$ check this logic with large spreads
1773 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1778 // getSpreadSizeFromReduce()
1779 //______________________________________________________________________________
1780 // Returns the spread size calculated from the reduction factor for the given pages
1781 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1782 var spreadSize = {};
1783 // $$$ Scale this based on reduce?
1784 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1785 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1786 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1788 // $$$ Possibly incorrect -- we should make height "dominant"
1789 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1790 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1791 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1792 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1793 spreadSize.reduce = reduce;
1798 // twoPageGetAutofitReduce()
1799 //______________________________________________________________________________
1800 // Returns the current ideal reduction factor
1801 BookReader.prototype.twoPageGetAutofitReduce = function() {
1802 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1803 return spreadSize.reduce;
1806 // twoPageSetCursor()
1807 //______________________________________________________________________________
1808 // Set the cursor for two page view
1809 BookReader.prototype.twoPageSetCursor = function() {
1810 // console.log('setting cursor');
1811 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1812 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1813 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1814 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1816 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1817 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1822 //______________________________________________________________________________
1823 // Returns the currently active index.
1824 BookReader.prototype.currentIndex = function() {
1825 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1826 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1827 return this.firstIndex; // $$$ TODO page in center of view would be better
1828 } else if (this.mode == this.constMode2up) {
1829 // Only allow indices that are actually present in book
1830 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1832 throw 'currentIndex called for unimplemented mode ' + this.mode;
1837 // Returns the current index if visible, or the logically current visible
1839 BookReader.prototype.currentIndexOrVisibleThumb = function() {
1840 // XXX finish implementation
1841 var index = this.currentIndex();
1842 if (!this.indexIsVisbleThumb(this.currentIndex()) {
1843 // XXX search for visible
1848 // Returns true if the given index is visible
1849 BookReader.prototype.indexIsVisibleThumb = function(index, onlyCompletelyVisible = true) {
1851 // $$$ I'd prefer to go through a stored leaf map instead of DOM
1859 //______________________________________________________________________________
1860 // Flip the right page over onto the left
1861 BookReader.prototype.right = function() {
1862 if ('rl' != this.pageProgression) {
1872 //______________________________________________________________________________
1873 // Flip to the rightmost page
1874 BookReader.prototype.rightmost = function() {
1875 if ('rl' != this.pageProgression) {
1883 //______________________________________________________________________________
1884 // Flip the left page over onto the right.
1885 BookReader.prototype.left = function() {
1886 if ('rl' != this.pageProgression) {
1896 //______________________________________________________________________________
1897 // Flip to the leftmost page
1898 BookReader.prototype.leftmost = function() {
1899 if ('rl' != this.pageProgression) {
1907 //______________________________________________________________________________
1908 BookReader.prototype.next = function() {
1909 if (2 == this.mode) {
1911 this.flipFwdToIndex(null);
1913 if (this.firstIndex < this.lastDisplayableIndex()) {
1914 this.jumpToIndex(this.firstIndex+1);
1920 //______________________________________________________________________________
1921 BookReader.prototype.prev = function() {
1922 if (2 == this.mode) {
1924 this.flipBackToIndex(null);
1926 if (this.firstIndex >= 1) {
1927 this.jumpToIndex(this.firstIndex-1);
1932 BookReader.prototype.first = function() {
1933 this.jumpToIndex(this.firstDisplayableIndex());
1936 BookReader.prototype.last = function() {
1937 this.jumpToIndex(this.lastDisplayableIndex());
1941 //______________________________________________________________________________
1942 // Scrolls down one screen view
1943 BookReader.prototype.scrollDown = function() {
1944 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1945 $('#BRcontainer').animate(
1946 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1947 450, 'easeInOutQuint'
1956 //______________________________________________________________________________
1957 // Scrolls up one screen view
1958 BookReader.prototype.scrollUp = function() {
1959 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1960 $('#BRcontainer').animate(
1961 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1962 450, 'easeInOutQuint'
1971 // flipBackToIndex()
1972 //______________________________________________________________________________
1973 // to flip back one spread, pass index=null
1974 BookReader.prototype.flipBackToIndex = function(index) {
1976 if (1 == this.mode) return;
1978 var leftIndex = this.twoPage.currentIndexL;
1980 if (this.animating) return;
1982 if (null != this.leafEdgeTmp) {
1983 alert('error: leafEdgeTmp should be null!');
1987 if (null == index) {
1988 index = leftIndex-2;
1990 //if (index<0) return;
1992 var previousIndices = this.getSpreadIndices(index);
1994 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1998 this.animating = true;
2000 if ('rl' != this.pageProgression) {
2001 // Assume LTR and we are going backward
2002 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
2003 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
2005 // RTL and going backward
2006 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2007 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2011 // flipLeftToRight()
2012 //______________________________________________________________________________
2013 // Flips the page on the left towards the page on the right
2014 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2016 var leftLeaf = this.twoPage.currentIndexL;
2018 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2019 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2020 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2022 var currWidthL = this.getPageWidth2UP(leftLeaf);
2023 var newWidthL = this.getPageWidth2UP(newIndexL);
2024 var newWidthR = this.getPageWidth2UP(newIndexR);
2026 var top = this.twoPageTop();
2027 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2029 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2030 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2032 //animation strategy:
2033 // 0. remove search highlight, if any.
2034 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2035 // of the left leaf and where the user clicked in the leaf edge.
2036 // Note that if this function was triggered by left() and not a
2037 // mouse click, the width of leafEdgeTmp is very small (zero px).
2038 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2039 // leftLeaf to width=0.
2040 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2041 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2042 // its new full width.
2043 // 4. After step 3 is finished, do the following:
2044 // - remove leafEdgeTmp from the dom.
2045 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2046 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2047 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2048 // and width=newLeafEdgeWidthL.
2049 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2050 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2051 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2052 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2053 // - prefetch new adjacent leafs.
2054 // - set up click handlers for both new left and right leafs.
2055 // - redraw the search highlight.
2056 // - update the pagenum box and the url.
2059 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2061 this.leafEdgeTmp = document.createElement('div');
2062 $(this.leafEdgeTmp).css({
2063 borderStyle: 'solid none solid solid',
2064 borderColor: 'rgb(51, 51, 34)',
2065 borderWidth: '1px 0px 1px 1px',
2066 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2067 width: leafEdgeTmpW + 'px',
2068 height: this.twoPage.height-1 + 'px',
2069 left: leftEdgeTmpLeft + 'px',
2071 position: 'absolute',
2073 }).appendTo('#BRtwopageview');
2075 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2076 $(this.leafEdgeL).css({
2077 width: newLeafEdgeWidthL+'px',
2078 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2081 // Left gets the offset of the current left leaf from the document
2082 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2083 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2084 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2086 // We change the left leaf to right positioning
2087 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2088 $(this.prefetchedImgs[leftLeaf]).css({
2093 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2094 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2098 this.removeSearchHilites();
2100 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2101 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2103 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2104 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2106 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2107 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2108 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2110 $(self.leafEdgeR).css({
2111 // Moves the right leaf edge
2112 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2113 left: gutter+newWidthR+'px'
2116 $(self.leafEdgeL).css({
2117 // Moves and resizes the left leaf edge
2118 width: newLeafEdgeWidthL+'px',
2119 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2122 // Resizes the brown border div
2123 $(self.twoPage.coverDiv).css({
2124 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2125 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2128 $(self.leafEdgeTmp).remove();
2129 self.leafEdgeTmp = null;
2131 // $$$ TODO refactor with opposite direction flip
2133 self.twoPage.currentIndexL = newIndexL;
2134 self.twoPage.currentIndexR = newIndexR;
2135 self.twoPage.scaledWL = newWidthL;
2136 self.twoPage.scaledWR = newWidthR;
2137 self.twoPage.gutter = gutter;
2139 self.firstIndex = self.twoPage.currentIndexL;
2140 self.displayedIndices = [newIndexL, newIndexR];
2141 self.pruneUnusedImgs();
2143 self.animating = false;
2145 self.updateSearchHilites2UP();
2146 self.updatePageNumBox2UP();
2148 // self.twoPagePlaceFlipAreas(); // No longer used
2149 self.setMouseHandlers2UP();
2150 self.twoPageSetCursor();
2152 if (self.animationFinishedCallback) {
2153 self.animationFinishedCallback();
2154 self.animationFinishedCallback = null;
2162 //______________________________________________________________________________
2163 // Whether we flip left or right is dependent on the page progression
2164 // to flip forward one spread, pass index=null
2165 BookReader.prototype.flipFwdToIndex = function(index) {
2167 if (this.animating) return;
2169 if (null != this.leafEdgeTmp) {
2170 alert('error: leafEdgeTmp should be null!');
2174 if (null == index) {
2175 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2177 if (index > this.lastDisplayableIndex()) return;
2179 this.animating = true;
2181 var nextIndices = this.getSpreadIndices(index);
2183 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2185 if ('rl' != this.pageProgression) {
2186 // We did not specify RTL
2187 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2188 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2191 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2192 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2196 // flipRightToLeft(nextL, nextR, gutter)
2197 // $$$ better not to have to pass gutter in
2198 //______________________________________________________________________________
2199 // Flip from left to right and show the nextL and nextR indices on those sides
2200 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2201 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2202 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2203 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2204 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2206 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2208 var top = this.twoPageTop();
2209 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2211 var middle = this.twoPage.middle;
2212 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2214 this.leafEdgeTmp = document.createElement('div');
2215 $(this.leafEdgeTmp).css({
2216 borderStyle: 'solid none solid solid',
2217 borderColor: 'rgb(51, 51, 34)',
2218 borderWidth: '1px 0px 1px 1px',
2219 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2220 width: leafEdgeTmpW + 'px',
2221 height: this.twoPage.height-1 + 'px',
2222 left: gutter+scaledW+'px',
2224 position: 'absolute',
2226 }).appendTo('#BRtwopageview');
2228 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2229 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2231 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2232 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2233 var newWidthL = this.getPageWidth2UP(newIndexL);
2234 var newWidthR = this.getPageWidth2UP(newIndexR);
2236 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2238 var self = this; // closure-tastic!
2240 var speed = this.flipSpeed;
2242 this.removeSearchHilites();
2244 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2245 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2246 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2247 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2248 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2250 $(self.leafEdgeL).css({
2251 width: newLeafEdgeWidthL+'px',
2252 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2255 // Resizes the book cover
2256 $(self.twoPage.coverDiv).css({
2257 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2258 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2261 $(self.leafEdgeTmp).remove();
2262 self.leafEdgeTmp = null;
2264 self.twoPage.currentIndexL = newIndexL;
2265 self.twoPage.currentIndexR = newIndexR;
2266 self.twoPage.scaledWL = newWidthL;
2267 self.twoPage.scaledWR = newWidthR;
2268 self.twoPage.gutter = gutter;
2270 self.firstIndex = self.twoPage.currentIndexL;
2271 self.displayedIndices = [newIndexL, newIndexR];
2272 self.pruneUnusedImgs();
2274 self.animating = false;
2277 self.updateSearchHilites2UP();
2278 self.updatePageNumBox2UP();
2280 // self.twoPagePlaceFlipAreas(); // No longer used
2281 self.setMouseHandlers2UP();
2282 self.twoPageSetCursor();
2284 if (self.animationFinishedCallback) {
2285 self.animationFinishedCallback();
2286 self.animationFinishedCallback = null;
2292 // setMouseHandlers2UP
2293 //______________________________________________________________________________
2294 BookReader.prototype.setMouseHandlers2UP = function() {
2296 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2301 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2308 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2309 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2316 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2317 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2320 e.data.self.right();
2326 //______________________________________________________________________________
2327 BookReader.prototype.prefetchImg = function(index) {
2328 var pageURI = this._getPageURI(index);
2330 // Load image if not loaded or URI has changed (e.g. due to scaling)
2331 var loadImage = false;
2332 if (undefined == this.prefetchedImgs[index]) {
2333 //console.log('no image for ' + index);
2335 } else if (pageURI != this.prefetchedImgs[index].uri) {
2336 //console.log('uri changed for ' + index);
2341 //console.log('prefetching ' + index);
2342 var img = document.createElement("img");
2344 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2345 this.prefetchedImgs[index] = img;
2350 // prepareFlipLeftToRight()
2352 //______________________________________________________________________________
2354 // Prepare to flip the left page towards the right. This corresponds to moving
2355 // backward when the page progression is left to right.
2356 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2358 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2360 this.prefetchImg(prevL);
2361 this.prefetchImg(prevR);
2363 var height = this._getPageHeight(prevL);
2364 var width = this._getPageWidth(prevL);
2365 var middle = this.twoPage.middle;
2366 var top = this.twoPageTop();
2367 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2369 // The gutter is the dividing line between the left and right pages.
2370 // It is offset from the middle to create the illusion of thickness to the pages
2371 var gutter = middle + this.gutterOffsetForIndex(prevL);
2373 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2374 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2375 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2378 position: 'absolute',
2379 left: gutter-scaledW+'px',
2380 right: '', // clear right property
2382 height: this.twoPage.height,
2383 width: scaledW+'px',
2384 backgroundColor: this.getPageBackgroundColor(prevL),
2385 borderRight: '1px solid black',
2389 $(this.prefetchedImgs[prevL]).css(leftCSS);
2391 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2393 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2396 position: 'absolute',
2400 height: this.twoPage.height,
2402 backgroundColor: this.getPageBackgroundColor(prevR),
2403 borderLeft: '1px solid black',
2407 $(this.prefetchedImgs[prevR]).css(rightCSS);
2409 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2413 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2414 // prepareFlipRightToLeft()
2415 //______________________________________________________________________________
2416 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2418 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2421 this.prefetchImg(nextL);
2422 this.prefetchImg(nextR);
2424 var height = this._getPageHeight(nextR);
2425 var width = this._getPageWidth(nextR);
2426 var middle = this.twoPage.middle;
2427 var top = this.twoPageTop();
2428 var scaledW = this.twoPage.height*width/height;
2430 var gutter = middle + this.gutterOffsetForIndex(nextL);
2432 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2433 $(this.prefetchedImgs[nextR]).css({
2434 position: 'absolute',
2437 backgroundColor: this.getPageBackgroundColor(nextR),
2438 height: this.twoPage.height,
2439 width: scaledW+'px',
2440 borderLeft: '1px solid black',
2444 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2446 height = this._getPageHeight(nextL);
2447 width = this._getPageWidth(nextL);
2448 scaledW = this.twoPage.height*width/height;
2450 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2451 $(this.prefetchedImgs[nextL]).css({
2452 position: 'absolute',
2453 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2455 backgroundColor: this.getPageBackgroundColor(nextL),
2456 height: this.twoPage.height,
2457 width: 0+'px', // Start at 0 width, then grow to the left
2458 borderRight: '1px solid black',
2462 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2466 // getNextLeafs() -- NOT RTL AWARE
2467 //______________________________________________________________________________
2468 // BookReader.prototype.getNextLeafs = function(o) {
2469 // //TODO: we might have two left or two right leafs in a row (damaged book)
2470 // //For now, assume that leafs are contiguous.
2472 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2473 // o.L = this.twoPage.currentIndexL+2;
2474 // o.R = this.twoPage.currentIndexL+3;
2477 // getprevLeafs() -- NOT RTL AWARE
2478 //______________________________________________________________________________
2479 // BookReader.prototype.getPrevLeafs = function(o) {
2480 // //TODO: we might have two left or two right leafs in a row (damaged book)
2481 // //For now, assume that leafs are contiguous.
2483 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2484 // o.L = this.twoPage.currentIndexL-2;
2485 // o.R = this.twoPage.currentIndexL-1;
2488 // pruneUnusedImgs()
2489 //______________________________________________________________________________
2490 BookReader.prototype.pruneUnusedImgs = function() {
2491 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2492 for (var key in this.prefetchedImgs) {
2493 //console.log('key is ' + key);
2494 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2495 //console.log('removing key '+ key);
2496 $(this.prefetchedImgs[key]).remove();
2498 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2499 //console.log('deleting key '+ key);
2500 delete this.prefetchedImgs[key];
2506 //______________________________________________________________________________
2507 BookReader.prototype.prefetch = function() {
2509 // $$$ We should check here if the current indices have finished
2510 // loading (with some timeout) before loading more page images
2511 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2513 // prefetch visible pages first
2514 this.prefetchImg(this.twoPage.currentIndexL);
2515 this.prefetchImg(this.twoPage.currentIndexR);
2517 var adjacentPagesToLoad = 3;
2519 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2520 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2522 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2523 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2525 // Load images spreading out from current
2526 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2527 var goingDown = lowCurrent - i;
2528 if (goingDown >= start) {
2529 this.prefetchImg(goingDown);
2531 var goingUp = highCurrent + i;
2532 if (goingUp <= end) {
2533 this.prefetchImg(goingUp);
2538 var lim = this.twoPage.currentIndexL-4;
2540 lim = Math.max(lim, 0);
2541 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2542 this.prefetchImg(i);
2545 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2546 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2547 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2548 this.prefetchImg(i);
2554 // getPageWidth2UP()
2555 //______________________________________________________________________________
2556 BookReader.prototype.getPageWidth2UP = function(index) {
2557 // We return the width based on the dominant height
2558 var height = this._getPageHeight(index);
2559 var width = this._getPageWidth(index);
2560 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2564 //______________________________________________________________________________
2565 BookReader.prototype.search = function(term) {
2566 term = term.replace(/\//g, ' '); // strip slashes
2567 this.searchTerm = term;
2568 $('#BookReaderSearchScript').remove();
2569 var script = document.createElement("script");
2570 script.setAttribute('id', 'BookReaderSearchScript');
2571 script.setAttribute("type", "text/javascript");
2572 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2573 document.getElementsByTagName('head')[0].appendChild(script);
2574 $('#BookReaderSearchBox').val(term);
2575 $('#BookReaderSearchResults').html('Searching...');
2578 // BRSearchCallback()
2579 //______________________________________________________________________________
2580 BookReader.prototype.BRSearchCallback = function(txt) {
2582 if (jQuery.browser.msie) {
2583 var dom=new ActiveXObject("Microsoft.XMLDOM");
2587 var parser = new DOMParser();
2588 var dom = parser.parseFromString(txt, "text/xml");
2591 $('#BookReaderSearchResults').empty();
2592 $('#BookReaderSearchResults').append('<ul>');
2594 for (var key in this.searchResults) {
2595 if (null != this.searchResults[key].div) {
2596 $(this.searchResults[key].div).remove();
2598 delete this.searchResults[key];
2601 var pages = dom.getElementsByTagName('PAGE');
2603 if (0 == pages.length) {
2604 // $$$ it would be nice to echo the (sanitized) search result here
2605 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2607 for (var i = 0; i < pages.length; i++){
2608 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2611 var re = new RegExp (/_(\d{4})\.djvu/);
2612 var reMatch = re.exec(pages[i].getAttribute('file'));
2613 var index = parseInt(reMatch[1], 10);
2614 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2616 var children = pages[i].childNodes;
2618 for (var j=0; j<children.length; j++) {
2619 //console.log(j + ' - ' + children[j].nodeName);
2620 //console.log(children[j].firstChild.nodeValue);
2621 if ('CONTEXT' == children[j].nodeName) {
2622 context += children[j].firstChild.nodeValue;
2623 } else if ('WORD' == children[j].nodeName) {
2624 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2626 var index = this.leafNumToIndex(index);
2627 if (null != index) {
2628 //coordinates are [left, bottom, right, top, [baseline]]
2629 //we'll skip baseline for now...
2630 var coords = children[j].getAttribute('coords').split(',',4);
2631 if (4 == coords.length) {
2632 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2637 var pageName = this.getPageName(index);
2638 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2639 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2640 //TODO: remove hardcoded instance name
2641 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2644 $('#BookReaderSearchResults').append('</ul>');
2646 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2647 $('#BookReaderSearchBox').val(this.searchTerm);
2649 this.updateSearchHilites();
2652 // updateSearchHilites()
2653 //______________________________________________________________________________
2654 BookReader.prototype.updateSearchHilites = function() {
2655 if (2 == this.mode) {
2656 this.updateSearchHilites2UP();
2658 this.updateSearchHilites1UP();
2662 // showSearchHilites1UP()
2663 //______________________________________________________________________________
2664 BookReader.prototype.updateSearchHilites1UP = function() {
2666 for (var key in this.searchResults) {
2668 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2669 var result = this.searchResults[key];
2670 if (null == result.div) {
2671 result.div = document.createElement('div');
2672 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2673 //console.log('appending ' + key);
2676 width: (result.r-result.l)/this.reduce + 'px',
2677 height: (result.b-result.t)/this.reduce + 'px',
2678 left: (result.l)/this.reduce + 'px',
2679 top: (result.t)/this.reduce +'px'
2683 //console.log(key + ' not displayed');
2684 this.searchResults[key].div=null;
2690 //______________________________________________________________________________
2691 // Returns the position of the gutter (line between the page images)
2692 BookReader.prototype.twoPageGutter = function() {
2693 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2697 //______________________________________________________________________________
2698 // Returns the offset for the top of the page images
2699 BookReader.prototype.twoPageTop = function() {
2700 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2703 // twoPageCoverWidth()
2704 //______________________________________________________________________________
2705 // Returns the width of the cover div given the total page width
2706 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2707 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2710 // twoPageGetViewCenter()
2711 //______________________________________________________________________________
2712 // Returns the percentage offset into twopageview div at the center of container div
2713 // { percentageX: float, percentageY: float }
2714 BookReader.prototype.twoPageGetViewCenter = function() {
2717 var containerOffset = $('#BRcontainer').offset();
2718 var viewOffset = $('#BRtwopageview').offset();
2719 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2720 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2725 // twoPageCenterView(percentageX, percentageY)
2726 //______________________________________________________________________________
2727 // Centers the point given by percentage from left,top of twopageview
2728 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2729 if ('undefined' == typeof(percentageX)) {
2732 if ('undefined' == typeof(percentageY)) {
2736 var viewWidth = $('#BRtwopageview').width();
2737 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2738 var intoViewX = percentageX * viewWidth;
2740 var viewHeight = $('#BRtwopageview').height();
2741 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2742 var intoViewY = percentageY * viewHeight;
2744 if (viewWidth < containerClientWidth) {
2745 // Can fit width without scrollbars - center by adjusting offset
2746 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2748 // Need to scroll to center
2749 $('#BRtwopageview').css('left', 0);
2750 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2753 if (viewHeight < containerClientHeight) {
2754 // Fits with scrollbars - add offset
2755 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2757 $('#BRtwopageview').css('top', 0);
2758 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2762 // twoPageFlipAreaHeight
2763 //______________________________________________________________________________
2764 // Returns the integer height of the click-to-flip areas at the edges of the book
2765 BookReader.prototype.twoPageFlipAreaHeight = function() {
2766 return parseInt(this.twoPage.height);
2769 // twoPageFlipAreaWidth
2770 //______________________________________________________________________________
2771 // Returns the integer width of the flip areas
2772 BookReader.prototype.twoPageFlipAreaWidth = function() {
2773 var max = 100; // $$$ TODO base on view width?
2776 var width = this.twoPage.width * 0.15;
2777 return parseInt(BookReader.util.clamp(width, min, max));
2780 // twoPageFlipAreaTop
2781 //______________________________________________________________________________
2782 // Returns integer top offset for flip areas
2783 BookReader.prototype.twoPageFlipAreaTop = function() {
2784 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2787 // twoPageLeftFlipAreaLeft
2788 //______________________________________________________________________________
2789 // Left offset for left flip area
2790 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2791 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2794 // twoPageRightFlipAreaLeft
2795 //______________________________________________________________________________
2796 // Left offset for right flip area
2797 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2798 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2801 // twoPagePlaceFlipAreas
2802 //______________________________________________________________________________
2803 // Readjusts position of flip areas based on current layout
2804 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2805 // We don't set top since it shouldn't change relative to view
2806 $(this.twoPage.leftFlipArea).css({
2807 left: this.twoPageLeftFlipAreaLeft() + 'px',
2808 width: this.twoPageFlipAreaWidth() + 'px'
2810 $(this.twoPage.rightFlipArea).css({
2811 left: this.twoPageRightFlipAreaLeft() + 'px',
2812 width: this.twoPageFlipAreaWidth() + 'px'
2816 // showSearchHilites2UP()
2817 //______________________________________________________________________________
2818 BookReader.prototype.updateSearchHilites2UP = function() {
2820 for (var key in this.searchResults) {
2821 key = parseInt(key, 10);
2822 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2823 var result = this.searchResults[key];
2824 if (null == result.div) {
2825 result.div = document.createElement('div');
2826 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2827 //console.log('appending ' + key);
2830 // We calculate the reduction factor for the specific page because it can be different
2831 // for each page in the spread
2832 var height = this._getPageHeight(key);
2833 var width = this._getPageWidth(key)
2834 var reduce = this.twoPage.height/height;
2835 var scaledW = parseInt(width*reduce);
2837 var gutter = this.twoPageGutter();
2839 if ('L' == this.getPageSide(key)) {
2840 pageL = gutter-scaledW;
2844 var pageT = this.twoPageTop();
2847 width: (result.r-result.l)*reduce + 'px',
2848 height: (result.b-result.t)*reduce + 'px',
2849 left: pageL+(result.l)*reduce + 'px',
2850 top: pageT+(result.t)*reduce +'px'
2854 //console.log(key + ' not displayed');
2855 if (null != this.searchResults[key].div) {
2856 //console.log('removing ' + key);
2857 $(this.searchResults[key].div).remove();
2859 this.searchResults[key].div=null;
2864 // removeSearchHilites()
2865 //______________________________________________________________________________
2866 BookReader.prototype.removeSearchHilites = function() {
2867 for (var key in this.searchResults) {
2868 if (null != this.searchResults[key].div) {
2869 $(this.searchResults[key].div).remove();
2870 this.searchResults[key].div=null;
2876 //______________________________________________________________________________
2877 BookReader.prototype.printPage = function() {
2878 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2880 /* iframe implementation
2882 if (null != this.printPopup) { // check if already showing
2885 this.printPopup = document.createElement("div");
2886 $(this.printPopup).css({
2887 position: 'absolute',
2889 left: ($('#BRcontainer').width()-400)/2 + 'px',
2892 border: "3px double #999999",
2894 backgroundColor: "#fff"
2895 }).appendTo('#BookReader');
2898 if (this.constMode1up == this.mode) {
2899 indexToPrint = this.firstIndex;
2901 indexToPrint = this.twoPage.currentIndexL;
2904 this.indexToPrint = indexToPrint;
2906 var htmlStr = '<div style="text-align: center;">';
2907 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>';
2908 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2909 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2910 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2911 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2912 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2914 htmlStr += '</div>';
2915 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2916 htmlStr += '</div>';
2918 this.printPopup.innerHTML = htmlStr;
2920 var iframe = document.createElement('iframe');
2921 iframe.id = 'printFrame';
2922 iframe.name = 'printFrame';
2923 iframe.width = '233px'; // 8.5 x 11 aspect
2924 iframe.height = '300px';
2926 var self = this; // closure
2928 $(iframe).load(function() {
2929 var doc = BookReader.util.getIFrameDocument(this);
2930 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2933 $('#printDiv').prepend(iframe);
2937 // Get print URI from current indices and mode
2938 BookReader.prototype.getPrintURI = function() {
2940 if (this.constMode2up == this.mode) {
2941 indexToPrint = this.twoPage.currentIndexL;
2943 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2946 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2947 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2948 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2950 if (this.constMode2up == this.mode) {
2951 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2952 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2953 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2955 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2958 return '/bookreader/print.php?' + options;
2961 /* iframe implementation
2962 BookReader.prototype.getPrintFrameContent = function(index) {
2963 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2964 // 8.5x11 so we should end up not overflowing on either paper size.
2965 var paperAspect = 8.5 / 11;
2966 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2970 // Rotate if possible and appropriate, to get larger image size on printed page
2971 if (this.canRotatePage(index)) {
2972 if (imageAspect > 1 && imageAspect > paperAspect) {
2973 // more wide than square, and more wide than paper
2975 imageAspect = 1/imageAspect;
2980 if (imageAspect > paperAspect) {
2981 // wider than paper, fit width
2982 fitAttrs = 'width="95%"';
2984 // taller than paper, fit height
2985 fitAttrs = 'height="95%"';
2988 var imageURL = this._getPageURI(index, 1, rotate);
2989 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2990 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2991 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2992 iframeStr += '</div>';
2993 iframeStr += '</body></html>';
2998 BookReader.prototype.updatePrintFrame = function(delta) {
2999 var newIndex = this.indexToPrint + delta;
3000 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
3001 if (newIndex == this.indexToPrint) {
3004 this.indexToPrint = newIndex;
3005 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
3006 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
3011 //______________________________________________________________________________
3012 BookReader.prototype.showEmbedCode = function() {
3013 if (null != this.embedPopup) { // check if already showing
3017 this.embedPopup = document.createElement("div");
3018 $(this.embedPopup).css({
3019 position: 'absolute',
3021 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
3024 border: "3px double #999999",
3026 backgroundColor: "#fff"
3027 }).appendTo('#BookReader');
3029 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
3030 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>';
3031 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
3032 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
3034 this.embedPopup.innerHTML = htmlStr;
3035 $(this.embedPopup).find('input').bind('click', function() {
3041 //______________________________________________________________________________
3042 BookReader.prototype.autoToggle = function() {
3044 var bComingFrom1up = false;
3045 if (2 != this.mode) {
3046 bComingFrom1up = true;
3050 // Change to autofit if book is too large
3051 if (this.reduce < this.twoPageGetAutofitReduce()) {
3056 if (null == this.autoTimer) {
3057 this.flipSpeed = 2000;
3059 // $$$ Draw events currently cause layout problems when they occur during animation.
3060 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3061 // we workaround for now by not triggering immediate animation in that case.
3062 // See https://bugs.launchpad.net/gnubook/+bug/328327
3063 if (('rl' == this.pageProgression) && bComingFrom1up) {
3064 // don't flip immediately -- wait until timer fires
3067 this.flipFwdToIndex();
3070 $('#BRtoolbar .play').hide();
3071 $('#BRtoolbar .pause').show();
3072 this.autoTimer=setInterval(function(){
3073 if (self.animating) {return;}
3075 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3076 self.flipBackToIndex(1); // $$$ really what we want?
3078 self.flipFwdToIndex();
3087 //______________________________________________________________________________
3088 // Stop autoplay mode, allowing animations to finish
3089 BookReader.prototype.autoStop = function() {
3090 if (null != this.autoTimer) {
3091 clearInterval(this.autoTimer);
3092 this.flipSpeed = 'fast';
3093 $('#BRtoolbar .pause').hide();
3094 $('#BRtoolbar .play').show();
3095 this.autoTimer = null;
3099 // stopFlipAnimations
3100 //______________________________________________________________________________
3101 // Immediately stop flip animations. Callbacks are triggered.
3102 BookReader.prototype.stopFlipAnimations = function() {
3104 this.autoStop(); // Clear timers
3106 // Stop animation, clear queue, trigger callbacks
3107 if (this.leafEdgeTmp) {
3108 $(this.leafEdgeTmp).stop(false, true);
3110 jQuery.each(this.prefetchedImgs, function() {
3111 $(this).stop(false, true);
3114 // And again since animations also queued in callbacks
3115 if (this.leafEdgeTmp) {
3116 $(this.leafEdgeTmp).stop(false, true);
3118 jQuery.each(this.prefetchedImgs, function() {
3119 $(this).stop(false, true);
3124 // keyboardNavigationIsDisabled(event)
3125 // - returns true if keyboard navigation should be disabled for the event
3126 //______________________________________________________________________________
3127 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3128 if (event.target.tagName == "INPUT") {
3134 // gutterOffsetForIndex
3135 //______________________________________________________________________________
3137 // Returns the gutter offset for the spread containing the given index.
3138 // This function supports RTL
3139 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3141 // To find the offset of the gutter from the middle we calculate our percentage distance
3142 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3143 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3145 // But then again for RTL it's the opposite
3146 if ('rl' == this.pageProgression) {
3154 //______________________________________________________________________________
3155 // Returns the width of the leaf edge div for the page with index given
3156 BookReader.prototype.leafEdgeWidth = function(pindex) {
3157 // $$$ could there be single pixel rounding errors for L vs R?
3158 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3159 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3161 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3165 // jumpIndexForLeftEdgePageX
3166 //______________________________________________________________________________
3167 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3168 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3169 if ('rl' != this.pageProgression) {
3170 // LTR - flipping backward
3171 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3173 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3174 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3178 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3179 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3184 // jumpIndexForRightEdgePageX
3185 //______________________________________________________________________________
3186 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3187 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3188 if ('rl' != this.pageProgression) {
3190 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3191 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3194 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3195 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3200 BookReader.prototype.initToolbar = function(mode, ui) {
3202 $("#BookReader").append("<div id='BRtoolbar'>"
3203 + "<span id='BRtoolbarbuttons' style='float: right'>"
3204 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3205 + "<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>"
3206 + "<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>"
3207 + "<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>"
3208 + "<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>"
3209 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3213 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3214 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3215 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3216 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3217 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3218 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3219 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3222 + "<span id='#BRbooktitle'>"
3223 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3227 this.updateToolbarZoom(this.reduce); // Pretty format
3229 if (ui == "embed") {
3230 $("#BookReader a.logo").attr("target","_blank");
3233 // $$$ turn this into a member variable
3234 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3236 // We build in mode 2
3239 this.bindToolbarNavHandlers(jToolbar);
3241 // Setup tooltips -- later we could load these from a file for i18n
3242 var titles = { '.logo': 'Go to Archive.org',
3243 '.zoom_in': 'Zoom in',
3244 '.zoom_out': 'Zoom out',
3245 '.one_page_mode': 'One-page view',
3246 '.two_page_mode': 'Two-page view',
3247 '.thumbnail_mode': 'Thumbnail view',
3248 '.print': 'Print this page',
3249 '.embed': 'Embed bookreader',
3250 '.book_left': 'Flip left',
3251 '.book_right': 'Flip right',
3252 '.book_up': 'Page up',
3253 '.book_down': 'Page down',
3256 '.book_top': 'First page',
3257 '.book_bottom': 'Last page'
3259 if ('rl' == this.pageProgression) {
3260 titles['.book_leftmost'] = 'Last page';
3261 titles['.book_rightmost'] = 'First page';
3263 titles['.book_leftmost'] = 'First page';
3264 titles['.book_rightmost'] = 'Last page';
3267 for (var icon in titles) {
3268 jToolbar.find(icon).attr('title', titles[icon]);
3271 // Hide mode buttons and autoplay if 2up is not available
3272 // $$$ if we end up with more than two modes we should show the applicable buttons
3273 if ( !this.canSwitchToMode(this.constMode2up) ) {
3274 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3277 // Switch to requested mode -- binds other click handlers
3278 this.switchToolbarMode(mode);
3283 // switchToolbarMode
3284 //______________________________________________________________________________
3285 // Update the toolbar for the given mode (changes navigation buttons)
3286 // $$$ we should soon split the toolbar out into its own module
3287 BookReader.prototype.switchToolbarMode = function(mode) {
3290 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3291 $('#BRtoolbar .BRtoolbarmode2').hide();
3292 $('#BRtoolbar .BRtoolbarmode3').hide();
3293 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3294 } else if (2 == mode) {
3296 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3297 $('#BRtoolbar .BRtoolbarmode1').hide();
3298 $('#BRtoolbar .BRtoolbarmode3').hide();
3299 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3302 $('#BRtoolbar .BRtoolbarzoom').hide();
3303 $('#BRtoolbar .BRtoolbarmode2').hide();
3304 $('#BRtoolbar .BRtoolbarmode1').hide();
3305 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3309 // bindToolbarNavHandlers
3310 //______________________________________________________________________________
3311 // Binds the toolbar handlers
3312 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3314 var self = this; // closure
3316 jToolbar.find('.book_left').bind('click', function(e) {
3321 jToolbar.find('.book_right').bind('click', function(e) {
3326 jToolbar.find('.book_up').bind('click', function(e) {
3327 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3335 jToolbar.find('.book_down').bind('click', function(e) {
3336 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3344 jToolbar.find('.print').bind('click', function(e) {
3349 jToolbar.find('.embed').bind('click', function(e) {
3350 self.showEmbedCode();
3354 jToolbar.find('.play').bind('click', function(e) {
3359 jToolbar.find('.pause').bind('click', function(e) {
3364 jToolbar.find('.book_top').bind('click', function(e) {
3369 jToolbar.find('.book_bottom').bind('click', function(e) {
3374 jToolbar.find('.book_leftmost').bind('click', function(e) {
3379 jToolbar.find('.book_rightmost').bind('click', function(e) {
3385 // updateToolbarZoom(reduce)
3386 //______________________________________________________________________________
3387 // Update the displayed zoom factor based on reduction factor
3388 BookReader.prototype.updateToolbarZoom = function(reduce) {
3390 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3393 value = (100 / reduce).toFixed(2);
3394 // Strip trailing zeroes and decimal if all zeroes
3395 value = value.replace(/0+$/,'');
3396 value = value.replace(/\.$/,'');
3399 $('#BRzoom').text(value);
3402 // firstDisplayableIndex
3403 //______________________________________________________________________________
3404 // Returns the index of the first visible page, dependent on the mode.
3405 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3406 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3407 BookReader.prototype.firstDisplayableIndex = function() {
3408 if (this.mode != this.constMode2up) {
3412 if ('rl' != this.pageProgression) {
3414 if (this.getPageSide(0) == 'L') {
3421 if (this.getPageSide(0) == 'R') {
3429 // lastDisplayableIndex
3430 //______________________________________________________________________________
3431 // Returns the index of the last visible page, dependent on the mode.
3432 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3433 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3434 BookReader.prototype.lastDisplayableIndex = function() {
3436 var lastIndex = this.numLeafs - 1;
3438 if (this.mode != this.constMode2up) {
3442 if ('rl' != this.pageProgression) {
3444 if (this.getPageSide(lastIndex) == 'R') {
3447 return lastIndex + 1;
3451 if (this.getPageSide(lastIndex) == 'L') {
3454 return lastIndex + 1;
3459 // shortTitle(maximumCharacters)
3461 // Returns a shortened version of the title with the maximum number of characters
3462 BookReader.prototype.shortTitle = function(maximumCharacters) {
3463 if (this.bookTitle.length < maximumCharacters) {
3464 return this.bookTitle;
3467 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3472 // Parameter related functions
3474 // updateFromParams(params)
3476 // Update ourselves from the params object.
3478 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3479 BookReader.prototype.updateFromParams = function(params) {
3480 if ('undefined' != typeof(params.mode)) {
3481 this.switchMode(params.mode);
3485 if ('undefined' != typeof(params.searchTerm)) {
3486 if (this.searchTerm != params.searchTerm) {
3487 this.search(params.searchTerm);
3491 // $$$ process /zoom
3493 // We only respect page if index is not set
3494 if ('undefined' != typeof(params.index)) {
3495 if (params.index != this.currentIndex()) {
3496 this.jumpToIndex(params.index);
3498 } else if ('undefined' != typeof(params.page)) {
3499 // $$$ this assumes page numbers are unique
3500 if (params.page != this.getPageNum(this.currentIndex())) {
3501 this.jumpToPage(params.page);
3505 // $$$ process /region
3506 // $$$ process /highlight
3509 // paramsFromFragment(urlFragment)
3511 // Returns a object with configuration parametes from a URL fragment.
3513 // E.g paramsFromFragment(window.location.hash)
3514 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3515 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3519 // For convenience we allow an initial # character (as from window.location.hash)
3520 // but don't require it
3521 if (urlFragment.substr(0,1) == '#') {
3522 urlFragment = urlFragment.substr(1);
3525 // Simple #nn syntax
3526 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3527 if ( !isNaN(oldStyleLeafNum) ) {
3528 params.index = oldStyleLeafNum;
3530 // Done processing if using old-style syntax
3534 // Split into key-value pairs
3535 var urlArray = urlFragment.split('/');
3537 for (var i = 0; i < urlArray.length; i += 2) {
3538 urlHash[urlArray[i]] = urlArray[i+1];
3542 if ('1up' == urlHash['mode']) {
3543 params.mode = this.constMode1up;
3544 } else if ('2up' == urlHash['mode']) {
3545 params.mode = this.constMode2up;
3546 } else if ('thumb' == urlHash['mode']) {
3547 params.mode = this.constModeThumb;
3551 if ('undefined' != typeof(urlHash['page'])) {
3552 // page was set -- may not be int
3553 params.page = urlHash['page'];
3556 // $$$ process /region
3557 // $$$ process /search
3559 if (urlHash['search'] != undefined) {
3560 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3563 // $$$ process /highlight
3568 // paramsFromCurrent()
3570 // Create a params object from the current parameters.
3571 BookReader.prototype.paramsFromCurrent = function() {
3575 var index = this.currentIndex();
3576 var pageNum = this.getPageNum(index);
3577 if ((pageNum === 0) || pageNum) {
3578 params.page = pageNum;
3581 params.index = index;
3582 params.mode = this.mode;
3588 if (this.searchHighlightVisible()) {
3589 params.searchTerm = this.searchTerm;
3595 // fragmentFromParams(params)
3597 // Create a fragment string from the params object.
3598 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3599 BookReader.prototype.fragmentFromParams = function(params) {
3600 var separator = '/';
3604 if ('undefined' != typeof(params.page)) {
3605 fragments.push('page', params.page);
3607 // Don't have page numbering -- use index instead
3608 fragments.push('page', 'n' + params.index);
3615 if ('undefined' != typeof(params.mode)) {
3616 if (params.mode == this.constMode1up) {
3617 fragments.push('mode', '1up');
3618 } else if (params.mode == this.constMode2up) {
3619 fragments.push('mode', '2up');
3620 } else if (params.mode == this.constModeThumb) {
3621 fragments.push('mode', 'thumb');
3623 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3628 if (params.searchTerm) {
3629 fragments.push('search', params.searchTerm);
3632 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3635 // getPageIndex(pageNum)
3637 // Returns the *highest* index the given page number, or undefined
3638 BookReader.prototype.getPageIndex = function(pageNum) {
3639 var pageIndices = this.getPageIndices(pageNum);
3641 if (pageIndices.length > 0) {
3642 return pageIndices[pageIndices.length - 1];
3648 // getPageIndices(pageNum)
3650 // Returns an array (possibly empty) of the indices with the given page number
3651 BookReader.prototype.getPageIndices = function(pageNum) {
3654 // Check for special "nXX" page number
3655 if (pageNum.slice(0,1) == 'n') {
3657 var pageIntStr = pageNum.slice(1, pageNum.length);
3658 var pageIndex = parseInt(pageIntStr);
3659 indices.push(pageIndex);
3662 // Do nothing... will run through page names and see if one matches
3667 for (i=0; i<this.numLeafs; i++) {
3668 if (this.getPageNum(i) == pageNum) {
3676 // getPageName(index)
3678 // Returns the name of the page as it should be displayed in the user interface
3679 BookReader.prototype.getPageName = function(index) {
3680 return 'Page ' + this.getPageNum(index);
3683 // updateLocationHash
3685 // Update the location hash from the current parameters. Call this instead of manually
3686 // using window.location.replace
3687 BookReader.prototype.updateLocationHash = function() {
3688 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3689 window.location.replace(newHash);
3691 // This is the variable checked in the timer. Only user-generated changes
3692 // to the URL will trigger the event.
3693 this.oldLocationHash = newHash;
3696 // startLocationPolling
3698 // Starts polling of window.location to see hash fragment changes
3699 BookReader.prototype.startLocationPolling = function() {
3700 var self = this; // remember who I am
3701 self.oldLocationHash = window.location.hash;
3703 if (this.locationPollId) {
3704 clearInterval(this.locationPollID);
3705 this.locationPollId = null;
3708 this.locationPollId = setInterval(function() {
3709 var newHash = window.location.hash;
3710 if (newHash != self.oldLocationHash) {
3711 if (newHash != self.oldUserHash) { // Only process new user hash once
3712 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3714 // Queue change if animating
3715 if (self.animating) {
3717 self.animationFinishedCallback = function() {
3718 self.updateFromParams(self.paramsFromFragment(newHash));
3720 } else { // update immediately
3721 self.updateFromParams(self.paramsFromFragment(newHash));
3723 self.oldUserHash = newHash;
3731 // Returns true if we can switch to the requested mode
3732 BookReader.prototype.canSwitchToMode = function(mode) {
3733 if (mode == this.constMode2up) {
3734 // check there are enough pages to display
3735 // $$$ this is a workaround for the mis-feature that we can't display
3736 // short books in 2up mode
3737 if (this.numLeafs < 6) {
3745 // searchHighlightVisible
3747 // Returns true if a search highlight is currently being displayed
3748 BookReader.prototype.searchHighlightVisible = function() {
3749 if (this.constMode2up == this.mode) {
3750 if (this.searchResults[this.twoPage.currentIndexL]
3751 || this.searchResults[this.twoPage.currentIndexR]) {
3755 if (this.searchResults[this.currentIndex()]) {
3762 // getPageBackgroundColor
3764 // Returns a CSS property string for the background color for the given page
3765 // $$$ turn into regular CSS?
3766 BookReader.prototype.getPageBackgroundColor = function(index) {
3767 if (index >= 0 && index < this.numLeafs) {
3769 return this.pageDefaultBackgroundColor;
3777 // Returns the page width for the given index, or first or last page if out of range
3778 BookReader.prototype._getPageWidth = function(index) {
3779 // Synthesize a page width for pages not actually present in book.
3780 // May or may not be the best approach.
3781 // If index is out of range we return the width of first or last page
3782 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3783 return this.getPageWidth(index);
3788 // Returns the page height for the given index, or first or last page if out of range
3789 BookReader.prototype._getPageHeight= function(index) {
3790 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3791 return this.getPageHeight(index);
3796 // Returns the page URI or transparent image if out of range
3797 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3798 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3799 return this.imagesBaseURL + "/transparent.png";
3802 if ('undefined' == typeof(reduce)) {
3803 // reduce not passed in
3804 // $$$ this probably won't work for thumbnail mode
3805 var ratio = this.getPageHeight(index) / this.twoPage.height;
3807 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3810 } else if (ratio < 4) {
3812 } else if (ratio < 8) {
3814 } else if (ratio < 16) {
3816 } else if (ratio < 32) {
3824 return this.getPageURI(index, reduce, rotate);
3827 // Library functions
3829 disableSelect: function(jObject) {
3830 // Bind mouse handlers
3831 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3832 jObject.bind('mousedown', function(e) {
3833 // $$$ check here for right-click and don't disable. Also use jQuery style
3834 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3837 // Special hack for IE7
3838 jObject[0].onselectstart = function(e) { return false; };
3841 clamp: function(value, min, max) {
3842 return Math.min(Math.max(value, min), max);
3845 notInArray: function(value, array) {
3846 // inArray returns -1 or undefined if value not in array
3847 return ! (jQuery.inArray(value, array) >= 0);
3850 getIFrameDocument: function(iframe) {
3851 // Adapted from http://xkr.us/articles/dom/iframe-document/
3852 var outer = (iframe.contentWindow || iframe.contentDocument);
3853 return (outer.document || outer);
3856 decodeURIComponentPlus: function(value) {
3857 // Decodes a URI component and converts '+' to ' '
3858 return decodeURIComponent(value).replace(/\+/g, ' ');
3861 encodeURIComponentPlus: function(value) {
3862 // Encodes a URI component and converts ' ' to '+'
3863 return encodeURIComponent(value).replace(/%20/g, '+');
3865 // The final property here must NOT have a comma after it - IE7