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;
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 // $$$ provide finer grained zooming
87 this.reductionFactors = [ {reduce: 0.5, autofit: null},
88 {reduce: 1, autofit: null},
89 {reduce: 2, autofit: null},
90 {reduce: 4, autofit: null},
91 {reduce: 8, autofit: null},
92 {reduce: 16, autofit: null} ];
94 // Object to hold parameters related to 1up mode
96 autofit: 'height' // valid values are height, width, none
99 // Object to hold parameters related to 2up mode
101 coverInternalPadding: 10, // Width of cover
102 coverExternalPadding: 10, // Padding outside of cover
103 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
107 // Text-to-Speech params
108 this.ttsIndex = null; //leaf index
109 this.ttsPosition = -1; //chunk (paragraph) number
116 //______________________________________________________________________________
117 BookReader.prototype.init = function() {
119 var startIndex = undefined;
120 this.pageScale = this.reduce; // preserve current reduce
122 // Find start index and mode if set in location hash
123 var params = this.paramsFromFragment(window.location.hash);
125 if ('undefined' != typeof(params.index)) {
126 startIndex = params.index;
127 } else if ('undefined' != typeof(params.page)) {
128 startIndex = this.getPageIndex(params.page);
131 if ('undefined' == typeof(startIndex)) {
132 if ('undefined' != typeof(this.titleLeaf)) {
133 startIndex = this.leafNumToIndex(this.titleLeaf);
137 if ('undefined' == typeof(startIndex)) {
141 if ('undefined' != typeof(params.mode)) {
142 this.mode = params.mode;
145 // Set document title -- may have already been set in enclosing html for
146 // search engine visibility
147 document.title = this.shortTitle(50);
149 // Sanitize parameters
150 if ( !this.canSwitchToMode( this.mode ) ) {
151 this.mode = this.constMode1up;
154 $("#BookReader").empty();
156 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
157 $("#BookReader").append("<div id='BRcontainer'></div>");
158 $("#BRcontainer").append("<div id='BRpageview'></div>");
160 $("#BRcontainer").bind('scroll', this, function(e) {
164 this.setupKeyListeners();
165 this.startLocationPolling();
167 $(window).bind('resize', this, function(e) {
168 //console.log('resize!');
169 if (1 == e.data.mode) {
170 //console.log('centering 1page view');
171 if (e.data.autofit) {
172 e.data.resizePageView();
174 e.data.centerPageView();
175 $('#BRpageview').empty()
176 e.data.displayedIndices = [];
177 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
179 } else if (3 == e.data.mode){
180 e.data.prepareThumbnailView();
182 //console.log('drawing 2 page view');
184 // We only need to prepare again in autofit (size of spread changes)
185 if (e.data.twoPage.autofit) {
186 e.data.prepareTwoPageView();
188 // Re-center if the scrollbars have disappeared
189 var center = e.data.twoPageGetViewCenter();
190 var doRecenter = false;
191 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
192 center.percentageX = 0.5;
195 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
196 center.percentageY = 0.5;
200 e.data.twoPageCenterView(center.percentageX, center.percentageY);
206 $('.BRpagediv1up').bind('mousedown', this, function(e) {
207 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
208 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
212 // $$$ refactor this so it's enough to set the first index and call preparePageView
213 // (get rid of mode-specific logic at this point)
214 if (1 == this.mode) {
215 this.firstIndex = startIndex;
216 this.prepareOnePageView();
217 this.jumpToIndex(startIndex);
218 } else if (3 == this.mode) {
219 this.firstIndex = startIndex;
220 this.prepareThumbnailView();
221 this.jumpToIndex(startIndex);
223 //this.resizePageView();
225 this.displayedIndices=[0];
226 this.firstIndex = startIndex;
227 this.displayedIndices = [this.firstIndex];
228 //console.log('titleLeaf: %d', this.titleLeaf);
229 //console.log('displayedIndices: %s', this.displayedIndices);
230 this.prepareTwoPageView();
233 // Enact other parts of initial params
234 this.updateFromParams(params);
237 BookReader.prototype.setupKeyListeners = function() {
250 // We use document here instead of window to avoid a bug in jQuery on IE7
251 $(document).keydown(function(e) {
253 // Keyboard navigation
254 if (!self.keyboardNavigationIsDisabled(e)) {
258 // In 1up mode page scrolling is handled by browser
259 if (2 == self.mode) {
266 if (2 == self.mode) {
280 if (2 == self.mode) {
286 if (2 == self.mode) {
297 //______________________________________________________________________________
298 BookReader.prototype.drawLeafs = function() {
299 if (1 == this.mode) {
300 this.drawLeafsOnePage();
301 } else if (3 == this.mode) {
302 this.drawLeafsThumbnail();
304 this.drawLeafsTwoPage();
309 // bindGestures(jElement)
310 //______________________________________________________________________________
311 BookReader.prototype.bindGestures = function(jElement) {
313 jElement.unbind('gesturechange').bind('gesturechange', function(e) {
315 if (e.originalEvent.scale > 1.5) {
317 } else if (e.originalEvent.scale < 0.6) {
324 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
325 //console.log('setting handler');
326 //console.log(element.tagName);
328 $(element).unbind('tap').bind('tap', data, function(e) {
333 // drawLeafsOnePage()
334 //______________________________________________________________________________
335 BookReader.prototype.drawLeafsOnePage = function() {
336 //alert('drawing leafs!');
340 var scrollTop = $('#BRcontainer').attr('scrollTop');
341 var scrollBottom = scrollTop + $('#BRcontainer').height();
342 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
344 var indicesToDisplay = [];
349 for (i=0; i<this.numLeafs; i++) {
350 var height = parseInt(this._getPageHeight(i)/this.reduce);
352 leafBottom += height;
353 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
354 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
355 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
356 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
357 if (topInView | bottomInView | middleInView) {
358 //console.log('displayed: ' + this.displayedIndices);
359 //console.log('to display: ' + i);
360 indicesToDisplay.push(i);
362 leafTop += height +10;
366 var firstIndexToDraw = indicesToDisplay[0];
367 this.firstIndex = firstIndexToDraw;
369 // Update hash, but only if we're currently displaying a leaf
370 // Hack that fixes #365790
371 if (this.displayedIndices.length > 0) {
372 this.updateLocationHash();
375 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
377 indicesToDisplay.unshift(firstIndexToDraw);
380 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
381 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
382 indicesToDisplay.push(lastIndexToDraw+1);
387 for (i=0; i<firstIndexToDraw; i++) {
388 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
391 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
392 var viewWidth = $('#BRcontainer').attr('scrollWidth');
395 for (i=0; i<indicesToDisplay.length; i++) {
396 var index = indicesToDisplay[i];
397 var height = parseInt(this._getPageHeight(index)/this.reduce);
399 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
400 var width = parseInt(this._getPageWidth(index)/this.reduce);
401 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
402 var div = document.createElement("div");
403 div.className = 'BRpagediv1up';
404 div.id = 'pagediv'+index;
405 div.style.position = "absolute";
406 $(div).css('top', leafTop + 'px');
407 var left = (viewWidth-width)>>1;
408 if (left<0) left = 0;
409 $(div).css('left', left+'px');
410 $(div).css('width', width+'px');
411 $(div).css('height', height+'px');
412 //$(div).text('loading...');
414 $('#BRpageview').append(div);
416 var img = document.createElement("img");
417 img.src = this._getPageURI(index, this.reduce, 0);
418 $(img).css('width', width+'px');
419 $(img).css('height', height+'px');
423 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
426 leafTop += height +10;
430 for (i=0; i<this.displayedIndices.length; i++) {
431 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
432 var index = this.displayedIndices[i];
433 //console.log('Removing leaf ' + index);
434 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
435 $('#pagediv'+index).remove();
437 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
441 this.displayedIndices = indicesToDisplay.slice();
442 this.updateSearchHilites();
444 if (null != this.getPageNum(firstIndexToDraw)) {
445 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
447 $("#BRpagenum").val('');
450 this.updateToolbarZoom(this.reduce);
454 // drawLeafsThumbnail()
455 //______________________________________________________________________________
456 // If seekIndex is defined, the view will be drawn with that page visible (without any
457 // animated scrolling)
458 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
459 //alert('drawing leafs!');
462 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
464 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
478 // Will be set to top of requested seek index, if set
481 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
482 for (i=0; i<this.numLeafs; i++) {
483 leafWidth = this.thumbWidth;
484 if (rightPos + (leafWidth + this.padding) > viewWidth){
490 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
491 if (leafMap[currentRow].leafs===undefined) {
492 leafMap[currentRow].leafs = [];
493 leafMap[currentRow].height = 0;
494 leafMap[currentRow].top = 0;
496 leafMap[currentRow].leafs[leafIndex] = {};
497 leafMap[currentRow].leafs[leafIndex].num = i;
498 leafMap[currentRow].leafs[leafIndex].left = rightPos;
500 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
501 if (leafHeight > leafMap[currentRow].height) {
502 leafMap[currentRow].height = leafHeight;
504 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
505 rightPos += leafWidth + this.padding;
506 if (rightPos > maxRight) { maxRight = rightPos; }
509 if (i == seekIndex) {
510 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
514 // reset the bottom position based on thumbnails
515 $('#BRpageview').height(bottomPos);
517 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
519 // If seekTop is defined, seeking was requested and target found
520 if (typeof(seekTop) != 'undefined') {
521 $('#BRcontainer').scrollTop( seekTop );
524 var scrollTop = $('#BRcontainer').attr('scrollTop');
525 var scrollBottom = scrollTop + $('#BRcontainer').height();
529 var rowsToDisplay = [];
531 // Visible leafs with least/greatest index
532 var leastVisible = this.numLeafs - 1;
535 // Determine the thumbnails in view
536 for (i=0; i<leafMap.length; i++) {
537 leafBottom += this.padding + leafMap[i].height;
538 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
539 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
540 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
541 if (topInView | bottomInView | middleInView) {
542 //console.log('row to display: ' + j);
543 rowsToDisplay.push(i);
544 if (leafMap[i].leafs[0].num < leastVisible) {
545 leastVisible = leafMap[i].leafs[0].num;
547 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
548 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
551 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
552 leafTop = leafBottom;
555 // create a buffer of preloaded rows before and after the visible rows
556 var firstRow = rowsToDisplay[0];
557 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
558 for (i=1; i<this.thumbRowBuffer+1; i++) {
559 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
561 for (i=1; i<this.thumbRowBuffer+1; i++) {
562 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
565 // Create the thumbnail divs and images (lazy loaded)
574 for (i=0; i<rowsToDisplay.length; i++) {
575 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
576 row = rowsToDisplay[i];
578 for (j=0; j<leafMap[row].leafs.length; j++) {
580 leaf = leafMap[row].leafs[j].num;
582 leafWidth = this.thumbWidth;
583 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
584 leafTop = leafMap[row].top;
585 left = leafMap[row].leafs[index].left + pageViewBuffer;
586 if ('rl' == this.pageProgression){
587 left = viewWidth - leafWidth - left;
590 div = document.createElement("div");
591 div.id = 'pagediv'+leaf;
592 div.style.position = "absolute";
593 div.className = "BRpagedivthumb";
595 left += this.padding;
596 $(div).css('top', leafTop + 'px');
597 $(div).css('left', left+'px');
598 $(div).css('width', leafWidth+'px');
599 $(div).css('height', leafHeight+'px');
600 //$(div).text('loading...');
602 // link to page in single page mode
603 link = document.createElement("a");
604 $(link).data('leaf', leaf);
605 $(link).bind('tap', function(event) {
606 self.firstIndex = $(this).data('leaf');
607 self.switchMode(self.constMode1up);
608 event.preventDefault();
611 // $$$ we don't actually go to this URL (click is handled in handler above)
612 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
615 $('#BRpageview').append(div);
617 img = document.createElement("img");
618 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
620 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
621 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
622 .addClass('BRlazyload')
623 // Store the URL of the image that will replace this one
624 .data('srcURL', this._getPageURI(leaf, thumbReduce));
626 //console.log('displaying thumbnail: ' + leaf);
631 // Remove thumbnails that are not to be displayed
633 for (i=0; i<this.displayedRows.length; i++) {
634 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
635 row = this.displayedRows[i];
637 // $$$ Safari doesn't like the comprehension
638 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
639 //console.log('Removing row ' + row + ' ' + rowLeafs);
641 for (k=0; k<leafMap[row].leafs.length; k++) {
642 index = leafMap[row].leafs[k].num;
643 //console.log('Removing leaf ' + index);
644 $('#pagediv'+index).remove();
648 var mRow = this.displayedRows[i];
649 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
650 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
655 // Update which page is considered current to make sure a visible page is the current one
656 var currentIndex = this.currentIndex();
657 // console.log('current ' + currentIndex);
658 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
659 if (currentIndex < leastVisible) {
660 this.setCurrentIndex(leastVisible);
661 } else if (currentIndex > mostVisible) {
662 this.setCurrentIndex(mostVisible);
665 this.displayedRows = rowsToDisplay.slice();
667 // Update hash, but only if we're currently displaying a leaf
668 // Hack that fixes #365790
669 if (this.displayedRows.length > 0) {
670 this.updateLocationHash();
673 // remove previous highlights
674 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
676 // highlight current page
677 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
679 this.lazyLoadThumbnails();
681 // Update page number box. $$$ refactor to function
682 if (null !== this.getPageNum(this.currentIndex())) {
683 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
685 $("#BRpagenum").val('');
688 this.updateToolbarZoom(this.reduce);
691 BookReader.prototype.lazyLoadThumbnails = function() {
693 // console.log('lazy load');
695 // We check the complete property since load may not be fired if loading from the cache
696 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
698 var loading = $('.BRlazyloading').length;
699 var toLoad = this.thumbMaxLoading - loading;
701 // console.log(' ' + loading + ' thumbnails loading');
702 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
707 // $$$ TODO load those near top (but not beyond) page view first
708 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
709 self.lazyLoadImage(this);
714 BookReader.prototype.lazyLoadImage = function (dummyImage) {
715 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
717 var img = new Image();
721 .addClass('BRlazyloading')
722 .one('load', function() {
723 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
725 $(this).removeClass('BRlazyloading');
727 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
728 // we call the function after a slight delay. Also the img.complete property
729 // is not yet set in IE8 inside this onload handler
730 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
732 .one('error', function() {
733 // Remove class so we no longer count as loading
734 $(this).removeClass('BRlazyloading');
736 .attr( { width: $(dummyImage).width(),
737 height: $(dummyImage).height(),
738 src: $(dummyImage).data('srcURL')
741 // replace with the new img
742 $(dummyImage).before(img).remove();
744 img = null; // tidy up closure
748 // drawLeafsTwoPage()
749 //______________________________________________________________________________
750 BookReader.prototype.drawLeafsTwoPage = function() {
751 var scrollTop = $('#BRtwopageview').attr('scrollTop');
752 var scrollBottom = scrollTop + $('#BRtwopageview').height();
754 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
756 var indexL = this.twoPage.currentIndexL;
758 var heightL = this._getPageHeight(indexL);
759 var widthL = this._getPageWidth(indexL);
761 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
762 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
763 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
764 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
765 //console.log(leafEdgeWidthL);
767 var middle = this.twoPage.middle; // $$$ getter instead?
768 var top = this.twoPageTop();
769 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
771 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
772 this.twoPage.gutter = this.twoPageGutter();
774 this.prefetchImg(indexL);
775 $(this.prefetchedImgs[indexL]).css({
776 position: 'absolute',
777 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
780 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
781 width: this.twoPage.scaledWL + 'px',
782 borderRight: '1px solid black',
784 }).appendTo('#BRtwopageview');
786 var indexR = this.twoPage.currentIndexR;
787 var heightR = this._getPageHeight(indexR);
788 var widthR = this._getPageWidth(indexR);
790 // $$$ should use getwidth2up?
791 //var scaledWR = this.twoPage.height*widthR/heightR;
792 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
793 this.prefetchImg(indexR);
794 $(this.prefetchedImgs[indexR]).css({
795 position: 'absolute',
796 left: this.twoPage.gutter+'px',
799 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
800 width: this.twoPage.scaledWR + 'px',
801 borderLeft: '1px solid black',
803 }).appendTo('#BRtwopageview');
806 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
807 this.setMouseHandlers2UP();
808 this.twoPageSetCursor();
810 this.updatePageNumBox2UP();
811 this.updateToolbarZoom(this.reduce);
813 // this.twoPagePlaceFlipAreas(); // No longer used
817 // updatePageNumBox2UP
818 //______________________________________________________________________________
819 BookReader.prototype.updatePageNumBox2UP = function() {
820 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
821 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
823 $("#BRpagenum").val('');
825 this.updateLocationHash();
829 //______________________________________________________________________________
830 BookReader.prototype.loadLeafs = function() {
834 if (null == this.timer) {
835 this.timer=setTimeout(function(){self.drawLeafs()},250);
837 clearTimeout(this.timer);
838 this.timer=setTimeout(function(){self.drawLeafs()},250);
844 // Pass 1 to zoom in, anything else to zoom out
845 //______________________________________________________________________________
846 BookReader.prototype.zoom = function(direction) {
848 case this.constMode1up:
849 if (direction == 1) {
851 return this.zoom1up('in');
853 return this.zoom1up('out');
856 case this.constMode2up:
857 if (direction == 1) {
859 return this.zoom2up('in');
861 return this.zoom2up('out');
864 case this.constModeThumb:
865 // XXX update zoomThumb for named directions
866 return this.zoomThumb(direction);
872 //______________________________________________________________________________
873 BookReader.prototype.zoom1up = function(direction) {
875 if (2 == this.mode) { //can only zoom in 1-page mode
880 var reduceFactor = this.nextReduce(this.reduce, direction, this.onePage.reductionFactors);
882 if (this.reduce == reduceFactor.reduce) {
883 // Already at this level
887 this.reduce = reduceFactor.reduce; // $$$ incorporate into function
888 this.onePage.autofit = reduceFactor.autofit;
890 this.pageScale = this.reduce; // preserve current reduce
891 this.resizePageView();
893 $('#BRpageview').empty()
894 this.displayedIndices = [];
897 this.updateToolbarZoom(this.reduce);
899 // Recalculate search hilites
900 this.removeSearchHilites();
901 this.updateSearchHilites();
906 //______________________________________________________________________________
907 BookReader.prototype.resizePageView = function() {
909 // $$$ This code assumes 1up mode
910 // e.g. does not preserve position in thumbnail mode
911 // See http://bugs.launchpad.net/bookreader/+bug/552972
914 case this.constMode1up:
915 case this.constMode2up:
916 this.resizePageView1up();
918 case this.constModeThumb:
919 this.prepareThumbnailView( this.currentIndex() );
922 alert('Resize not implemented for this mode');
926 BookReader.prototype.resizePageView1up = function() {
929 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
930 var viewWidth = $('#BRcontainer').attr('clientWidth');
932 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
933 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
934 var oldPageViewHeight = $('#BRpageview').height();
935 var oldPageViewWidth = $('#BRpageview').width();
937 var oldCenterY = this.centerY1up();
938 var oldCenterX = this.centerX1up();
940 if (0 != oldPageViewHeight) {
941 var scrollRatio = oldCenterY / oldPageViewHeight;
946 // Recalculate 1up reduction factors
947 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'),
948 $('#BRcontainer').attr('clientHeight') );
949 // Update current reduce (if in autofit)
950 if (this.onePage.autofit) {
951 var reductionFactor = this.nextReduce(this.reduce, this.onePage.autofit, this.onePage.reductionFactors);
952 this.reduce = reductionFactor.reduce;
955 for (i=0; i<this.numLeafs; i++) {
956 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
957 var width = parseInt(this._getPageWidth(i)/this.reduce);
958 if (width>viewWidth) viewWidth=width;
960 $('#BRpageview').height(viewHeight);
961 $('#BRpageview').width(viewWidth);
963 var newCenterY = scrollRatio*viewHeight;
964 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
965 $('#BRcontainer').attr('scrollTop', newTop);
967 // We use clientWidth here to avoid miscalculating due to scroll bar
968 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
969 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
970 newLeft = Math.max(newLeft, 0);
971 $('#BRcontainer').attr('scrollLeft', newLeft);
972 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
974 //this.centerPageView();
977 this.removeSearchHilites();
978 this.updateSearchHilites();
983 //______________________________________________________________________________
984 // Returns the current offset of the viewport center in scaled document coordinates.
985 BookReader.prototype.centerX1up = function() {
987 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
988 centerX = $('#BRpageview').width();
990 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
992 centerX = Math.floor(centerX);
997 //______________________________________________________________________________
998 // Returns the current offset of the viewport center in scaled document coordinates.
999 BookReader.prototype.centerY1up = function() {
1000 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1001 return Math.floor(centerY);
1005 //______________________________________________________________________________
1006 BookReader.prototype.centerPageView = function() {
1008 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1009 var clientWidth = $('#BRcontainer').attr('clientWidth');
1010 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1011 if (scrollWidth > clientWidth) {
1012 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1017 // zoom2up(direction)
1018 //______________________________________________________________________________
1019 BookReader.prototype.zoom2up = function(direction) {
1021 // Hard stop autoplay
1022 this.stopFlipAnimations();
1024 // Recalculate autofit factors
1025 this.twoPageCalculateReductionFactors();
1027 // Get new zoom state
1028 var reductionFactor = this.nextReduce(this.reduce, direction, this.twoPage.reductionFactors);
1029 if ((this.reduce == reductionFactor.reduce) && (this.twoPage.autofit == reductionFactor.autofit)) {
1033 this.twoPage.autofit = reductionFactor.autofit;
1034 this.reduce = reductionFactor.reduce;
1035 this.pageScale = this.reduce; // preserve current reduce
1037 // Preserve view center position
1038 var oldCenter = this.twoPageGetViewCenter();
1040 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1041 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1042 if (1 == direction) {
1043 for (var img in this.prefetchedImgs) {
1044 delete this.prefetchedImgs[img];
1048 // Prepare view with new center to minimize visual glitches
1049 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1052 BookReader.prototype.zoomThumb = function(direction) {
1053 var oldColumns = this.thumbColumns;
1054 switch (direction) {
1056 this.thumbColumns += 1;
1059 this.thumbColumns -= 1;
1064 if (this.thumbColumns < 2) {
1065 this.thumbColumns = 2;
1066 } else if (this.thumbColumns > 8) {
1067 this.thumbColumns = 8;
1070 if (this.thumbColumns != oldColumns) {
1071 this.prepareThumbnailView();
1075 // Returns the width per thumbnail to display the requested number of columns
1076 // Note: #BRpageview must already exist since its width is used to calculate the
1078 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1079 var padding = (thumbnailColumns + 1) * this.padding;
1080 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1081 return parseInt(width);
1084 // quantizeReduce(reduce)
1085 //______________________________________________________________________________
1086 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1087 BookReader.prototype.quantizeReduce = function(reduce, reductionFactors) {
1088 var quantized = reductionFactors[0].reduce;
1089 var distance = Math.abs(reduce - quantized);
1090 for (var i = 1; i < reductionFactors.length; i++) {
1091 newDistance = Math.abs(reduce - reductionFactors[i].reduce);
1092 if (newDistance < distance) {
1093 distance = newDistance;
1094 quantized = reductionFactors[i].reduce;
1101 // reductionFactors should be array of sorted reduction factors
1102 // e.g. [ {reduce: 0.25, autofit: null}, {reduce: 0.3, autofit: 'width'}, {reduce: 1, autofit: null} ]
1103 BookReader.prototype.nextReduce = function( currentReduce, direction, reductionFactors ) {
1105 // XXX add 'closest', to replace quantize function
1107 if (direction == 'in') {
1108 var newReduceIndex = 0;
1110 for (var i = 1; i < reductionFactors.length; i++) {
1111 if (reductionFactors[i].reduce < currentReduce) {
1115 return reductionFactors[newReduceIndex];
1117 } else if (direction == 'out') { // zoom out
1118 var lastIndex = reductionFactors.length - 1;
1119 var newReduceIndex = lastIndex;
1121 for (var i = lastIndex; i >= 0; i--) {
1122 if (reductionFactors[i].reduce > currentReduce) {
1126 return reductionFactors[newReduceIndex];
1129 // Asked for specific autofit mode
1130 for (var i = 0; i < reductionFactors.length; i++) {
1131 if (reductionFactors[i].autofit == direction) {
1132 return reductionFactors[i];
1136 alert('Could not find reduction factor for direction ' + direction);
1137 return reductionFactors[0];
1141 BookReader.prototype._reduceSort = function(a, b) {
1142 return a.reduce - b.reduce;
1146 //______________________________________________________________________________
1147 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1148 BookReader.prototype.jumpToPage = function(pageNum) {
1150 var pageIndex = this.getPageIndex(pageNum);
1152 if ('undefined' != typeof(pageIndex)) {
1155 this.jumpToIndex(pageIndex);
1156 $('#BRcontainer').attr('scrollTop', leafTop);
1165 //______________________________________________________________________________
1166 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1168 if (this.constMode2up == this.mode) {
1171 // By checking against min/max we do nothing if requested index
1173 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1174 this.flipBackToIndex(index);
1175 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1176 this.flipFwdToIndex(index);
1179 } else if (this.constModeThumb == this.mode) {
1180 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1190 for (i=0; i<(index+1); i++) {
1191 leafWidth = this.thumbWidth;
1192 if (rightPos + (leafWidth + this.padding) > viewWidth){
1198 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1199 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1200 if (leafIndex==0) { leafTop = bottomPos; }
1201 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1202 rightPos += leafWidth + this.padding;
1205 this.firstIndex=index;
1206 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1209 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1217 for (i=0; i<index; i++) {
1218 h = parseInt(this._getPageHeight(i)/this.reduce);
1219 leafTop += h + this.padding;
1223 //console.log('pageY ' + pageY);
1224 var offset = parseInt( (pageY) / this.reduce);
1225 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1226 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1229 // Show page just a little below the top
1230 leafTop -= this.padding / 2;
1234 var offset = parseInt( (pageX) / this.reduce);
1235 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1238 // Preserve left position
1239 leafLeft = $('#BRcontainer').scrollLeft();
1242 //$('#BRcontainer').attr('scrollTop', leafTop);
1243 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1249 //______________________________________________________________________________
1250 BookReader.prototype.switchMode = function(mode) {
1252 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1254 if (mode == this.mode) {
1258 if (!this.canSwitchToMode(mode)) {
1263 this.removeSearchHilites();
1266 this.switchToolbarMode(mode);
1268 // reinstate scale if moving from thumbnail view
1269 if (this.pageScale != this.reduce) {
1270 this.reduce = this.pageScale;
1273 // $$$ TODO preserve center of view when switching between mode
1274 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1276 // XXX maybe better to preserve zoom in each mode
1278 this.onePageCalculateReductionFactors( $('#BRcontainer').attr('clientWidth'), $('#BRcontainer').attr('clientHeight'));
1279 this.reduce = this.quantizeReduce(this.reduce, this.onePage.reductionFactors);
1280 this.prepareOnePageView();
1281 } else if (3 == mode) {
1282 this.reduce = this.quantizeReduce(this.reduce, this.reductionFactors);
1283 this.prepareThumbnailView();
1285 // $$$ why don't we save autofit?
1286 this.twoPage.autofit = null; // Take zoom level from other mode
1287 this.twoPageCalculateReductionFactors();
1288 this.reduce = this.quantizeReduce(this.reduce, this.twoPage.reductionFactors);
1289 this.prepareTwoPageView();
1290 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1295 //prepareOnePageView()
1296 //______________________________________________________________________________
1297 BookReader.prototype.prepareOnePageView = function() {
1299 // var startLeaf = this.displayedIndices[0];
1300 var startLeaf = this.currentIndex();
1302 $('#BRcontainer').empty();
1303 $('#BRcontainer').css({
1304 overflowY: 'scroll',
1308 $("#BRcontainer").append("<div id='BRpageview'></div>");
1310 // Attaches to first child - child must be present
1311 $('#BRcontainer').dragscrollable();
1312 this.bindGestures($('#BRcontainer'));
1314 // $$$ keep select enabled for now since disabling it breaks keyboard
1315 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1316 // BookReader.util.disableSelect($('#BRpageview'));
1318 this.resizePageView();
1320 this.jumpToIndex(startLeaf);
1321 this.displayedIndices = [];
1323 this.drawLeafsOnePage();
1326 //prepareThumbnailView()
1327 //______________________________________________________________________________
1328 BookReader.prototype.prepareThumbnailView = function() {
1330 $('#BRcontainer').empty();
1331 $('#BRcontainer').css({
1332 overflowY: 'scroll',
1336 $("#BRcontainer").append("<div id='BRpageview'></div>");
1338 $('#BRcontainer').dragscrollable();
1339 this.bindGestures($('#BRcontainer'));
1341 // $$$ keep select enabled for now since disabling it breaks keyboard
1342 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1343 // BookReader.util.disableSelect($('#BRpageview'));
1345 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1346 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1348 this.displayedRows = [];
1350 // Draw leafs with current index directly in view (no animating to the index)
1351 this.drawLeafsThumbnail( this.currentIndex() );
1355 // prepareTwoPageView()
1356 //______________________________________________________________________________
1357 // Some decisions about two page view:
1359 // Both pages will be displayed at the same height, even if they were different physical/scanned
1360 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1361 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1362 // aspect ratio to determine the height.
1364 // The two page view div is resized to keep the middle of the book in the middle of the div
1365 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1366 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1367 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1368 $('#BRcontainer').empty();
1369 $('#BRcontainer').css('overflow', 'auto');
1371 // We want to display two facing pages. We may be missing
1372 // one side of the spread because it is the first/last leaf,
1373 // foldouts, missing pages, etc
1375 //var targetLeaf = this.displayedIndices[0];
1376 var targetLeaf = this.firstIndex;
1378 if (targetLeaf < this.firstDisplayableIndex()) {
1379 targetLeaf = this.firstDisplayableIndex();
1382 if (targetLeaf > this.lastDisplayableIndex()) {
1383 targetLeaf = this.lastDisplayableIndex();
1386 //this.twoPage.currentIndexL = null;
1387 //this.twoPage.currentIndexR = null;
1388 //this.pruneUnusedImgs();
1390 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1391 this.twoPage.currentIndexL = currentSpreadIndices[0];
1392 this.twoPage.currentIndexR = currentSpreadIndices[1];
1393 this.firstIndex = this.twoPage.currentIndexL;
1395 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1397 this.pruneUnusedImgs();
1398 this.prefetch(); // Preload images or reload if scaling has changed
1400 //console.dir(this.twoPage);
1402 // Add the two page view
1403 // $$$ Can we get everything set up and then append?
1404 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1406 // Attaches to first child, so must come after we add the page view
1407 $('#BRcontainer').dragscrollable();
1408 this.bindGestures($('#BRcontainer'));
1410 // $$$ calculate first then set
1411 $('#BRtwopageview').css( {
1412 height: this.twoPage.totalHeight + 'px',
1413 width: this.twoPage.totalWidth + 'px',
1414 position: 'absolute'
1417 // If there will not be scrollbars (e.g. when zooming out) we center the book
1418 // since otherwise the book will be stuck off-center
1419 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1420 centerPercentageX = 0.5;
1422 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1423 centerPercentageY = 0.5;
1426 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1428 this.twoPage.coverDiv = document.createElement('div');
1429 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1430 width: this.twoPage.bookCoverDivWidth + 'px',
1431 height: this.twoPage.bookCoverDivHeight+'px',
1432 visibility: 'visible',
1433 position: 'absolute',
1434 left: this.twoPage.bookCoverDivLeft + 'px',
1435 top: this.twoPage.bookCoverDivTop+'px'
1436 }).appendTo('#BRtwopageview');
1438 this.leafEdgeR = document.createElement('div');
1439 this.leafEdgeR.className = 'BRleafEdgeR';
1440 $(this.leafEdgeR).css({
1441 width: this.twoPage.leafEdgeWidthR + 'px',
1442 height: this.twoPage.height-1 + 'px',
1443 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1444 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px'
1445 }).appendTo('#BRtwopageview');
1447 this.leafEdgeL = document.createElement('div');
1448 this.leafEdgeL.className = 'BRleafEdgeL';
1449 $(this.leafEdgeL).css({
1450 width: this.twoPage.leafEdgeWidthL + 'px',
1451 height: this.twoPage.height-1 + 'px',
1452 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1453 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px'
1454 }).appendTo('#BRtwopageview');
1456 div = document.createElement('div');
1457 $(div).attr('id', 'BRbookspine').css({
1458 width: this.twoPage.bookSpineDivWidth+'px',
1459 height: this.twoPage.bookSpineDivHeight+'px',
1460 left: this.twoPage.bookSpineDivLeft+'px',
1461 top: this.twoPage.bookSpineDivTop+'px'
1462 }).appendTo('#BRtwopageview');
1464 var self = this; // for closure
1466 /* Flip areas no longer used
1467 this.twoPage.leftFlipArea = document.createElement('div');
1468 this.twoPage.leftFlipArea.className = 'BRfliparea';
1469 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1471 width: this.twoPageFlipAreaWidth() + 'px',
1472 height: this.twoPageFlipAreaHeight() + 'px',
1473 position: 'absolute',
1474 left: this.twoPageLeftFlipAreaLeft() + 'px',
1475 top: this.twoPageFlipAreaTop() + 'px',
1478 }).bind('click', function(e) {
1480 }).bind('mousedown', function(e) {
1482 }).appendTo('#BRtwopageview');
1484 this.twoPage.rightFlipArea = document.createElement('div');
1485 this.twoPage.rightFlipArea.className = 'BRfliparea';
1486 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1488 width: this.twoPageFlipAreaWidth() + 'px',
1489 height: this.twoPageFlipAreaHeight() + 'px',
1490 position: 'absolute',
1491 left: this.twoPageRightFlipAreaLeft() + 'px',
1492 top: this.twoPageFlipAreaTop() + 'px',
1495 }).bind('click', function(e) {
1497 }).bind('mousedown', function(e) {
1499 }).appendTo('#BRtwopageview');
1502 this.prepareTwoPagePopUp();
1504 this.displayedIndices = [];
1506 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1507 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1509 this.drawLeafsTwoPage();
1510 this.updateToolbarZoom(this.reduce);
1514 this.removeSearchHilites();
1515 this.updateSearchHilites();
1519 // prepareTwoPagePopUp()
1521 // This function prepares the "View Page n" popup that shows while the mouse is
1522 // over the left/right "stack of sheets" edges. It also binds the mouse
1523 // events for these divs.
1524 //______________________________________________________________________________
1525 BookReader.prototype.prepareTwoPagePopUp = function() {
1527 this.twoPagePopUp = document.createElement('div');
1528 this.twoPagePopUp.className = 'BRtwoPagePopUp';
1529 $(this.twoPagePopUp).css({
1531 }).appendTo('#BRcontainer');
1532 $(this.twoPagePopUp).hide();
1534 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1535 $(e.data.twoPagePopUp).show();
1538 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1539 $(e.data.twoPagePopUp).hide();
1542 $(this.leafEdgeL).bind('click', this, function(e) {
1544 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1545 e.data.jumpToIndex(jumpIndex);
1548 $(this.leafEdgeR).bind('click', this, function(e) {
1550 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1551 e.data.jumpToIndex(jumpIndex);
1554 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1556 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1557 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1559 // $$$ TODO: Make sure popup is positioned so that it is in view
1560 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1561 $(e.data.twoPagePopUp).css({
1562 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1563 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1567 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1569 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1570 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1572 // $$$ TODO: Make sure popup is positioned so that it is in view
1573 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1574 $(e.data.twoPagePopUp).css({
1575 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1576 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1581 // calculateSpreadSize()
1582 //______________________________________________________________________________
1583 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1584 // this.twoPage.currentIndexR
1585 // This function sets this.twoPage.height, twoPage.width
1587 BookReader.prototype.calculateSpreadSize = function() {
1589 var firstIndex = this.twoPage.currentIndexL;
1590 var secondIndex = this.twoPage.currentIndexR;
1591 //console.log('first page is ' + firstIndex);
1593 // Calculate page sizes and total leaf width
1595 if ( this.twoPage.autofit) {
1596 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1598 // set based on reduction factor
1599 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1602 // Both pages together
1603 this.twoPage.height = spreadSize.height;
1604 this.twoPage.width = spreadSize.width;
1607 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1608 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1611 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1612 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1613 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1617 // The width of the book cover div. The combined width of both pages, twice the width
1618 // of the book cover internal padding (2*10) and the page edges
1619 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1620 // The height of the book cover div
1621 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1624 // We calculate the total width and height for the div so that we can make the book
1626 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1627 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1628 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1629 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1630 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1631 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1633 // We want to minimize the unused space in two-up mode (maximize the amount of page
1634 // shown). We give width to the leaf edges and these widths change (though the sum
1635 // of the two remains constant) as we flip through the book. With the book
1636 // cover centered and fixed in the BRcontainer div the page images will meet
1637 // at the "gutter" which is generally offset from the center.
1638 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1639 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1641 // The left edge of the book cover moves depending on the width of the pages
1642 // $$$ change to getter
1643 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1644 // The top edge of the book cover stays a fixed distance from the top
1645 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1648 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1649 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1650 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1653 this.reduce = spreadSize.reduce; // $$$ really set this here?
1656 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1659 // We check which page is closest to a "normal" page and use that to set the height
1660 // for both pages. This means that foldouts and other odd size pages will be displayed
1661 // smaller than the nominal zoom amount.
1662 var canon5Dratio = 1.5;
1665 height: this._getPageHeight(firstIndex),
1666 width: this._getPageWidth(firstIndex)
1670 height: this._getPageHeight(secondIndex),
1671 width: this._getPageWidth(secondIndex)
1674 var firstIndexRatio = first.height / first.width;
1675 var secondIndexRatio = second.height / second.width;
1676 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1679 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1680 ratio = firstIndexRatio;
1681 //console.log('using firstIndexRatio ' + ratio);
1683 ratio = secondIndexRatio;
1684 //console.log('using secondIndexRatio ' + ratio);
1687 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1688 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1689 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1691 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1692 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1694 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1695 ideal.width -= 10; // $$$ fudge factor
1696 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1697 ideal.height -= 20; // fudge factor
1698 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1700 if (ideal.height/ratio <= ideal.width) {
1702 ideal.width = parseInt(ideal.height/ratio);
1705 ideal.height = parseInt(ideal.width*ratio);
1708 // $$$ check this logic with large spreads
1709 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1714 // getSpreadSizeFromReduce()
1715 //______________________________________________________________________________
1716 // Returns the spread size calculated from the reduction factor for the given pages
1717 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1718 var spreadSize = {};
1719 // $$$ Scale this based on reduce?
1720 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1721 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1722 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1724 // $$$ Possibly incorrect -- we should make height "dominant"
1725 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1726 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1727 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1728 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1729 spreadSize.reduce = reduce;
1734 // twoPageGetAutofitReduce()
1735 //______________________________________________________________________________
1736 // Returns the current ideal reduction factor
1737 BookReader.prototype.twoPageGetAutofitReduce = function() {
1738 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1739 return spreadSize.reduce;
1742 BookReader.prototype.onePageGetAutofitWidth = function() {
1743 var widthPadding = 20;
1744 return (this.getMedianPageSize().width + 0.0) / ($('#BRcontainer').attr('clientWidth') - widthPadding * 2);
1747 BookReader.prototype.onePageGetAutofitHeight = function() {
1748 return (this.getMedianPageSize().height + 0.0) / ($('#BRcontainer').attr('clientHeight') - this.padding * 2); // make sure a little of adjacent pages show
1751 BookReader.prototype.getMedianPageSize = function() {
1752 if (this._medianPageSize) {
1753 return this._medianPageSize;
1756 // A little expensive but we just do it once
1759 for (var i = 0; i < this.numLeafs; i++) {
1760 widths.push(this.getPageWidth(i));
1761 heights.push(this.getPageHeight(i));
1767 this._medianPageSize = { width: widths[parseInt(widths.length / 2)], height: heights[parseInt(heights.length / 2)] };
1768 return this._medianPageSize;
1771 // Update the reduction factors for 1up mode given the available width and height. Recalculates
1772 // the autofit reduction factors.
1773 BookReader.prototype.onePageCalculateReductionFactors = function( width, height ) {
1774 this.onePage.reductionFactors = this.reductionFactors.concat(
1776 { reduce: this.onePageGetAutofitWidth(), autofit: 'width' },
1777 { reduce: this.onePageGetAutofitHeight(), autofit: 'height'}
1779 this.onePage.reductionFactors.sort(this._reduceSort);
1782 BookReader.prototype.twoPageCalculateReductionFactors = function() {
1783 this.twoPage.reductionFactors = this.reductionFactors.concat(
1785 { reduce: this.getIdealSpreadSize( this.twoPage.currentIndexL, this.twoPage.currentIndexR ).reduce,
1788 this.twoPage.reductionFactors.sort(this._reduceSort);
1791 // twoPageSetCursor()
1792 //______________________________________________________________________________
1793 // Set the cursor for two page view
1794 BookReader.prototype.twoPageSetCursor = function() {
1795 // console.log('setting cursor');
1796 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1797 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1798 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1799 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1801 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1802 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1807 //______________________________________________________________________________
1808 // Returns the currently active index.
1809 BookReader.prototype.currentIndex = function() {
1810 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1811 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1812 return this.firstIndex; // $$$ TODO page in center of view would be better
1813 } else if (this.mode == this.constMode2up) {
1814 // Only allow indices that are actually present in book
1815 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1817 throw 'currentIndex called for unimplemented mode ' + this.mode;
1821 // setCurrentIndex(index)
1822 //______________________________________________________________________________
1823 // Sets the idea of current index without triggering other actions such as animation.
1824 // Compare to jumpToIndex which animates to that index
1825 BookReader.prototype.setCurrentIndex = function(index) {
1826 this.firstIndex = index;
1831 //______________________________________________________________________________
1832 // Flip the right page over onto the left
1833 BookReader.prototype.right = function() {
1834 if ('rl' != this.pageProgression) {
1844 //______________________________________________________________________________
1845 // Flip to the rightmost page
1846 BookReader.prototype.rightmost = function() {
1847 if ('rl' != this.pageProgression) {
1855 //______________________________________________________________________________
1856 // Flip the left page over onto the right.
1857 BookReader.prototype.left = function() {
1858 if ('rl' != this.pageProgression) {
1868 //______________________________________________________________________________
1869 // Flip to the leftmost page
1870 BookReader.prototype.leftmost = function() {
1871 if ('rl' != this.pageProgression) {
1879 //______________________________________________________________________________
1880 BookReader.prototype.next = function() {
1881 if (2 == this.mode) {
1883 this.flipFwdToIndex(null);
1885 if (this.firstIndex < this.lastDisplayableIndex()) {
1886 this.jumpToIndex(this.firstIndex+1);
1892 //______________________________________________________________________________
1893 BookReader.prototype.prev = function() {
1894 if (2 == this.mode) {
1896 this.flipBackToIndex(null);
1898 if (this.firstIndex >= 1) {
1899 this.jumpToIndex(this.firstIndex-1);
1904 BookReader.prototype.first = function() {
1905 this.jumpToIndex(this.firstDisplayableIndex());
1908 BookReader.prototype.last = function() {
1909 this.jumpToIndex(this.lastDisplayableIndex());
1913 //______________________________________________________________________________
1914 // Scrolls down one screen view
1915 BookReader.prototype.scrollDown = function() {
1916 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1917 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1918 // Whole pages are visible, scroll whole page only
1922 $('#BRcontainer').animate(
1923 { scrollTop: '+=' + this._scrollAmount() + 'px'},
1924 400, 'easeInOutExpo'
1933 //______________________________________________________________________________
1934 // Scrolls up one screen view
1935 BookReader.prototype.scrollUp = function() {
1936 if ($.inArray(this.mode, [this.constMode1up, this.constModeThumb]) >= 0) {
1937 if ( this.mode == this.constMode1up && (this.reduce >= this.onePageGetAutofitHeight()) ) {
1938 // Whole pages are visible, scroll whole page only
1942 $('#BRcontainer').animate(
1943 { scrollTop: '-=' + this._scrollAmount() + 'px'},
1944 400, 'easeInOutExpo'
1953 //______________________________________________________________________________
1954 // The amount to scroll vertically in integer pixels
1955 BookReader.prototype._scrollAmount = function() {
1956 if (this.constMode1up == this.mode) {
1957 // Overlap by % of page size
1958 return parseInt($('#BRcontainer').attr('clientHeight') - this.getPageHeight(this.currentIndex()) / this.reduce * 0.03);
1961 return parseInt(0.9 * $('#BRcontainer').attr('clientHeight'));
1965 // flipBackToIndex()
1966 //______________________________________________________________________________
1967 // to flip back one spread, pass index=null
1968 BookReader.prototype.flipBackToIndex = function(index) {
1970 if (1 == this.mode) return;
1972 var leftIndex = this.twoPage.currentIndexL;
1974 if (this.animating) return;
1976 if (null != this.leafEdgeTmp) {
1977 alert('error: leafEdgeTmp should be null!');
1981 if (null == index) {
1982 index = leftIndex-2;
1984 //if (index<0) return;
1986 var previousIndices = this.getSpreadIndices(index);
1988 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1992 this.animating = true;
1994 if ('rl' != this.pageProgression) {
1995 // Assume LTR and we are going backward
1996 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1997 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1999 // RTL and going backward
2000 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2001 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2005 // flipLeftToRight()
2006 //______________________________________________________________________________
2007 // Flips the page on the left towards the page on the right
2008 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2010 var leftLeaf = this.twoPage.currentIndexL;
2012 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2013 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2014 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2016 var currWidthL = this.getPageWidth2UP(leftLeaf);
2017 var newWidthL = this.getPageWidth2UP(newIndexL);
2018 var newWidthR = this.getPageWidth2UP(newIndexR);
2020 var top = this.twoPageTop();
2021 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2023 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2024 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2026 //animation strategy:
2027 // 0. remove search highlight, if any.
2028 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2029 // of the left leaf and where the user clicked in the leaf edge.
2030 // Note that if this function was triggered by left() and not a
2031 // mouse click, the width of leafEdgeTmp is very small (zero px).
2032 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2033 // leftLeaf to width=0.
2034 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2035 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2036 // its new full width.
2037 // 4. After step 3 is finished, do the following:
2038 // - remove leafEdgeTmp from the dom.
2039 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2040 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2041 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2042 // and width=newLeafEdgeWidthL.
2043 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2044 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2045 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2046 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2047 // - prefetch new adjacent leafs.
2048 // - set up click handlers for both new left and right leafs.
2049 // - redraw the search highlight.
2050 // - update the pagenum box and the url.
2053 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2055 this.leafEdgeTmp = document.createElement('div');
2056 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2057 $(this.leafEdgeTmp).css({
2058 width: leafEdgeTmpW + 'px',
2059 height: this.twoPage.height-1 + 'px',
2060 left: leftEdgeTmpLeft + 'px',
2063 }).appendTo('#BRtwopageview');
2065 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2066 $(this.leafEdgeL).css({
2067 width: newLeafEdgeWidthL+'px',
2068 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2071 // Left gets the offset of the current left leaf from the document
2072 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2073 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2074 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2076 // We change the left leaf to right positioning
2077 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2078 $(this.prefetchedImgs[leftLeaf]).css({
2083 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2084 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2088 this.removeSearchHilites();
2090 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2091 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2093 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2094 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2096 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2097 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2098 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2100 $(self.leafEdgeR).css({
2101 // Moves the right leaf edge
2102 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2103 left: gutter+newWidthR+'px'
2106 $(self.leafEdgeL).css({
2107 // Moves and resizes the left leaf edge
2108 width: newLeafEdgeWidthL+'px',
2109 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2112 // Resizes the brown border div
2113 $(self.twoPage.coverDiv).css({
2114 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2115 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2118 $(self.leafEdgeTmp).remove();
2119 self.leafEdgeTmp = null;
2121 // $$$ TODO refactor with opposite direction flip
2123 self.twoPage.currentIndexL = newIndexL;
2124 self.twoPage.currentIndexR = newIndexR;
2125 self.twoPage.scaledWL = newWidthL;
2126 self.twoPage.scaledWR = newWidthR;
2127 self.twoPage.gutter = gutter;
2129 self.firstIndex = self.twoPage.currentIndexL;
2130 self.displayedIndices = [newIndexL, newIndexR];
2131 self.pruneUnusedImgs();
2133 self.animating = false;
2135 self.updateSearchHilites2UP();
2136 self.updatePageNumBox2UP();
2138 // self.twoPagePlaceFlipAreas(); // No longer used
2139 self.setMouseHandlers2UP();
2140 self.twoPageSetCursor();
2142 if (self.animationFinishedCallback) {
2143 self.animationFinishedCallback();
2144 self.animationFinishedCallback = null;
2152 //______________________________________________________________________________
2153 // Whether we flip left or right is dependent on the page progression
2154 // to flip forward one spread, pass index=null
2155 BookReader.prototype.flipFwdToIndex = function(index) {
2157 if (this.animating) return;
2159 if (null != this.leafEdgeTmp) {
2160 alert('error: leafEdgeTmp should be null!');
2164 if (null == index) {
2165 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2167 if (index > this.lastDisplayableIndex()) return;
2169 this.animating = true;
2171 var nextIndices = this.getSpreadIndices(index);
2173 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2175 if ('rl' != this.pageProgression) {
2176 // We did not specify RTL
2177 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2178 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2181 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2182 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2186 // flipRightToLeft(nextL, nextR, gutter)
2187 // $$$ better not to have to pass gutter in
2188 //______________________________________________________________________________
2189 // Flip from left to right and show the nextL and nextR indices on those sides
2190 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2191 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2192 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2193 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2194 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2196 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2198 var top = this.twoPageTop();
2199 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2201 var middle = this.twoPage.middle;
2202 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2204 this.leafEdgeTmp = document.createElement('div');
2205 this.leafEdgeTmp.className = 'BRleafEdgeTmp';
2206 $(this.leafEdgeTmp).css({
2207 width: leafEdgeTmpW + 'px',
2208 height: this.twoPage.height-1 + 'px',
2209 left: gutter+scaledW+'px',
2212 }).appendTo('#BRtwopageview');
2214 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2215 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2217 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2218 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2219 var newWidthL = this.getPageWidth2UP(newIndexL);
2220 var newWidthR = this.getPageWidth2UP(newIndexR);
2222 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2224 var self = this; // closure-tastic!
2226 var speed = this.flipSpeed;
2228 this.removeSearchHilites();
2230 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2231 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2232 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2233 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2234 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2236 $(self.leafEdgeL).css({
2237 width: newLeafEdgeWidthL+'px',
2238 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2241 // Resizes the book cover
2242 $(self.twoPage.coverDiv).css({
2243 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2244 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2247 $(self.leafEdgeTmp).remove();
2248 self.leafEdgeTmp = null;
2250 self.twoPage.currentIndexL = newIndexL;
2251 self.twoPage.currentIndexR = newIndexR;
2252 self.twoPage.scaledWL = newWidthL;
2253 self.twoPage.scaledWR = newWidthR;
2254 self.twoPage.gutter = gutter;
2256 self.firstIndex = self.twoPage.currentIndexL;
2257 self.displayedIndices = [newIndexL, newIndexR];
2258 self.pruneUnusedImgs();
2260 self.animating = false;
2263 self.updateSearchHilites2UP();
2264 self.updatePageNumBox2UP();
2266 // self.twoPagePlaceFlipAreas(); // No longer used
2267 self.setMouseHandlers2UP();
2268 self.twoPageSetCursor();
2270 if (self.animationFinishedCallback) {
2271 self.animationFinishedCallback();
2272 self.animationFinishedCallback = null;
2278 // setMouseHandlers2UP
2279 //______________________________________________________________________________
2280 BookReader.prototype.setMouseHandlers2UP = function() {
2281 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2289 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2292 e.data.self.right();
2299 //______________________________________________________________________________
2300 BookReader.prototype.prefetchImg = function(index) {
2301 var pageURI = this._getPageURI(index);
2303 // Load image if not loaded or URI has changed (e.g. due to scaling)
2304 var loadImage = false;
2305 if (undefined == this.prefetchedImgs[index]) {
2306 //console.log('no image for ' + index);
2308 } else if (pageURI != this.prefetchedImgs[index].uri) {
2309 //console.log('uri changed for ' + index);
2314 //console.log('prefetching ' + index);
2315 var img = document.createElement("img");
2316 img.className = 'BRpageimage';
2317 if (index < 0 || index > (this.numLeafs - 1) ) {
2318 // Facing page at beginning or end, or beyond
2320 'background-color': 'transparent'
2324 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2325 this.prefetchedImgs[index] = img;
2330 // prepareFlipLeftToRight()
2332 //______________________________________________________________________________
2334 // Prepare to flip the left page towards the right. This corresponds to moving
2335 // backward when the page progression is left to right.
2336 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2338 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2340 this.prefetchImg(prevL);
2341 this.prefetchImg(prevR);
2343 var height = this._getPageHeight(prevL);
2344 var width = this._getPageWidth(prevL);
2345 var middle = this.twoPage.middle;
2346 var top = this.twoPageTop();
2347 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2349 // The gutter is the dividing line between the left and right pages.
2350 // It is offset from the middle to create the illusion of thickness to the pages
2351 var gutter = middle + this.gutterOffsetForIndex(prevL);
2353 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2354 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2355 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2358 position: 'absolute',
2359 left: gutter-scaledW+'px',
2360 right: '', // clear right property
2362 height: this.twoPage.height,
2363 width: scaledW+'px',
2364 borderRight: '1px solid black',
2368 $(this.prefetchedImgs[prevL]).css(leftCSS);
2370 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2372 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2375 position: 'absolute',
2379 height: this.twoPage.height,
2381 borderLeft: '1px solid black',
2385 $(this.prefetchedImgs[prevR]).css(rightCSS);
2387 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2391 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2392 // prepareFlipRightToLeft()
2393 //______________________________________________________________________________
2394 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2396 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2399 this.prefetchImg(nextL);
2400 this.prefetchImg(nextR);
2402 var height = this._getPageHeight(nextR);
2403 var width = this._getPageWidth(nextR);
2404 var middle = this.twoPage.middle;
2405 var top = this.twoPageTop();
2406 var scaledW = this.twoPage.height*width/height;
2408 var gutter = middle + this.gutterOffsetForIndex(nextL);
2410 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2411 $(this.prefetchedImgs[nextR]).css({
2412 position: 'absolute',
2415 height: this.twoPage.height,
2416 width: scaledW+'px',
2417 borderLeft: '1px solid black',
2421 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2423 height = this._getPageHeight(nextL);
2424 width = this._getPageWidth(nextL);
2425 scaledW = this.twoPage.height*width/height;
2427 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2428 $(this.prefetchedImgs[nextL]).css({
2429 position: 'absolute',
2430 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2432 height: this.twoPage.height,
2433 width: 0+'px', // Start at 0 width, then grow to the left
2434 borderRight: '1px solid black',
2438 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2442 // getNextLeafs() -- NOT RTL AWARE
2443 //______________________________________________________________________________
2444 // BookReader.prototype.getNextLeafs = function(o) {
2445 // //TODO: we might have two left or two right leafs in a row (damaged book)
2446 // //For now, assume that leafs are contiguous.
2448 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2449 // o.L = this.twoPage.currentIndexL+2;
2450 // o.R = this.twoPage.currentIndexL+3;
2453 // getprevLeafs() -- NOT RTL AWARE
2454 //______________________________________________________________________________
2455 // BookReader.prototype.getPrevLeafs = function(o) {
2456 // //TODO: we might have two left or two right leafs in a row (damaged book)
2457 // //For now, assume that leafs are contiguous.
2459 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2460 // o.L = this.twoPage.currentIndexL-2;
2461 // o.R = this.twoPage.currentIndexL-1;
2464 // pruneUnusedImgs()
2465 //______________________________________________________________________________
2466 BookReader.prototype.pruneUnusedImgs = function() {
2467 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2468 for (var key in this.prefetchedImgs) {
2469 //console.log('key is ' + key);
2470 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2471 //console.log('removing key '+ key);
2472 $(this.prefetchedImgs[key]).remove();
2474 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2475 //console.log('deleting key '+ key);
2476 delete this.prefetchedImgs[key];
2482 //______________________________________________________________________________
2483 BookReader.prototype.prefetch = function() {
2485 // $$$ We should check here if the current indices have finished
2486 // loading (with some timeout) before loading more page images
2487 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2489 // prefetch visible pages first
2490 this.prefetchImg(this.twoPage.currentIndexL);
2491 this.prefetchImg(this.twoPage.currentIndexR);
2493 var adjacentPagesToLoad = 3;
2495 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2496 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2498 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2499 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2501 // Load images spreading out from current
2502 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2503 var goingDown = lowCurrent - i;
2504 if (goingDown >= start) {
2505 this.prefetchImg(goingDown);
2507 var goingUp = highCurrent + i;
2508 if (goingUp <= end) {
2509 this.prefetchImg(goingUp);
2514 var lim = this.twoPage.currentIndexL-4;
2516 lim = Math.max(lim, 0);
2517 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2518 this.prefetchImg(i);
2521 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2522 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2523 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2524 this.prefetchImg(i);
2530 // getPageWidth2UP()
2531 //______________________________________________________________________________
2532 BookReader.prototype.getPageWidth2UP = function(index) {
2533 // We return the width based on the dominant height
2534 var height = this._getPageHeight(index);
2535 var width = this._getPageWidth(index);
2536 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2540 //______________________________________________________________________________
2541 BookReader.prototype.search = function(term) {
2542 term = term.replace(/\//g, ' '); // strip slashes
2543 this.searchTerm = term;
2544 $('#BookReaderSearchScript').remove();
2545 var script = document.createElement("script");
2546 script.setAttribute('id', 'BookReaderSearchScript');
2547 script.setAttribute("type", "text/javascript");
2548 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2549 document.getElementsByTagName('head')[0].appendChild(script);
2550 $('#BookReaderSearchBox').val(term);
2551 $('#BookReaderSearchResults').html('Searching...');
2554 // BRSearchCallback()
2555 //______________________________________________________________________________
2556 BookReader.prototype.BRSearchCallback = function(txt) {
2558 if (jQuery.browser.msie) {
2559 var dom=new ActiveXObject("Microsoft.XMLDOM");
2563 var parser = new DOMParser();
2564 var dom = parser.parseFromString(txt, "text/xml");
2567 $('#BookReaderSearchResults').empty();
2568 $('#BookReaderSearchResults').append('<ul>');
2570 for (var key in this.searchResults) {
2571 if (null != this.searchResults[key].div) {
2572 $(this.searchResults[key].div).remove();
2574 delete this.searchResults[key];
2577 var pages = dom.getElementsByTagName('PAGE');
2579 if (0 == pages.length) {
2580 // $$$ it would be nice to echo the (sanitized) search result here
2581 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2583 for (var i = 0; i < pages.length; i++){
2584 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2587 var re = new RegExp (/_(\d{4})\.djvu/);
2588 var reMatch = re.exec(pages[i].getAttribute('file'));
2589 var index = parseInt(reMatch[1], 10);
2590 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2592 var children = pages[i].childNodes;
2594 for (var j=0; j<children.length; j++) {
2595 //console.log(j + ' - ' + children[j].nodeName);
2596 //console.log(children[j].firstChild.nodeValue);
2597 if ('CONTEXT' == children[j].nodeName) {
2598 context += children[j].firstChild.nodeValue;
2599 } else if ('WORD' == children[j].nodeName) {
2600 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2602 var index = this.leafNumToIndex(index);
2603 if (null != index) {
2604 //coordinates are [left, bottom, right, top, [baseline]]
2605 //we'll skip baseline for now...
2606 var coords = children[j].getAttribute('coords').split(',',4);
2607 if (4 == coords.length) {
2608 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2613 var pageName = this.getPageName(index);
2614 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2615 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2616 //TODO: remove hardcoded instance name
2617 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2620 $('#BookReaderSearchResults').append('</ul>');
2622 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2623 $('#BookReaderSearchBox').val(this.searchTerm);
2625 this.updateSearchHilites();
2628 // updateSearchHilites()
2629 //______________________________________________________________________________
2630 BookReader.prototype.updateSearchHilites = function() {
2631 if (2 == this.mode) {
2632 this.updateSearchHilites2UP();
2634 this.updateSearchHilites1UP();
2638 // showSearchHilites1UP()
2639 //______________________________________________________________________________
2640 BookReader.prototype.updateSearchHilites1UP = function() {
2642 for (var key in this.searchResults) {
2644 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2645 var result = this.searchResults[key];
2646 if (null == result.div) {
2647 result.div = document.createElement('div');
2648 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2649 //console.log('appending ' + key);
2652 width: (result.r-result.l)/this.reduce + 'px',
2653 height: (result.b-result.t)/this.reduce + 'px',
2654 left: (result.l)/this.reduce + 'px',
2655 top: (result.t)/this.reduce +'px'
2659 //console.log(key + ' not displayed');
2660 this.searchResults[key].div=null;
2666 //______________________________________________________________________________
2667 // Returns the position of the gutter (line between the page images)
2668 BookReader.prototype.twoPageGutter = function() {
2669 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2673 //______________________________________________________________________________
2674 // Returns the offset for the top of the page images
2675 BookReader.prototype.twoPageTop = function() {
2676 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2679 // twoPageCoverWidth()
2680 //______________________________________________________________________________
2681 // Returns the width of the cover div given the total page width
2682 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2683 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2686 // twoPageGetViewCenter()
2687 //______________________________________________________________________________
2688 // Returns the percentage offset into twopageview div at the center of container div
2689 // { percentageX: float, percentageY: float }
2690 BookReader.prototype.twoPageGetViewCenter = function() {
2693 var containerOffset = $('#BRcontainer').offset();
2694 var viewOffset = $('#BRtwopageview').offset();
2695 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2696 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2701 // twoPageCenterView(percentageX, percentageY)
2702 //______________________________________________________________________________
2703 // Centers the point given by percentage from left,top of twopageview
2704 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2705 if ('undefined' == typeof(percentageX)) {
2708 if ('undefined' == typeof(percentageY)) {
2712 var viewWidth = $('#BRtwopageview').width();
2713 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2714 var intoViewX = percentageX * viewWidth;
2716 var viewHeight = $('#BRtwopageview').height();
2717 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2718 var intoViewY = percentageY * viewHeight;
2720 if (viewWidth < containerClientWidth) {
2721 // Can fit width without scrollbars - center by adjusting offset
2722 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2724 // Need to scroll to center
2725 $('#BRtwopageview').css('left', 0);
2726 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2729 if (viewHeight < containerClientHeight) {
2730 // Fits with scrollbars - add offset
2731 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2733 $('#BRtwopageview').css('top', 0);
2734 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2738 // twoPageFlipAreaHeight
2739 //______________________________________________________________________________
2740 // Returns the integer height of the click-to-flip areas at the edges of the book
2741 BookReader.prototype.twoPageFlipAreaHeight = function() {
2742 return parseInt(this.twoPage.height);
2745 // twoPageFlipAreaWidth
2746 //______________________________________________________________________________
2747 // Returns the integer width of the flip areas
2748 BookReader.prototype.twoPageFlipAreaWidth = function() {
2749 var max = 100; // $$$ TODO base on view width?
2752 var width = this.twoPage.width * 0.15;
2753 return parseInt(BookReader.util.clamp(width, min, max));
2756 // twoPageFlipAreaTop
2757 //______________________________________________________________________________
2758 // Returns integer top offset for flip areas
2759 BookReader.prototype.twoPageFlipAreaTop = function() {
2760 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2763 // twoPageLeftFlipAreaLeft
2764 //______________________________________________________________________________
2765 // Left offset for left flip area
2766 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2767 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2770 // twoPageRightFlipAreaLeft
2771 //______________________________________________________________________________
2772 // Left offset for right flip area
2773 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2774 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2777 // twoPagePlaceFlipAreas
2778 //______________________________________________________________________________
2779 // Readjusts position of flip areas based on current layout
2780 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2781 // We don't set top since it shouldn't change relative to view
2782 $(this.twoPage.leftFlipArea).css({
2783 left: this.twoPageLeftFlipAreaLeft() + 'px',
2784 width: this.twoPageFlipAreaWidth() + 'px'
2786 $(this.twoPage.rightFlipArea).css({
2787 left: this.twoPageRightFlipAreaLeft() + 'px',
2788 width: this.twoPageFlipAreaWidth() + 'px'
2792 // showSearchHilites2UP()
2793 //______________________________________________________________________________
2794 BookReader.prototype.updateSearchHilites2UP = function() {
2796 for (var key in this.searchResults) {
2797 key = parseInt(key, 10);
2798 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2799 var result = this.searchResults[key];
2800 if (null == result.div) {
2801 result.div = document.createElement('div');
2802 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2803 //console.log('appending ' + key);
2806 this.setHilightCss2UP(result.div, key, result.l, result.r, result.t, result.b);
2809 //console.log(key + ' not displayed');
2810 if (null != this.searchResults[key].div) {
2811 //console.log('removing ' + key);
2812 $(this.searchResults[key].div).remove();
2814 this.searchResults[key].div=null;
2819 // setHilightCss2UP()
2820 //______________________________________________________________________________
2821 //position calculation shared between search and text-to-speech functions
2822 BookReader.prototype.setHilightCss2UP = function(div, index, left, right, top, bottom) {
2824 // We calculate the reduction factor for the specific page because it can be different
2825 // for each page in the spread
2826 var height = this._getPageHeight(index);
2827 var width = this._getPageWidth(index)
2828 var reduce = this.twoPage.height/height;
2829 var scaledW = parseInt(width*reduce);
2831 var gutter = this.twoPageGutter();
2833 if ('L' == this.getPageSide(index)) {
2834 pageL = gutter-scaledW;
2838 var pageT = this.twoPageTop();
2841 width: (right-left)*reduce + 'px',
2842 height: (bottom-top)*reduce + 'px',
2843 left: pageL+left*reduce + 'px',
2844 top: pageT+top*reduce +'px'
2848 // removeSearchHilites()
2849 //______________________________________________________________________________
2850 BookReader.prototype.removeSearchHilites = function() {
2851 for (var key in this.searchResults) {
2852 if (null != this.searchResults[key].div) {
2853 $(this.searchResults[key].div).remove();
2854 this.searchResults[key].div=null;
2860 //______________________________________________________________________________
2861 BookReader.prototype.printPage = function() {
2862 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2865 // Get print URI from current indices and mode
2866 BookReader.prototype.getPrintURI = function() {
2868 if (this.constMode2up == this.mode) {
2869 indexToPrint = this.twoPage.currentIndexL;
2871 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2874 var options = 'id=' + this.subPrefix + '&server=' + this.server + '&zip=' + this.zip
2875 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2876 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2878 if (this.constMode2up == this.mode) {
2879 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2880 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2881 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2883 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2886 return '/bookreader/print.php?' + options;
2889 /* iframe implementation
2890 BookReader.prototype.getPrintFrameContent = function(index) {
2891 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2892 // 8.5x11 so we should end up not overflowing on either paper size.
2893 var paperAspect = 8.5 / 11;
2894 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2898 // Rotate if possible and appropriate, to get larger image size on printed page
2899 if (this.canRotatePage(index)) {
2900 if (imageAspect > 1 && imageAspect > paperAspect) {
2901 // more wide than square, and more wide than paper
2903 imageAspect = 1/imageAspect;
2908 if (imageAspect > paperAspect) {
2909 // wider than paper, fit width
2910 fitAttrs = 'width="95%"';
2912 // taller than paper, fit height
2913 fitAttrs = 'height="95%"';
2916 var imageURL = this._getPageURI(index, 1, rotate);
2917 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2918 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2919 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2920 iframeStr += '</div>';
2921 iframeStr += '</body></html>';
2926 BookReader.prototype.updatePrintFrame = function(delta) {
2927 var newIndex = this.indexToPrint + delta;
2928 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2929 if (newIndex == this.indexToPrint) {
2932 this.indexToPrint = newIndex;
2933 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2934 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2939 //______________________________________________________________________________
2940 BookReader.prototype.showEmbedCode = function() {
2941 if (null != this.embedPopup) { // check if already showing
2945 this.embedPopup = document.createElement("div");
2946 $(this.embedPopup).css({
2947 position: 'absolute',
2949 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2952 border: "3px double #999999",
2954 backgroundColor: "#fff"
2955 }).appendTo('#BookReader');
2957 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2958 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>';
2959 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2960 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2962 this.embedPopup.innerHTML = htmlStr;
2963 $(this.embedPopup).find('input').bind('click', function() {
2969 //______________________________________________________________________________
2970 BookReader.prototype.autoToggle = function() {
2972 var bComingFrom1up = false;
2973 if (2 != this.mode) {
2974 bComingFrom1up = true;
2978 // Change to autofit if book is too large
2979 if (this.reduce < this.twoPageGetAutofitReduce()) {
2980 this.zoom2up('auto');
2984 if (null == this.autoTimer) {
2985 this.flipSpeed = 2000;
2987 // $$$ Draw events currently cause layout problems when they occur during animation.
2988 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2989 // we workaround for now by not triggering immediate animation in that case.
2990 // See https://bugs.launchpad.net/gnubook/+bug/328327
2991 if (('rl' == this.pageProgression) && bComingFrom1up) {
2992 // don't flip immediately -- wait until timer fires
2995 this.flipFwdToIndex();
2998 $('#BRtoolbar .play').hide();
2999 $('#BRtoolbar .pause').show();
3000 this.autoTimer=setInterval(function(){
3001 if (self.animating) {return;}
3003 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3004 self.flipBackToIndex(1); // $$$ really what we want?
3006 self.flipFwdToIndex();
3015 //______________________________________________________________________________
3016 // Stop autoplay mode, allowing animations to finish
3017 BookReader.prototype.autoStop = function() {
3018 if (null != this.autoTimer) {
3019 clearInterval(this.autoTimer);
3020 this.flipSpeed = 'fast';
3021 $('#BRtoolbar .pause').hide();
3022 $('#BRtoolbar .play').show();
3023 this.autoTimer = null;
3027 // stopFlipAnimations
3028 //______________________________________________________________________________
3029 // Immediately stop flip animations. Callbacks are triggered.
3030 BookReader.prototype.stopFlipAnimations = function() {
3032 this.autoStop(); // Clear timers
3034 // Stop animation, clear queue, trigger callbacks
3035 if (this.leafEdgeTmp) {
3036 $(this.leafEdgeTmp).stop(false, true);
3038 jQuery.each(this.prefetchedImgs, function() {
3039 $(this).stop(false, true);
3042 // And again since animations also queued in callbacks
3043 if (this.leafEdgeTmp) {
3044 $(this.leafEdgeTmp).stop(false, true);
3046 jQuery.each(this.prefetchedImgs, function() {
3047 $(this).stop(false, true);
3052 // keyboardNavigationIsDisabled(event)
3053 // - returns true if keyboard navigation should be disabled for the event
3054 //______________________________________________________________________________
3055 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3056 if (event.target.tagName == "INPUT") {
3062 // gutterOffsetForIndex
3063 //______________________________________________________________________________
3065 // Returns the gutter offset for the spread containing the given index.
3066 // This function supports RTL
3067 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3069 // To find the offset of the gutter from the middle we calculate our percentage distance
3070 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3071 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3073 // But then again for RTL it's the opposite
3074 if ('rl' == this.pageProgression) {
3082 //______________________________________________________________________________
3083 // Returns the width of the leaf edge div for the page with index given
3084 BookReader.prototype.leafEdgeWidth = function(pindex) {
3085 // $$$ could there be single pixel rounding errors for L vs R?
3086 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3087 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3089 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3093 // jumpIndexForLeftEdgePageX
3094 //______________________________________________________________________________
3095 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3096 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3097 if ('rl' != this.pageProgression) {
3098 // LTR - flipping backward
3099 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3101 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3102 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3106 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3107 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3112 // jumpIndexForRightEdgePageX
3113 //______________________________________________________________________________
3114 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3115 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3116 if ('rl' != this.pageProgression) {
3118 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3119 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3122 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3123 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3128 BookReader.prototype.initToolbar = function(mode, ui) {
3130 $("#BookReader").append("<div id='BRtoolbar'>"
3131 + "<span id='BRtoolbarbuttons' style='float: right'>"
3132 + "<button class='BRicon rollover read_aloud' onclick='br.ttsStart(); return false;'/>"
3133 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3134 + "<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>"
3135 + "<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>"
3136 + "<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>"
3137 + "<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>"
3138 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3142 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3143 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3144 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3145 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3146 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3147 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3148 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3151 + "<span id='#BRbooktitle'>"
3152 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3156 this.updateToolbarZoom(this.reduce); // Pretty format
3158 if (ui == "embed" || ui == "touch") {
3159 $("#BookReader a.logo").attr("target","_blank");
3162 // $$$ turn this into a member variable
3163 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3165 // We build in mode 2
3168 this.bindToolbarNavHandlers(jToolbar);
3170 // Setup tooltips -- later we could load these from a file for i18n
3171 var titles = { '.logo': 'Go to Archive.org',
3172 '.zoom_in': 'Zoom in',
3173 '.zoom_out': 'Zoom out',
3174 '.one_page_mode': 'One-page view',
3175 '.two_page_mode': 'Two-page view',
3176 '.thumbnail_mode': 'Thumbnail view',
3177 '.print': 'Print this page',
3178 '.embed': 'Embed bookreader',
3179 '.book_left': 'Flip left',
3180 '.book_right': 'Flip right',
3181 '.book_up': 'Page up',
3182 '.book_down': 'Page down',
3185 '.book_top': 'First page',
3186 '.book_bottom': 'Last page'
3188 if ('rl' == this.pageProgression) {
3189 titles['.book_leftmost'] = 'Last page';
3190 titles['.book_rightmost'] = 'First page';
3192 titles['.book_leftmost'] = 'First page';
3193 titles['.book_rightmost'] = 'Last page';
3196 for (var icon in titles) {
3197 jToolbar.find(icon).attr('title', titles[icon]);
3200 // Hide mode buttons and autoplay if 2up is not available
3201 // $$$ if we end up with more than two modes we should show the applicable buttons
3202 if ( !this.canSwitchToMode(this.constMode2up) ) {
3203 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3206 // Switch to requested mode -- binds other click handlers
3207 this.switchToolbarMode(mode);
3212 // switchToolbarMode
3213 //______________________________________________________________________________
3214 // Update the toolbar for the given mode (changes navigation buttons)
3215 // $$$ we should soon split the toolbar out into its own module
3216 BookReader.prototype.switchToolbarMode = function(mode) {
3219 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3220 $('#BRtoolbar .BRtoolbarmode2').hide();
3221 $('#BRtoolbar .BRtoolbarmode3').hide();
3222 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3223 } else if (2 == mode) {
3225 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3226 $('#BRtoolbar .BRtoolbarmode1').hide();
3227 $('#BRtoolbar .BRtoolbarmode3').hide();
3228 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3231 $('#BRtoolbar .BRtoolbarzoom').hide();
3232 $('#BRtoolbar .BRtoolbarmode2').hide();
3233 $('#BRtoolbar .BRtoolbarmode1').hide();
3234 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3238 // bindToolbarNavHandlers
3239 //______________________________________________________________________________
3240 // Binds the toolbar handlers
3241 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3243 var self = this; // closure
3245 jToolbar.find('.book_left').bind('click', function(e) {
3250 jToolbar.find('.book_right').bind('click', function(e) {
3255 jToolbar.find('.book_up').bind('click', function(e) {
3256 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3264 jToolbar.find('.book_down').bind('click', function(e) {
3265 if ($.inArray(self.mode, [self.constMode1up, self.constModeThumb]) >= 0) {
3273 jToolbar.find('.print').bind('click', function(e) {
3278 jToolbar.find('.embed').bind('click', function(e) {
3279 self.showEmbedCode();
3283 jToolbar.find('.play').bind('click', function(e) {
3288 jToolbar.find('.pause').bind('click', function(e) {
3293 jToolbar.find('.book_top').bind('click', function(e) {
3298 jToolbar.find('.book_bottom').bind('click', function(e) {
3303 jToolbar.find('.book_leftmost').bind('click', function(e) {
3308 jToolbar.find('.book_rightmost').bind('click', function(e) {
3314 // updateToolbarZoom(reduce)
3315 //______________________________________________________________________________
3316 // Update the displayed zoom factor based on reduction factor
3317 BookReader.prototype.updateToolbarZoom = function(reduce) {
3321 // $$$ TODO preserve zoom/fit for each mode
3322 if (this.mode == this.constMode2up) {
3323 autofit = this.twoPage.autofit;
3325 autofit = this.onePage.autofit;
3329 value = autofit.slice(0,1).toUpperCase() + autofit.slice(1);
3331 value = (100 / reduce).toFixed(2);
3332 // Strip trailing zeroes and decimal if all zeroes
3333 value = value.replace(/0+$/,'');
3334 value = value.replace(/\.$/,'');
3337 $('#BRzoom').text(value);
3340 // firstDisplayableIndex
3341 //______________________________________________________________________________
3342 // Returns the index of the first visible page, dependent on the mode.
3343 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3344 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3345 BookReader.prototype.firstDisplayableIndex = function() {
3346 if (this.mode != this.constMode2up) {
3350 if ('rl' != this.pageProgression) {
3352 if (this.getPageSide(0) == 'L') {
3359 if (this.getPageSide(0) == 'R') {
3367 // lastDisplayableIndex
3368 //______________________________________________________________________________
3369 // Returns the index of the last visible page, dependent on the mode.
3370 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3371 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3372 BookReader.prototype.lastDisplayableIndex = function() {
3374 var lastIndex = this.numLeafs - 1;
3376 if (this.mode != this.constMode2up) {
3380 if ('rl' != this.pageProgression) {
3382 if (this.getPageSide(lastIndex) == 'R') {
3385 return lastIndex + 1;
3389 if (this.getPageSide(lastIndex) == 'L') {
3392 return lastIndex + 1;
3397 // shortTitle(maximumCharacters)
3399 // Returns a shortened version of the title with the maximum number of characters
3400 BookReader.prototype.shortTitle = function(maximumCharacters) {
3401 if (this.bookTitle.length < maximumCharacters) {
3402 return this.bookTitle;
3405 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3410 // Parameter related functions
3412 // updateFromParams(params)
3414 // Update ourselves from the params object.
3416 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3417 BookReader.prototype.updateFromParams = function(params) {
3418 if ('undefined' != typeof(params.mode)) {
3419 this.switchMode(params.mode);
3423 if ('undefined' != typeof(params.searchTerm)) {
3424 if (this.searchTerm != params.searchTerm) {
3425 this.search(params.searchTerm);
3429 // $$$ process /zoom
3431 // We only respect page if index is not set
3432 if ('undefined' != typeof(params.index)) {
3433 if (params.index != this.currentIndex()) {
3434 this.jumpToIndex(params.index);
3436 } else if ('undefined' != typeof(params.page)) {
3437 // $$$ this assumes page numbers are unique
3438 if (params.page != this.getPageNum(this.currentIndex())) {
3439 this.jumpToPage(params.page);
3443 // $$$ process /region
3444 // $$$ process /highlight
3447 // paramsFromFragment(urlFragment)
3449 // Returns a object with configuration parametes from a URL fragment.
3451 // E.g paramsFromFragment(window.location.hash)
3452 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3453 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3457 // For convenience we allow an initial # character (as from window.location.hash)
3458 // but don't require it
3459 if (urlFragment.substr(0,1) == '#') {
3460 urlFragment = urlFragment.substr(1);
3463 // Simple #nn syntax
3464 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3465 if ( !isNaN(oldStyleLeafNum) ) {
3466 params.index = oldStyleLeafNum;
3468 // Done processing if using old-style syntax
3472 // Split into key-value pairs
3473 var urlArray = urlFragment.split('/');
3475 for (var i = 0; i < urlArray.length; i += 2) {
3476 urlHash[urlArray[i]] = urlArray[i+1];
3480 if ('1up' == urlHash['mode']) {
3481 params.mode = this.constMode1up;
3482 } else if ('2up' == urlHash['mode']) {
3483 params.mode = this.constMode2up;
3484 } else if ('thumb' == urlHash['mode']) {
3485 params.mode = this.constModeThumb;
3489 if ('undefined' != typeof(urlHash['page'])) {
3490 // page was set -- may not be int
3491 params.page = urlHash['page'];
3494 // $$$ process /region
3495 // $$$ process /search
3497 if (urlHash['search'] != undefined) {
3498 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3501 // $$$ process /highlight
3506 // paramsFromCurrent()
3508 // Create a params object from the current parameters.
3509 BookReader.prototype.paramsFromCurrent = function() {
3513 var index = this.currentIndex();
3514 var pageNum = this.getPageNum(index);
3515 if ((pageNum === 0) || pageNum) {
3516 params.page = pageNum;
3519 params.index = index;
3520 params.mode = this.mode;
3526 if (this.searchHighlightVisible()) {
3527 params.searchTerm = this.searchTerm;
3533 // fragmentFromParams(params)
3535 // Create a fragment string from the params object.
3536 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3537 BookReader.prototype.fragmentFromParams = function(params) {
3538 var separator = '/';
3542 if ('undefined' != typeof(params.page)) {
3543 fragments.push('page', params.page);
3545 // Don't have page numbering -- use index instead
3546 fragments.push('page', 'n' + params.index);
3553 if ('undefined' != typeof(params.mode)) {
3554 if (params.mode == this.constMode1up) {
3555 fragments.push('mode', '1up');
3556 } else if (params.mode == this.constMode2up) {
3557 fragments.push('mode', '2up');
3558 } else if (params.mode == this.constModeThumb) {
3559 fragments.push('mode', 'thumb');
3561 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3566 if (params.searchTerm) {
3567 fragments.push('search', params.searchTerm);
3570 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3573 // getPageIndex(pageNum)
3575 // Returns the *highest* index the given page number, or undefined
3576 BookReader.prototype.getPageIndex = function(pageNum) {
3577 var pageIndices = this.getPageIndices(pageNum);
3579 if (pageIndices.length > 0) {
3580 return pageIndices[pageIndices.length - 1];
3586 // getPageIndices(pageNum)
3588 // Returns an array (possibly empty) of the indices with the given page number
3589 BookReader.prototype.getPageIndices = function(pageNum) {
3592 // Check for special "nXX" page number
3593 if (pageNum.slice(0,1) == 'n') {
3595 var pageIntStr = pageNum.slice(1, pageNum.length);
3596 var pageIndex = parseInt(pageIntStr);
3597 indices.push(pageIndex);
3600 // Do nothing... will run through page names and see if one matches
3605 for (i=0; i<this.numLeafs; i++) {
3606 if (this.getPageNum(i) == pageNum) {
3614 // getPageName(index)
3616 // Returns the name of the page as it should be displayed in the user interface
3617 BookReader.prototype.getPageName = function(index) {
3618 return 'Page ' + this.getPageNum(index);
3621 // updateLocationHash
3623 // Update the location hash from the current parameters. Call this instead of manually
3624 // using window.location.replace
3625 BookReader.prototype.updateLocationHash = function() {
3626 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3627 window.location.replace(newHash);
3629 // This is the variable checked in the timer. Only user-generated changes
3630 // to the URL will trigger the event.
3631 this.oldLocationHash = newHash;
3634 // startLocationPolling
3636 // Starts polling of window.location to see hash fragment changes
3637 BookReader.prototype.startLocationPolling = function() {
3638 var self = this; // remember who I am
3639 self.oldLocationHash = window.location.hash;
3641 if (this.locationPollId) {
3642 clearInterval(this.locationPollID);
3643 this.locationPollId = null;
3646 this.locationPollId = setInterval(function() {
3647 var newHash = window.location.hash;
3648 if (newHash != self.oldLocationHash) {
3649 if (newHash != self.oldUserHash) { // Only process new user hash once
3650 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3652 // Queue change if animating
3653 if (self.animating) {
3655 self.animationFinishedCallback = function() {
3656 self.updateFromParams(self.paramsFromFragment(newHash));
3658 } else { // update immediately
3659 self.updateFromParams(self.paramsFromFragment(newHash));
3661 self.oldUserHash = newHash;
3669 // Returns true if we can switch to the requested mode
3670 BookReader.prototype.canSwitchToMode = function(mode) {
3671 if (mode == this.constMode2up) {
3672 // check there are enough pages to display
3673 // $$$ this is a workaround for the mis-feature that we can't display
3674 // short books in 2up mode
3675 if (this.numLeafs < 6) {
3683 // searchHighlightVisible
3685 // Returns true if a search highlight is currently being displayed
3686 BookReader.prototype.searchHighlightVisible = function() {
3687 if (this.constMode2up == this.mode) {
3688 if (this.searchResults[this.twoPage.currentIndexL]
3689 || this.searchResults[this.twoPage.currentIndexR]) {
3693 if (this.searchResults[this.currentIndex()]) {
3702 // Returns the page width for the given index, or first or last page if out of range
3703 BookReader.prototype._getPageWidth = function(index) {
3704 // Synthesize a page width for pages not actually present in book.
3705 // May or may not be the best approach.
3706 // If index is out of range we return the width of first or last page
3707 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3708 return this.getPageWidth(index);
3713 // Returns the page height for the given index, or first or last page if out of range
3714 BookReader.prototype._getPageHeight= function(index) {
3715 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3716 return this.getPageHeight(index);
3721 // Returns the page URI or transparent image if out of range
3722 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3723 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3724 return this.imagesBaseURL + "/transparent.png";
3727 if ('undefined' == typeof(reduce)) {
3728 // reduce not passed in
3729 // $$$ this probably won't work for thumbnail mode
3730 var ratio = this.getPageHeight(index) / this.twoPage.height;
3732 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3735 } else if (ratio < 4) {
3737 } else if (ratio < 8) {
3739 } else if (ratio < 16) {
3741 } else if (ratio < 32) {
3749 return this.getPageURI(index, reduce, rotate);
3752 // Library functions
3754 disableSelect: function(jObject) {
3755 // Bind mouse handlers
3756 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3757 jObject.bind('mousedown', function(e) {
3758 // $$$ check here for right-click and don't disable. Also use jQuery style
3759 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3762 // Special hack for IE7
3763 jObject[0].onselectstart = function(e) { return false; };
3766 clamp: function(value, min, max) {
3767 return Math.min(Math.max(value, min), max);
3770 notInArray: function(value, array) {
3771 // inArray returns -1 or undefined if value not in array
3772 return ! (jQuery.inArray(value, array) >= 0);
3775 getIFrameDocument: function(iframe) {
3776 // Adapted from http://xkr.us/articles/dom/iframe-document/
3777 var outer = (iframe.contentWindow || iframe.contentDocument);
3778 return (outer.document || outer);
3781 decodeURIComponentPlus: function(value) {
3782 // Decodes a URI component and converts '+' to ' '
3783 return decodeURIComponent(value).replace(/\+/g, ' ');
3786 encodeURIComponentPlus: function(value) {
3787 // Encodes a URI component and converts ' ' to '+'
3788 return encodeURIComponent(value).replace(/%20/g, '+');
3790 // The final property here must NOT have a comma after it - IE7
3795 //______________________________________________________________________________
3796 BookReader.prototype.ttsStart = function () {
3797 console.log('starting readAloud');
3798 var url = 'http://'+this.server+'/BookReader/BookReaderGetTextWrapper.php?path='+this.bookPath+'_djvu.xml&page='+this.currentIndex();
3799 this.ttsIndex = this.currentIndex();
3800 $.ajax({url:url, dataType:'jsonp', jsonpCallback:'ttsStartCB'});
3804 //______________________________________________________________________________
3805 BookReader.prototype.ttsGetText = function(index, callback) {
3806 var url = 'http://'+this.server+'/BookReader/BookReaderGetTextWrapper.php?path='+this.bookPath+'_djvu.xml&page='+index;
3807 $.ajax({url:url, dataType:'jsonp', jsonpCallback:callback});
3810 // ttsStartCB(): text-to-speech callback
3811 //______________________________________________________________________________
3812 BookReader.prototype.ttsStartCB = function (data) {
3813 console.log('ttsStartCB got data:');
3815 this.ttsChunks = data;
3816 this.ttsHilites = [];
3817 //$.ajax({url:'http://'+this.ttsServer+'/renderAudio.py', data:{string:data[0][0], format:'ogg'}, dataType:'json'});
3819 this.ttsShowPopup();
3821 this.ttsPosition = -1;
3822 var snd = soundManager.createSound({
3823 id: 'chunk'+this.ttsIndex+'-0',
3824 //url: 'http://home.us.archive.org/~rkumar/arctic.ogg',
3825 url: 'http://home.us.archive.org/~rkumar/getOgg.php?string=' + escape(data[0][0]) + '&f=.ogg', //the .ogg is to trick SoundManager2 to use the HTML5 audio player
3826 whileloading: function(){if (this.bytesLoaded == this.bytesTotal) {$(br.popup).remove(); br.popup=null;}} //onload never fires...
3831 this.ttsNextChunk();
3835 //______________________________________________________________________________
3836 BookReader.prototype.ttsShowPopup = function() {
3837 this.popup = document.createElement("div");
3839 position: 'absolute',
3841 left: ($('#BRcontainer').attr('clientWidth')-600)/2 + 'px',
3844 border: "3px double #999999",
3846 backgroundColor: "#f00",
3849 }).appendTo('#BookReader');
3851 htmlStr = '<p style="text-align:center;"><b>Ever wanted to wait while audio loads?</b><br/>';
3852 htmlStr += "It's OK. We all do.</p>";
3854 this.popup.innerHTML = htmlStr;
3858 //______________________________________________________________________________
3859 BookReader.prototype.ttsNextPageCB = function (data) {
3860 this.ttsNextChunks = data;
3861 console.log('preloaded next chunks.. data is');
3865 //______________________________________________________________________________
3866 BookReader.prototype.ttsLoadChunk = function (page, pos, string) {
3867 var snd = soundManager.createSound({
3868 id: 'chunk'+page+'-'+pos,
3869 url: 'http://home.us.archive.org/~rkumar/getOgg.php?string=' + escape(string) + '&f=.ogg' //the .ogg is to trick SoundManager2 to use the HTML5 audio player
3877 //______________________________________________________________________________
3878 BookReader.prototype.ttsNextChunk = function () {
3880 console.log(this.ttsPosition);
3882 if (-1 != this.ttsPosition) {
3883 soundManager.destroySound('chunk'+this.ttsIndex+'-'+this.ttsPosition);
3887 console.log('next chunk is ');
3888 console.log(this.ttsPosition);
3890 if (this.ttsPosition >= this.ttsChunks.length) {
3892 if (this.ttsIndex == (this.numLeafs-1)) {
3893 console.log('tts stop');
3896 if (null != this.ttsNextChunks) {
3897 console.log('moving to next page!');
3899 this.ttsPosition = 0;
3900 this.ttsChunks = this.ttsNextChunks;
3901 this.ttsNextChunks = null;
3903 console.log('ttsNextChunks is null');
3909 //prefetch next page of text
3910 if (0 == this.ttsPosition) {
3911 if (this.ttsIndex<(this.numLeafs-1)) {
3912 this.ttsGetText(this.ttsIndex+1, 'ttsNextPageCB');
3916 var chunk = this.ttsChunks[this.ttsPosition];
3917 console.log('position = ' + this.ttsPosition);
3918 console.log('chunk = ' + chunk);
3919 console.log(this.ttsChunks);
3921 //remove old hilights
3922 $(this.ttsHilites).remove();
3923 this.ttsHilites = [];
3926 if (2 == this.mode) {
3927 this.ttsHilite2UP(chunk);
3929 alert('only 2 page mode supported for TTS..');
3932 //preload next chunk
3933 var nextPos = this.ttsPosition+1;
3934 if (nextPos < this.ttsChunks.length) {
3935 this.ttsLoadChunk(this.ttsIndex, nextPos, this.ttsChunks[nextPos][0]);
3937 this.ttsLoadChunk(this.ttsIndex+1, 0, this.ttsNextChunks[0][0]);
3940 //play current chunk
3941 soundManager.play('chunk'+this.ttsIndex+'-'+this.ttsPosition,{onfinish:function(){br.ttsNextChunk();}});
3946 //______________________________________________________________________________
3947 BookReader.prototype.ttsHilite2UP = function (chunk) {
3949 for (i=0; i<chunk.length; i++) {
3950 //each rect is an array of l,b,r,t coords (djvu.xml ordering...)
3951 var l = chunk[i][0];
3952 var b = chunk[i][1];
3953 var r = chunk[i][2];
3954 var t = chunk[i][3];
3956 var div = document.createElement('div');
3957 this.ttsHilites.push(div);
3958 $(div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
3959 this.setHilightCss2UP(div, this.ttsIndex, l, r, t, b);