2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
6 BookReader is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 BookReader is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
45 this.thumbWidth = 100; // will be overridden during prepareThumbnailView
46 this.thumbRowBuffer = 2; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.thumbMaxLoading = 4; // number of thumbnails to load at once
49 this.displayedRows=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
88 // Object to hold parameters related to 2up mode
90 coverInternalPadding: 10, // Width of cover
91 coverExternalPadding: 10, // Padding outside of cover
92 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
96 // Background color for pages (e.g. when loading page image)
97 // $$$ TODO dynamically calculate based on page images
98 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
104 //______________________________________________________________________________
105 BookReader.prototype.init = function() {
107 var startIndex = undefined;
108 this.pageScale = this.reduce; // preserve current reduce
110 // Find start index and mode if set in location hash
111 var params = this.paramsFromFragment(window.location.hash);
113 if ('undefined' != typeof(params.index)) {
114 startIndex = params.index;
115 } else if ('undefined' != typeof(params.page)) {
116 startIndex = this.getPageIndex(params.page);
119 if ('undefined' == typeof(startIndex)) {
120 if ('undefined' != typeof(this.titleLeaf)) {
121 startIndex = this.leafNumToIndex(this.titleLeaf);
125 if ('undefined' == typeof(startIndex)) {
129 if ('undefined' != typeof(params.mode)) {
130 this.mode = params.mode;
133 // Set document title -- may have already been set in enclosing html for
134 // search engine visibility
135 document.title = this.shortTitle(50);
137 // Sanitize parameters
138 if ( !this.canSwitchToMode( this.mode ) ) {
139 this.mode = this.constMode1up;
142 $("#BookReader").empty();
143 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
144 $("#BookReader").append("<div id='BRcontainer'></div>");
145 $("#BRcontainer").append("<div id='BRpageview'></div>");
147 $("#BRcontainer").bind('scroll', this, function(e) {
151 this.setupKeyListeners();
152 this.startLocationPolling();
154 $(window).bind('resize', this, function(e) {
155 //console.log('resize!');
156 if (1 == e.data.mode) {
157 //console.log('centering 1page view');
158 e.data.centerPageView();
159 $('#BRpageview').empty()
160 e.data.displayedIndices = [];
161 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
163 } else if (3 == e.data.mode){
164 e.data.prepareThumbnailView();
166 //console.log('drawing 2 page view');
168 // We only need to prepare again in autofit (size of spread changes)
169 if (e.data.twoPage.autofit) {
170 e.data.prepareTwoPageView();
172 // Re-center if the scrollbars have disappeared
173 var center = e.data.twoPageGetViewCenter();
174 var doRecenter = false;
175 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
176 center.percentageX = 0.5;
179 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
180 center.percentageY = 0.5;
184 e.data.twoPageCenterView(center.percentageX, center.percentageY);
190 $('.BRpagediv1up').bind('mousedown', this, function(e) {
191 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
192 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
196 // $$$ refactor this so it's enough to set the first index and call preparePageView
197 // (get rid of mode-specific logic at this point)
198 if (1 == this.mode) {
199 this.resizePageView();
200 this.firstIndex = startIndex;
201 this.jumpToIndex(startIndex);
202 } else if (3 == this.mode) {
203 this.firstIndex = startIndex;
204 this.prepareThumbnailView();
205 this.jumpToIndex(startIndex);
207 //this.resizePageView();
209 this.displayedIndices=[0];
210 this.firstIndex = startIndex;
211 this.displayedIndices = [this.firstIndex];
212 //console.log('titleLeaf: %d', this.titleLeaf);
213 //console.log('displayedIndices: %s', this.displayedIndices);
214 this.prepareTwoPageView();
217 // Enact other parts of initial params
218 this.updateFromParams(params);
221 BookReader.prototype.setupKeyListeners = function() {
234 // We use document here instead of window to avoid a bug in jQuery on IE7
235 $(document).keydown(function(e) {
237 // Keyboard navigation
238 if (!self.keyboardNavigationIsDisabled(e)) {
242 // In 1up mode page scrolling is handled by browser
243 if (2 == self.mode) {
250 if (2 == self.mode) {
264 if (2 == self.mode) {
270 if (2 == self.mode) {
281 //______________________________________________________________________________
282 BookReader.prototype.drawLeafs = function() {
283 if (1 == this.mode) {
284 this.drawLeafsOnePage();
285 } else if (3 == this.mode) {
286 this.drawLeafsThumbnail();
288 this.drawLeafsTwoPage();
294 //______________________________________________________________________________
295 BookReader.prototype.setDragHandler = function(div) {
296 div.dragging = false;
298 $(div).unbind('mousedown').bind('mousedown', function(e) {
301 //console.log('mousedown at ' + e.pageY);
303 this.dragging = true;
304 this.prevMouseX = e.pageX;
305 this.prevMouseY = e.pageY;
307 var startX = e.pageX;
308 var startY = e.pageY;
309 var startTop = $('#BRcontainer').attr('scrollTop');
310 var startLeft = $('#BRcontainer').attr('scrollLeft');
314 $(div).unbind('mousemove').bind('mousemove', function(ee) {
317 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
319 var offsetX = ee.pageX - this.prevMouseX;
320 var offsetY = ee.pageY - this.prevMouseY;
323 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
324 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
327 this.prevMouseX = ee.pageX;
328 this.prevMouseY = ee.pageY;
332 $(div).unbind('mouseup').bind('mouseup', function(ee) {
334 //console.log('mouseup');
336 this.dragging = false;
339 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
341 //console.log('mouseleave');
343 this.dragging = false;
346 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
348 //console.log('mouseenter');
350 this.dragging = false;
354 // setDragHandler2UP()
355 //______________________________________________________________________________
356 BookReader.prototype.setDragHandler2UP = function(div) {
357 div.dragging = false;
359 $(div).unbind('mousedown').bind('mousedown', function(e) {
362 //console.log('mousedown at ' + e.pageY);
364 this.dragStart = {x: e.pageX, y: e.pageY };
365 this.mouseDown = true;
366 this.dragging = false; // wait until drag distance
367 this.prevMouseX = e.pageX;
368 this.prevMouseY = e.pageY;
370 var startX = e.pageX;
371 var startY = e.pageY;
372 var startTop = $('#BRcontainer').attr('scrollTop');
373 var startLeft = $('#BRcontainer').attr('scrollLeft');
377 $(div).unbind('mousemove').bind('mousemove', function(ee) {
380 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
382 var offsetX = ee.pageX - this.prevMouseX;
383 var offsetY = ee.pageY - this.prevMouseY;
385 var minDragDistance = 5; // $$$ constant
387 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
389 if (this.mouseDown && (distance > minDragDistance)) {
390 //console.log('drag start!');
392 this.dragging = true;
396 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
397 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
398 this.prevMouseX = ee.pageX;
399 this.prevMouseY = ee.pageY;
406 $(div).unbind('mouseup').bind('mouseup', function(ee) {
408 //console.log('mouseup');
410 this.dragging = false;
411 this.mouseDown = false;
416 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
418 //console.log('mouseleave');
420 this.dragging = false;
421 this.mouseDown = false;
424 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
426 //console.log('mouseenter');
428 this.dragging = false;
429 this.mouseDown = false;
433 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
434 //console.log('setting handler');
435 //console.log(element.tagName);
437 $(element).unbind('click').bind('click', data, function(e) {
440 //console.log('click!');
442 if (this.mouseDown && (!this.dragging)) {
443 //console.log('click not dragging!');
447 this.dragging = false;
448 this.mouseDown = false;
452 // drawLeafsOnePage()
453 //______________________________________________________________________________
454 BookReader.prototype.drawLeafsOnePage = function() {
455 //alert('drawing leafs!');
459 var scrollTop = $('#BRcontainer').attr('scrollTop');
460 var scrollBottom = scrollTop + $('#BRcontainer').height();
461 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
463 var indicesToDisplay = [];
468 for (i=0; i<this.numLeafs; i++) {
469 var height = parseInt(this._getPageHeight(i)/this.reduce);
471 leafBottom += height;
472 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
473 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
474 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
475 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
476 if (topInView | bottomInView | middleInView) {
477 //console.log('displayed: ' + this.displayedIndices);
478 //console.log('to display: ' + i);
479 indicesToDisplay.push(i);
481 leafTop += height +10;
485 var firstIndexToDraw = indicesToDisplay[0];
486 this.firstIndex = firstIndexToDraw;
488 // Update hash, but only if we're currently displaying a leaf
489 // Hack that fixes #365790
490 if (this.displayedIndices.length > 0) {
491 this.updateLocationHash();
494 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
496 indicesToDisplay.unshift(firstIndexToDraw);
499 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
500 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
501 indicesToDisplay.push(lastIndexToDraw+1);
506 for (i=0; i<firstIndexToDraw; i++) {
507 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
510 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
511 var viewWidth = $('#BRcontainer').attr('scrollWidth');
514 for (i=0; i<indicesToDisplay.length; i++) {
515 var index = indicesToDisplay[i];
516 var height = parseInt(this._getPageHeight(index)/this.reduce);
518 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
519 var width = parseInt(this._getPageWidth(index)/this.reduce);
520 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
521 var div = document.createElement("div");
522 div.className = 'BRpagediv1up';
523 div.id = 'pagediv'+index;
524 div.style.position = "absolute";
525 $(div).css('top', leafTop + 'px');
526 var left = (viewWidth-width)>>1;
527 if (left<0) left = 0;
528 $(div).css('left', left+'px');
529 $(div).css('width', width+'px');
530 $(div).css('height', height+'px');
531 //$(div).text('loading...');
533 this.setDragHandler(div);
535 $('#BRpageview').append(div);
537 var img = document.createElement("img");
538 img.src = this._getPageURI(index, this.reduce, 0);
539 $(img).css('width', width+'px');
540 $(img).css('height', height+'px');
544 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
547 leafTop += height +10;
551 for (i=0; i<this.displayedIndices.length; i++) {
552 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
553 var index = this.displayedIndices[i];
554 //console.log('Removing leaf ' + index);
555 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
556 $('#pagediv'+index).remove();
558 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
562 this.displayedIndices = indicesToDisplay.slice();
563 this.updateSearchHilites();
565 if (null != this.getPageNum(firstIndexToDraw)) {
566 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
568 $("#BRpagenum").val('');
571 this.updateToolbarZoom(this.reduce);
575 // drawLeafsThumbnail()
576 //______________________________________________________________________________
577 // If seekIndex is defined, the view will be drawn with that page visible (without any
578 // animated scrolling)
579 BookReader.prototype.drawLeafsThumbnail = function( seekIndex ) {
580 //alert('drawing leafs!');
583 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
585 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
599 // Will be set to top of requested seek index, if set
602 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
603 for (i=0; i<this.numLeafs; i++) {
604 leafWidth = this.thumbWidth;
605 if (rightPos + (leafWidth + this.padding) > viewWidth){
611 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
612 if (leafMap[currentRow].leafs===undefined) {
613 leafMap[currentRow].leafs = [];
614 leafMap[currentRow].height = 0;
615 leafMap[currentRow].top = 0;
617 leafMap[currentRow].leafs[leafIndex] = {};
618 leafMap[currentRow].leafs[leafIndex].num = i;
619 leafMap[currentRow].leafs[leafIndex].left = rightPos;
621 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
622 if (leafHeight > leafMap[currentRow].height) {
623 leafMap[currentRow].height = leafHeight;
625 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
626 rightPos += leafWidth + this.padding;
627 if (rightPos > maxRight) { maxRight = rightPos; }
630 if (i == seekIndex) {
631 seekTop = bottomPos - this.padding - leafMap[currentRow].height;
635 // reset the bottom position based on thumbnails
636 $('#BRpageview').height(bottomPos);
638 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
640 // If seekTop is defined, seeking was requested and target found
641 if (typeof(seekTop) != 'undefined') {
642 $('#BRcontainer').scrollTop( seekTop );
645 var scrollTop = $('#BRcontainer').attr('scrollTop');
646 var scrollBottom = scrollTop + $('#BRcontainer').height();
650 var rowsToDisplay = [];
652 // Visible leafs with least/greatest index
653 var leastVisible = this.numLeafs - 1;
656 // Determine the thumbnails in view
657 for (i=0; i<leafMap.length; i++) {
658 leafBottom += this.padding + leafMap[i].height;
659 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
660 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
661 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
662 if (topInView | bottomInView | middleInView) {
663 //console.log('row to display: ' + j);
664 rowsToDisplay.push(i);
665 if (leafMap[i].leafs[0].num < leastVisible) {
666 leastVisible = leafMap[i].leafs[0].num;
668 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
669 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
672 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
673 leafTop = leafBottom;
676 // create a buffer of preloaded rows before and after the visible rows
677 var firstRow = rowsToDisplay[0];
678 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
679 for (i=1; i<this.thumbRowBuffer+1; i++) {
680 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
682 for (i=1; i<this.thumbRowBuffer+1; i++) {
683 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
686 // Create the thumbnail divs and images (lazy loaded)
695 for (i=0; i<rowsToDisplay.length; i++) {
696 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
697 row = rowsToDisplay[i];
699 for (j=0; j<leafMap[row].leafs.length; j++) {
701 leaf = leafMap[row].leafs[j].num;
703 leafWidth = this.thumbWidth;
704 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
705 leafTop = leafMap[row].top;
706 left = leafMap[row].leafs[index].left + pageViewBuffer;
707 if ('rl' == this.pageProgression){
708 left = viewWidth - leafWidth - left;
711 div = document.createElement("div");
712 div.id = 'pagediv'+leaf;
713 div.style.position = "absolute";
714 div.className = "BRpagedivthumb";
716 left += this.padding;
717 $(div).css('top', leafTop + 'px');
718 $(div).css('left', left+'px');
719 $(div).css('width', leafWidth+'px');
720 $(div).css('height', leafHeight+'px');
721 //$(div).text('loading...');
723 // link to page in single page mode
724 link = document.createElement("a");
725 $(link).data('leaf', leaf);
726 $(link).bind('click', function(event) {
727 self.firstIndex = $(this).data('leaf');
728 self.switchMode(self.constMode1up);
729 event.preventDefault();
732 // $$$ we don't actually go to this URL (click is handled in handler above)
733 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
736 $('#BRpageview').append(div);
738 img = document.createElement("img");
739 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
741 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
742 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
743 .addClass('BRlazyload')
744 // Store the URL of the image that will replace this one
745 .data('srcURL', this._getPageURI(leaf, thumbReduce));
747 //console.log('displaying thumbnail: ' + leaf);
752 // Remove thumbnails that are not to be displayed
754 for (i=0; i<this.displayedRows.length; i++) {
755 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
756 row = this.displayedRows[i];
758 // $$$ Safari doesn't like the comprehension
759 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
760 //console.log('Removing row ' + row + ' ' + rowLeafs);
762 for (k=0; k<leafMap[row].leafs.length; k++) {
763 index = leafMap[row].leafs[k].num;
764 //console.log('Removing leaf ' + index);
765 $('#pagediv'+index).remove();
769 var mRow = this.displayedRows[i];
770 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
771 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
776 // Update which page is considered current to make sure a visible page is the current one
777 var currentIndex = this.currentIndex();
778 // console.log('current ' + currentIndex);
779 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
780 if (currentIndex < leastVisible) {
781 this.setCurrentIndex(leastVisible);
782 } else if (currentIndex > mostVisible) {
783 this.setCurrentIndex(mostVisible);
786 this.displayedRows = rowsToDisplay.slice();
788 // Update hash, but only if we're currently displaying a leaf
789 // Hack that fixes #365790
790 if (this.displayedRows.length > 0) {
791 this.updateLocationHash();
794 // remove previous highlights
795 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
797 // highlight current page
798 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
800 this.lazyLoadThumbnails();
802 // Update page number box. $$$ refactor to function
803 if (null !== this.getPageNum(this.currentIndex())) {
804 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
806 $("#BRpagenum").val('');
809 this.updateToolbarZoom(this.reduce);
812 BookReader.prototype.lazyLoadThumbnails = function() {
814 // console.log('lazy load');
816 // We check the complete property since load may not be fired if loading from the cache
817 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
819 var loading = $('.BRlazyloading').length;
820 var toLoad = this.thumbMaxLoading - loading;
822 // console.log(' ' + loading + ' thumbnails loading');
823 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
828 // $$$ TODO load those near top (but not beyond) page view first
829 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
830 self.lazyLoadImage(this);
835 BookReader.prototype.lazyLoadImage = function (dummyImage) {
836 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
838 var img = new Image();
842 .addClass('BRlazyloading')
843 .one('load', function() {
844 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
846 $(this).removeClass('BRlazyloading');
848 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
849 // we call the function after a slight delay. Also the img.complete property
850 // is not yet set in IE8 inside this onload handler
851 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
853 .one('error', function() {
854 // Remove class so we no longer count as loading
855 $(this).removeClass('BRlazyloading');
857 .attr( { width: $(dummyImage).width(),
858 height: $(dummyImage).height(),
859 src: $(dummyImage).data('srcURL')
862 // replace with the new img
863 $(dummyImage).before(img).remove();
865 img = null; // tidy up closure
869 // drawLeafsTwoPage()
870 //______________________________________________________________________________
871 BookReader.prototype.drawLeafsTwoPage = function() {
872 var scrollTop = $('#BRtwopageview').attr('scrollTop');
873 var scrollBottom = scrollTop + $('#BRtwopageview').height();
875 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
877 var indexL = this.twoPage.currentIndexL;
879 var heightL = this._getPageHeight(indexL);
880 var widthL = this._getPageWidth(indexL);
882 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
883 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
884 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
885 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
886 //console.log(leafEdgeWidthL);
888 var middle = this.twoPage.middle; // $$$ getter instead?
889 var top = this.twoPageTop();
890 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
892 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
893 this.twoPage.gutter = this.twoPageGutter();
895 this.prefetchImg(indexL);
896 $(this.prefetchedImgs[indexL]).css({
897 position: 'absolute',
898 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
901 backgroundColor: this.getPageBackgroundColor(indexL),
902 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
903 width: this.twoPage.scaledWL + 'px',
904 borderRight: '1px solid black',
906 }).appendTo('#BRtwopageview');
908 var indexR = this.twoPage.currentIndexR;
909 var heightR = this._getPageHeight(indexR);
910 var widthR = this._getPageWidth(indexR);
912 // $$$ should use getwidth2up?
913 //var scaledWR = this.twoPage.height*widthR/heightR;
914 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
915 this.prefetchImg(indexR);
916 $(this.prefetchedImgs[indexR]).css({
917 position: 'absolute',
918 left: this.twoPage.gutter+'px',
921 backgroundColor: this.getPageBackgroundColor(indexR),
922 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
923 width: this.twoPage.scaledWR + 'px',
924 borderLeft: '1px solid black',
926 }).appendTo('#BRtwopageview');
929 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
930 this.setMouseHandlers2UP();
931 this.twoPageSetCursor();
933 this.updatePageNumBox2UP();
934 this.updateToolbarZoom(this.reduce);
936 // this.twoPagePlaceFlipAreas(); // No longer used
940 // updatePageNumBox2UP
941 //______________________________________________________________________________
942 BookReader.prototype.updatePageNumBox2UP = function() {
943 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
944 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
946 $("#BRpagenum").val('');
948 this.updateLocationHash();
952 //______________________________________________________________________________
953 BookReader.prototype.loadLeafs = function() {
957 if (null == this.timer) {
958 this.timer=setTimeout(function(){self.drawLeafs()},250);
960 clearTimeout(this.timer);
961 this.timer=setTimeout(function(){self.drawLeafs()},250);
967 // Pass 1 to zoom in, anything else to zoom out
968 //______________________________________________________________________________
969 BookReader.prototype.zoom = function(direction) {
971 case this.constMode1up:
972 return this.zoom1up(direction);
973 case this.constMode2up:
974 return this.zoom2up(direction);
975 case this.constModeThumb:
976 return this.zoomThumb(direction);
981 //______________________________________________________________________________
982 BookReader.prototype.zoom1up = function(dir) {
984 if (2 == this.mode) { //can only zoom in 1-page mode
989 // $$$ with flexible zoom we could "snap" to /2 page reductions
990 // for better scaling
992 if (this.reduce <= 0.5) return;
993 this.reduce*=0.5; //zoom in
995 if (this.reduce >= 8) return;
996 this.reduce*=2; //zoom out
999 this.pageScale = this.reduce; // preserve current reduce
1000 this.resizePageView();
1002 $('#BRpageview').empty()
1003 this.displayedIndices = [];
1006 this.updateToolbarZoom(this.reduce);
1008 // Recalculate search hilites
1009 this.removeSearchHilites();
1010 this.updateSearchHilites();
1015 //______________________________________________________________________________
1016 BookReader.prototype.resizePageView = function() {
1018 // $$$ This code assumes 1up mode
1019 // e.g. does not preserve position in thumbnail mode
1020 // See http://bugs.launchpad.net/bookreader/+bug/552972
1022 switch (this.mode) {
1023 case this.constMode1up:
1024 case this.constMode2up:
1025 this.resizePageView1up();
1027 case this.constModeThumb:
1028 this.prepareThumbnailView( this.currentIndex() );
1031 alert('Resize not implemented for this mode');
1035 BookReader.prototype.resizePageView1up = function() {
1038 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
1039 var viewWidth = $('#BRcontainer').attr('clientWidth');
1041 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
1042 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
1043 var oldPageViewHeight = $('#BRpageview').height();
1044 var oldPageViewWidth = $('#BRpageview').width();
1046 var oldCenterY = this.centerY1up();
1047 var oldCenterX = this.centerX1up();
1049 if (0 != oldPageViewHeight) {
1050 var scrollRatio = oldCenterY / oldPageViewHeight;
1052 var scrollRatio = 0;
1055 for (i=0; i<this.numLeafs; i++) {
1056 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
1057 var width = parseInt(this._getPageWidth(i)/this.reduce);
1058 if (width>viewWidth) viewWidth=width;
1060 $('#BRpageview').height(viewHeight);
1061 $('#BRpageview').width(viewWidth);
1063 var newCenterY = scrollRatio*viewHeight;
1064 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
1065 $('#BRcontainer').attr('scrollTop', newTop);
1067 // We use clientWidth here to avoid miscalculating due to scroll bar
1068 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
1069 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
1070 newLeft = Math.max(newLeft, 0);
1071 $('#BRcontainer').attr('scrollLeft', newLeft);
1072 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
1074 //this.centerPageView();
1077 this.removeSearchHilites();
1078 this.updateSearchHilites();
1083 //______________________________________________________________________________
1084 // Returns the current offset of the viewport center in scaled document coordinates.
1085 BookReader.prototype.centerX1up = function() {
1087 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
1088 centerX = $('#BRpageview').width();
1090 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
1092 centerX = Math.floor(centerX);
1097 //______________________________________________________________________________
1098 // Returns the current offset of the viewport center in scaled document coordinates.
1099 BookReader.prototype.centerY1up = function() {
1100 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1101 return Math.floor(centerY);
1105 //______________________________________________________________________________
1106 BookReader.prototype.centerPageView = function() {
1108 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1109 var clientWidth = $('#BRcontainer').attr('clientWidth');
1110 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1111 if (scrollWidth > clientWidth) {
1112 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1117 // zoom2up(direction)
1118 //______________________________________________________________________________
1119 BookReader.prototype.zoom2up = function(direction) {
1121 // Hard stop autoplay
1122 this.stopFlipAnimations();
1124 // Get new zoom state
1125 var newZoom = this.twoPageNextReduce(this.reduce, direction);
1126 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
1129 this.twoPage.autofit = newZoom.autofit;
1130 this.reduce = newZoom.reduce;
1131 this.pageScale = this.reduce; // preserve current reduce
1133 // Preserve view center position
1134 var oldCenter = this.twoPageGetViewCenter();
1136 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1137 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1138 if (1 == direction) {
1139 for (var img in this.prefetchedImgs) {
1140 delete this.prefetchedImgs[img];
1144 // Prepare view with new center to minimize visual glitches
1145 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1148 BookReader.prototype.zoomThumb = function(direction) {
1149 var oldColumns = this.thumbColumns;
1150 switch (direction) {
1152 this.thumbColumns += 1;
1155 this.thumbColumns -= 1;
1160 if (this.thumbColumns < 2) {
1161 this.thumbColumns = 2;
1162 } else if (this.thumbColumns > 8) {
1163 this.thumbColumns = 8;
1166 if (this.thumbColumns != oldColumns) {
1167 this.prepareThumbnailView();
1171 // Returns the width per thumbnail to display the requested number of columns
1172 // Note: #BRpageview must already exist since its width is used to calculate the
1174 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1175 var padding = (thumbnailColumns + 1) * this.padding;
1176 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1177 return parseInt(width);
1180 // quantizeReduce(reduce)
1181 //______________________________________________________________________________
1182 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1183 BookReader.prototype.quantizeReduce = function(reduce) {
1184 var quantized = this.reductionFactors[0];
1185 var distance = Math.abs(reduce - quantized);
1186 for (var i = 1; i < this.reductionFactors.length; i++) {
1187 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1188 if (newDistance < distance) {
1189 distance = newDistance;
1190 quantized = this.reductionFactors[i];
1197 // twoPageNextReduce()
1198 //______________________________________________________________________________
1199 // Returns the next reduction level
1200 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1202 var autofitReduce = this.twoPageGetAutofitReduce();
1204 if (0 == direction) { // autofit
1205 result.autofit = true;
1206 result.reduce = autofitReduce;
1208 } else if (1 == direction) { // zoom in
1209 var newReduce = this.reductionFactors[0];
1211 for (var i = 1; i < this.reductionFactors.length; i++) {
1212 if (this.reductionFactors[i] < reduce) {
1213 newReduce = this.reductionFactors[i];
1217 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1219 result.autofit = true;
1220 result.reduce = autofitReduce;
1222 result.autofit = false;
1223 result.reduce = newReduce;
1226 } else { // zoom out
1227 var lastIndex = this.reductionFactors.length - 1;
1228 var newReduce = this.reductionFactors[lastIndex];
1230 for (var i = lastIndex; i >= 0; i--) {
1231 if (this.reductionFactors[i] > reduce) {
1232 newReduce = this.reductionFactors[i];
1236 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1238 result.autofit = true;
1239 result.reduce = autofitReduce;
1241 result.autofit = false;
1242 result.reduce = newReduce;
1250 //______________________________________________________________________________
1251 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1252 BookReader.prototype.jumpToPage = function(pageNum) {
1254 var pageIndex = this.getPageIndex(pageNum);
1256 if ('undefined' != typeof(pageIndex)) {
1259 this.jumpToIndex(pageIndex);
1260 $('#BRcontainer').attr('scrollTop', leafTop);
1269 //______________________________________________________________________________
1270 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1272 if (2 == this.mode) {
1275 // By checking against min/max we do nothing if requested index
1277 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1278 this.flipBackToIndex(index);
1279 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1280 this.flipFwdToIndex(index);
1283 } else if (3 == this.mode) {
1284 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1294 for (i=0; i<(index+1); i++) {
1295 leafWidth = this.thumbWidth;
1296 if (rightPos + (leafWidth + this.padding) > viewWidth){
1302 leafHeight = parseInt((this.getPageHeight(leafIndex)*this.thumbWidth)/this.getPageWidth(leafIndex), 10);
1303 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1304 if (leafIndex==0) { leafTop = bottomPos; }
1305 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1306 rightPos += leafWidth + this.padding;
1309 this.firstIndex=index;
1310 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1313 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1320 for (i=0; i<index; i++) {
1321 h = parseInt(this._getPageHeight(i)/this.reduce);
1322 leafTop += h + this.padding;
1326 //console.log('pageY ' + pageY);
1327 var offset = parseInt( (pageY) / this.reduce);
1328 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1329 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1334 var offset = parseInt( (pageX) / this.reduce);
1335 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1339 //$('#BRcontainer').attr('scrollTop', leafTop);
1340 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1346 //______________________________________________________________________________
1347 BookReader.prototype.switchMode = function(mode) {
1349 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1351 if (mode == this.mode) {
1355 if (!this.canSwitchToMode(mode)) {
1360 this.removeSearchHilites();
1363 this.switchToolbarMode(mode);
1365 // reinstate scale if moving from thumbnail view
1366 if (this.pageScale != this.reduce) {
1367 this.reduce = this.pageScale;
1370 // $$$ TODO preserve center of view when switching between mode
1371 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1374 this.reduce = this.quantizeReduce(this.reduce);
1375 this.prepareOnePageView();
1376 } else if (3 == mode) {
1377 this.reduce = this.quantizeReduce(this.reduce);
1378 this.prepareThumbnailView();
1380 // $$$ why don't we save autofit?
1381 this.twoPage.autofit = false; // Take zoom level from other mode
1382 this.reduce = this.quantizeReduce(this.reduce);
1383 this.prepareTwoPageView();
1384 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1389 //prepareOnePageView()
1390 //______________________________________________________________________________
1391 BookReader.prototype.prepareOnePageView = function() {
1393 // var startLeaf = this.displayedIndices[0];
1394 var startLeaf = this.currentIndex();
1396 $('#BRcontainer').empty();
1397 $('#BRcontainer').css({
1398 overflowY: 'scroll',
1402 $("#BRcontainer").append("<div id='BRpageview'></div>");
1403 // $$$ keep select enabled for now since disabling it breaks keyboard
1404 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1405 // BookReader.util.disableSelect($('#BRpageview'));
1407 this.resizePageView();
1409 this.jumpToIndex(startLeaf);
1410 this.displayedIndices = [];
1412 this.drawLeafsOnePage();
1415 //prepareThumbnailView()
1416 //______________________________________________________________________________
1417 BookReader.prototype.prepareThumbnailView = function() {
1419 $('#BRcontainer').empty();
1420 $('#BRcontainer').css({
1421 overflowY: 'scroll',
1425 $("#BRcontainer").append("<div id='BRpageview'></div>");
1427 // $$$ keep select enabled for now since disabling it breaks keyboard
1428 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1429 // BookReader.util.disableSelect($('#BRpageview'));
1431 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1432 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1434 this.displayedRows = [];
1436 // Draw leafs with current index directly in view (no animating to the index)
1437 this.drawLeafsThumbnail( this.currentIndex() );
1441 // prepareTwoPageView()
1442 //______________________________________________________________________________
1443 // Some decisions about two page view:
1445 // Both pages will be displayed at the same height, even if they were different physical/scanned
1446 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1447 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1448 // aspect ratio to determine the height.
1450 // The two page view div is resized to keep the middle of the book in the middle of the div
1451 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1452 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1453 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1454 $('#BRcontainer').empty();
1455 $('#BRcontainer').css('overflow', 'auto');
1457 // We want to display two facing pages. We may be missing
1458 // one side of the spread because it is the first/last leaf,
1459 // foldouts, missing pages, etc
1461 //var targetLeaf = this.displayedIndices[0];
1462 var targetLeaf = this.firstIndex;
1464 if (targetLeaf < this.firstDisplayableIndex()) {
1465 targetLeaf = this.firstDisplayableIndex();
1468 if (targetLeaf > this.lastDisplayableIndex()) {
1469 targetLeaf = this.lastDisplayableIndex();
1472 //this.twoPage.currentIndexL = null;
1473 //this.twoPage.currentIndexR = null;
1474 //this.pruneUnusedImgs();
1476 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1477 this.twoPage.currentIndexL = currentSpreadIndices[0];
1478 this.twoPage.currentIndexR = currentSpreadIndices[1];
1479 this.firstIndex = this.twoPage.currentIndexL;
1481 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1483 this.pruneUnusedImgs();
1484 this.prefetch(); // Preload images or reload if scaling has changed
1486 //console.dir(this.twoPage);
1488 // Add the two page view
1489 // $$$ Can we get everything set up and then append?
1490 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1492 // $$$ calculate first then set
1493 $('#BRtwopageview').css( {
1494 height: this.twoPage.totalHeight + 'px',
1495 width: this.twoPage.totalWidth + 'px',
1496 position: 'absolute'
1499 // If there will not be scrollbars (e.g. when zooming out) we center the book
1500 // since otherwise the book will be stuck off-center
1501 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1502 centerPercentageX = 0.5;
1504 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1505 centerPercentageY = 0.5;
1508 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1510 this.twoPage.coverDiv = document.createElement('div');
1511 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1512 border: '1px solid rgb(68, 25, 17)',
1513 width: this.twoPage.bookCoverDivWidth + 'px',
1514 height: this.twoPage.bookCoverDivHeight+'px',
1515 visibility: 'visible',
1516 position: 'absolute',
1517 backgroundColor: '#663929',
1518 left: this.twoPage.bookCoverDivLeft + 'px',
1519 top: this.twoPage.bookCoverDivTop+'px',
1520 MozBorderRadiusTopleft: '7px',
1521 MozBorderRadiusTopright: '7px',
1522 MozBorderRadiusBottomright: '7px',
1523 MozBorderRadiusBottomleft: '7px'
1524 }).appendTo('#BRtwopageview');
1526 this.leafEdgeR = document.createElement('div');
1527 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1528 $(this.leafEdgeR).css({
1529 borderStyle: 'solid solid solid none',
1530 borderColor: 'rgb(51, 51, 34)',
1531 borderWidth: '1px 1px 1px 0px',
1532 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1533 width: this.twoPage.leafEdgeWidthR + 'px',
1534 height: this.twoPage.height-1 + 'px',
1536 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1537 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1538 position: 'absolute'
1539 }).appendTo('#BRtwopageview');
1541 this.leafEdgeL = document.createElement('div');
1542 this.leafEdgeL.className = 'leafEdgeL';
1543 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1544 borderStyle: 'solid none solid solid',
1545 borderColor: 'rgb(51, 51, 34)',
1546 borderWidth: '1px 0px 1px 1px',
1547 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1548 width: this.twoPage.leafEdgeWidthL + 'px',
1549 height: this.twoPage.height-1 + 'px',
1550 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1551 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1552 position: 'absolute'
1553 }).appendTo('#BRtwopageview');
1555 div = document.createElement('div');
1556 $(div).attr('id', 'BRbookspine').css({
1557 border: '1px solid rgb(68, 25, 17)',
1558 width: this.twoPage.bookSpineDivWidth+'px',
1559 height: this.twoPage.bookSpineDivHeight+'px',
1560 position: 'absolute',
1561 backgroundColor: 'rgb(68, 25, 17)',
1562 left: this.twoPage.bookSpineDivLeft+'px',
1563 top: this.twoPage.bookSpineDivTop+'px'
1564 }).appendTo('#BRtwopageview');
1566 var self = this; // for closure
1568 /* Flip areas no longer used
1569 this.twoPage.leftFlipArea = document.createElement('div');
1570 this.twoPage.leftFlipArea.className = 'BRfliparea';
1571 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1573 width: this.twoPageFlipAreaWidth() + 'px',
1574 height: this.twoPageFlipAreaHeight() + 'px',
1575 position: 'absolute',
1576 left: this.twoPageLeftFlipAreaLeft() + 'px',
1577 top: this.twoPageFlipAreaTop() + 'px',
1580 }).bind('click', function(e) {
1582 }).bind('mousedown', function(e) {
1584 }).appendTo('#BRtwopageview');
1586 this.twoPage.rightFlipArea = document.createElement('div');
1587 this.twoPage.rightFlipArea.className = 'BRfliparea';
1588 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1590 width: this.twoPageFlipAreaWidth() + 'px',
1591 height: this.twoPageFlipAreaHeight() + 'px',
1592 position: 'absolute',
1593 left: this.twoPageRightFlipAreaLeft() + 'px',
1594 top: this.twoPageFlipAreaTop() + 'px',
1597 }).bind('click', function(e) {
1599 }).bind('mousedown', function(e) {
1601 }).appendTo('#BRtwopageview');
1604 this.prepareTwoPagePopUp();
1606 this.displayedIndices = [];
1608 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1609 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1611 this.drawLeafsTwoPage();
1612 this.updateToolbarZoom(this.reduce);
1616 this.removeSearchHilites();
1617 this.updateSearchHilites();
1621 // prepareTwoPagePopUp()
1623 // This function prepares the "View Page n" popup that shows while the mouse is
1624 // over the left/right "stack of sheets" edges. It also binds the mouse
1625 // events for these divs.
1626 //______________________________________________________________________________
1627 BookReader.prototype.prepareTwoPagePopUp = function() {
1629 this.twoPagePopUp = document.createElement('div');
1630 $(this.twoPagePopUp).css({
1631 border: '1px solid black',
1633 position: 'absolute',
1634 fontFamily: 'sans-serif',
1637 backgroundColor: 'rgb(255, 255, 238)',
1639 }).appendTo('#BRcontainer');
1640 $(this.twoPagePopUp).hide();
1642 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1643 $(e.data.twoPagePopUp).show();
1646 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1647 $(e.data.twoPagePopUp).hide();
1650 $(this.leafEdgeL).bind('click', this, function(e) {
1652 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1653 e.data.jumpToIndex(jumpIndex);
1656 $(this.leafEdgeR).bind('click', this, function(e) {
1658 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1659 e.data.jumpToIndex(jumpIndex);
1662 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1664 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1665 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1667 // $$$ TODO: Make sure popup is positioned so that it is in view
1668 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1669 $(e.data.twoPagePopUp).css({
1670 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1671 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1675 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1677 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1678 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1680 // $$$ TODO: Make sure popup is positioned so that it is in view
1681 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1682 $(e.data.twoPagePopUp).css({
1683 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1684 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1689 // calculateSpreadSize()
1690 //______________________________________________________________________________
1691 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1692 // this.twoPage.currentIndexR
1693 // This function sets this.twoPage.height, twoPage.width
1695 BookReader.prototype.calculateSpreadSize = function() {
1697 var firstIndex = this.twoPage.currentIndexL;
1698 var secondIndex = this.twoPage.currentIndexR;
1699 //console.log('first page is ' + firstIndex);
1701 // Calculate page sizes and total leaf width
1703 if ( this.twoPage.autofit) {
1704 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1706 // set based on reduction factor
1707 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1710 // Both pages together
1711 this.twoPage.height = spreadSize.height;
1712 this.twoPage.width = spreadSize.width;
1715 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1716 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1719 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1720 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1721 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1725 // The width of the book cover div. The combined width of both pages, twice the width
1726 // of the book cover internal padding (2*10) and the page edges
1727 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1728 // The height of the book cover div
1729 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1732 // We calculate the total width and height for the div so that we can make the book
1734 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1735 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1736 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1737 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1738 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1739 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1741 // We want to minimize the unused space in two-up mode (maximize the amount of page
1742 // shown). We give width to the leaf edges and these widths change (though the sum
1743 // of the two remains constant) as we flip through the book. With the book
1744 // cover centered and fixed in the BRcontainer div the page images will meet
1745 // at the "gutter" which is generally offset from the center.
1746 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1747 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1749 // The left edge of the book cover moves depending on the width of the pages
1750 // $$$ change to getter
1751 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1752 // The top edge of the book cover stays a fixed distance from the top
1753 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1756 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1757 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1758 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1761 this.reduce = spreadSize.reduce; // $$$ really set this here?
1764 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1767 // We check which page is closest to a "normal" page and use that to set the height
1768 // for both pages. This means that foldouts and other odd size pages will be displayed
1769 // smaller than the nominal zoom amount.
1770 var canon5Dratio = 1.5;
1773 height: this._getPageHeight(firstIndex),
1774 width: this._getPageWidth(firstIndex)
1778 height: this._getPageHeight(secondIndex),
1779 width: this._getPageWidth(secondIndex)
1782 var firstIndexRatio = first.height / first.width;
1783 var secondIndexRatio = second.height / second.width;
1784 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1787 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1788 ratio = firstIndexRatio;
1789 //console.log('using firstIndexRatio ' + ratio);
1791 ratio = secondIndexRatio;
1792 //console.log('using secondIndexRatio ' + ratio);
1795 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1796 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1797 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1799 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1800 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1802 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1803 ideal.width -= 10; // $$$ fudge factor
1804 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1805 ideal.height -= 20; // fudge factor
1806 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1808 if (ideal.height/ratio <= ideal.width) {
1810 ideal.width = parseInt(ideal.height/ratio);
1813 ideal.height = parseInt(ideal.width*ratio);
1816 // $$$ check this logic with large spreads
1817 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1822 // getSpreadSizeFromReduce()
1823 //______________________________________________________________________________
1824 // Returns the spread size calculated from the reduction factor for the given pages
1825 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1826 var spreadSize = {};
1827 // $$$ Scale this based on reduce?
1828 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1829 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1830 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1832 // $$$ Possibly incorrect -- we should make height "dominant"
1833 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1834 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1835 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1836 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1837 spreadSize.reduce = reduce;
1842 // twoPageGetAutofitReduce()
1843 //______________________________________________________________________________
1844 // Returns the current ideal reduction factor
1845 BookReader.prototype.twoPageGetAutofitReduce = function() {
1846 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1847 return spreadSize.reduce;
1850 // twoPageSetCursor()
1851 //______________________________________________________________________________
1852 // Set the cursor for two page view
1853 BookReader.prototype.twoPageSetCursor = function() {
1854 // console.log('setting cursor');
1855 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1856 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1857 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1858 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1860 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1861 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1866 //______________________________________________________________________________
1867 // Returns the currently active index.
1868 BookReader.prototype.currentIndex = function() {
1869 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1870 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1871 return this.firstIndex; // $$$ TODO page in center of view would be better
1872 } else if (this.mode == this.constMode2up) {
1873 // Only allow indices that are actually present in book
1874 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1876 throw 'currentIndex called for unimplemented mode ' + this.mode;
1880 // setCurrentIndex(index)
1881 //______________________________________________________________________________
1882 // Sets the idea of current index without triggering other actions such as animation.
1883 // Compare to jumpToIndex which animates to that index
1884 BookReader.prototype.setCurrentIndex = function(index) {
1885 this.firstIndex = index;
1890 //______________________________________________________________________________
1891 // Flip the right page over onto the left
1892 BookReader.prototype.right = function() {
1893 if ('rl' != this.pageProgression) {
1903 //______________________________________________________________________________
1904 // Flip to the rightmost page
1905 BookReader.prototype.rightmost = function() {
1906 if ('rl' != this.pageProgression) {
1914 //______________________________________________________________________________
1915 // Flip the left page over onto the right.
1916 BookReader.prototype.left = function() {
1917 if ('rl' != this.pageProgression) {
1927 //______________________________________________________________________________
1928 // Flip to the leftmost page
1929 BookReader.prototype.leftmost = function() {
1930 if ('rl' != this.pageProgression) {
1938 //______________________________________________________________________________
1939 BookReader.prototype.next = function() {
1940 if (2 == this.mode) {
1942 this.flipFwdToIndex(null);
1944 if (this.firstIndex < this.lastDisplayableIndex()) {
1945 this.jumpToIndex(this.firstIndex+1);
1951 //______________________________________________________________________________
1952 BookReader.prototype.prev = function() {
1953 if (2 == this.mode) {
1955 this.flipBackToIndex(null);
1957 if (this.firstIndex >= 1) {
1958 this.jumpToIndex(this.firstIndex-1);
1963 BookReader.prototype.first = function() {
1964 this.jumpToIndex(this.firstDisplayableIndex());
1967 BookReader.prototype.last = function() {
1968 this.jumpToIndex(this.lastDisplayableIndex());
1972 //______________________________________________________________________________
1973 // Scrolls down one screen view
1974 BookReader.prototype.scrollDown = function() {
1975 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1976 $('#BRcontainer').animate(
1977 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1978 450, 'easeInOutQuint'
1987 //______________________________________________________________________________
1988 // Scrolls up one screen view
1989 BookReader.prototype.scrollUp = function() {
1990 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1991 $('#BRcontainer').animate(
1992 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1993 450, 'easeInOutQuint'
2002 // flipBackToIndex()
2003 //______________________________________________________________________________
2004 // to flip back one spread, pass index=null
2005 BookReader.prototype.flipBackToIndex = function(index) {
2007 if (1 == this.mode) return;
2009 var leftIndex = this.twoPage.currentIndexL;
2011 if (this.animating) return;
2013 if (null != this.leafEdgeTmp) {
2014 alert('error: leafEdgeTmp should be null!');
2018 if (null == index) {
2019 index = leftIndex-2;
2021 //if (index<0) return;
2023 var previousIndices = this.getSpreadIndices(index);
2025 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
2029 this.animating = true;
2031 if ('rl' != this.pageProgression) {
2032 // Assume LTR and we are going backward
2033 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
2034 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
2036 // RTL and going backward
2037 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2038 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2042 // flipLeftToRight()
2043 //______________________________________________________________________________
2044 // Flips the page on the left towards the page on the right
2045 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2047 var leftLeaf = this.twoPage.currentIndexL;
2049 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2050 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2051 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2053 var currWidthL = this.getPageWidth2UP(leftLeaf);
2054 var newWidthL = this.getPageWidth2UP(newIndexL);
2055 var newWidthR = this.getPageWidth2UP(newIndexR);
2057 var top = this.twoPageTop();
2058 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2060 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2061 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2063 //animation strategy:
2064 // 0. remove search highlight, if any.
2065 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2066 // of the left leaf and where the user clicked in the leaf edge.
2067 // Note that if this function was triggered by left() and not a
2068 // mouse click, the width of leafEdgeTmp is very small (zero px).
2069 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2070 // leftLeaf to width=0.
2071 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2072 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2073 // its new full width.
2074 // 4. After step 3 is finished, do the following:
2075 // - remove leafEdgeTmp from the dom.
2076 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2077 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2078 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2079 // and width=newLeafEdgeWidthL.
2080 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2081 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2082 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2083 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2084 // - prefetch new adjacent leafs.
2085 // - set up click handlers for both new left and right leafs.
2086 // - redraw the search highlight.
2087 // - update the pagenum box and the url.
2090 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2092 this.leafEdgeTmp = document.createElement('div');
2093 $(this.leafEdgeTmp).css({
2094 borderStyle: 'solid none solid solid',
2095 borderColor: 'rgb(51, 51, 34)',
2096 borderWidth: '1px 0px 1px 1px',
2097 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2098 width: leafEdgeTmpW + 'px',
2099 height: this.twoPage.height-1 + 'px',
2100 left: leftEdgeTmpLeft + 'px',
2102 position: 'absolute',
2104 }).appendTo('#BRtwopageview');
2106 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2107 $(this.leafEdgeL).css({
2108 width: newLeafEdgeWidthL+'px',
2109 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2112 // Left gets the offset of the current left leaf from the document
2113 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2114 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2115 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2117 // We change the left leaf to right positioning
2118 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2119 $(this.prefetchedImgs[leftLeaf]).css({
2124 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2125 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2129 this.removeSearchHilites();
2131 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2132 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2134 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2135 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2137 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2138 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2139 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2141 $(self.leafEdgeR).css({
2142 // Moves the right leaf edge
2143 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2144 left: gutter+newWidthR+'px'
2147 $(self.leafEdgeL).css({
2148 // Moves and resizes the left leaf edge
2149 width: newLeafEdgeWidthL+'px',
2150 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2153 // Resizes the brown border div
2154 $(self.twoPage.coverDiv).css({
2155 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2156 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2159 $(self.leafEdgeTmp).remove();
2160 self.leafEdgeTmp = null;
2162 // $$$ TODO refactor with opposite direction flip
2164 self.twoPage.currentIndexL = newIndexL;
2165 self.twoPage.currentIndexR = newIndexR;
2166 self.twoPage.scaledWL = newWidthL;
2167 self.twoPage.scaledWR = newWidthR;
2168 self.twoPage.gutter = gutter;
2170 self.firstIndex = self.twoPage.currentIndexL;
2171 self.displayedIndices = [newIndexL, newIndexR];
2172 self.pruneUnusedImgs();
2174 self.animating = false;
2176 self.updateSearchHilites2UP();
2177 self.updatePageNumBox2UP();
2179 // self.twoPagePlaceFlipAreas(); // No longer used
2180 self.setMouseHandlers2UP();
2181 self.twoPageSetCursor();
2183 if (self.animationFinishedCallback) {
2184 self.animationFinishedCallback();
2185 self.animationFinishedCallback = null;
2193 //______________________________________________________________________________
2194 // Whether we flip left or right is dependent on the page progression
2195 // to flip forward one spread, pass index=null
2196 BookReader.prototype.flipFwdToIndex = function(index) {
2198 if (this.animating) return;
2200 if (null != this.leafEdgeTmp) {
2201 alert('error: leafEdgeTmp should be null!');
2205 if (null == index) {
2206 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2208 if (index > this.lastDisplayableIndex()) return;
2210 this.animating = true;
2212 var nextIndices = this.getSpreadIndices(index);
2214 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2216 if ('rl' != this.pageProgression) {
2217 // We did not specify RTL
2218 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2219 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2222 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2223 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2227 // flipRightToLeft(nextL, nextR, gutter)
2228 // $$$ better not to have to pass gutter in
2229 //______________________________________________________________________________
2230 // Flip from left to right and show the nextL and nextR indices on those sides
2231 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2232 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2233 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2234 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2235 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2237 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2239 var top = this.twoPageTop();
2240 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2242 var middle = this.twoPage.middle;
2243 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2245 this.leafEdgeTmp = document.createElement('div');
2246 $(this.leafEdgeTmp).css({
2247 borderStyle: 'solid none solid solid',
2248 borderColor: 'rgb(51, 51, 34)',
2249 borderWidth: '1px 0px 1px 1px',
2250 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2251 width: leafEdgeTmpW + 'px',
2252 height: this.twoPage.height-1 + 'px',
2253 left: gutter+scaledW+'px',
2255 position: 'absolute',
2257 }).appendTo('#BRtwopageview');
2259 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2260 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2262 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2263 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2264 var newWidthL = this.getPageWidth2UP(newIndexL);
2265 var newWidthR = this.getPageWidth2UP(newIndexR);
2267 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2269 var self = this; // closure-tastic!
2271 var speed = this.flipSpeed;
2273 this.removeSearchHilites();
2275 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2276 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2277 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2278 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2279 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2281 $(self.leafEdgeL).css({
2282 width: newLeafEdgeWidthL+'px',
2283 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2286 // Resizes the book cover
2287 $(self.twoPage.coverDiv).css({
2288 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2289 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2292 $(self.leafEdgeTmp).remove();
2293 self.leafEdgeTmp = null;
2295 self.twoPage.currentIndexL = newIndexL;
2296 self.twoPage.currentIndexR = newIndexR;
2297 self.twoPage.scaledWL = newWidthL;
2298 self.twoPage.scaledWR = newWidthR;
2299 self.twoPage.gutter = gutter;
2301 self.firstIndex = self.twoPage.currentIndexL;
2302 self.displayedIndices = [newIndexL, newIndexR];
2303 self.pruneUnusedImgs();
2305 self.animating = false;
2308 self.updateSearchHilites2UP();
2309 self.updatePageNumBox2UP();
2311 // self.twoPagePlaceFlipAreas(); // No longer used
2312 self.setMouseHandlers2UP();
2313 self.twoPageSetCursor();
2315 if (self.animationFinishedCallback) {
2316 self.animationFinishedCallback();
2317 self.animationFinishedCallback = null;
2323 // setMouseHandlers2UP
2324 //______________________________________________________________________________
2325 BookReader.prototype.setMouseHandlers2UP = function() {
2327 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2332 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2339 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2340 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2347 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2348 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2351 e.data.self.right();
2357 //______________________________________________________________________________
2358 BookReader.prototype.prefetchImg = function(index) {
2359 var pageURI = this._getPageURI(index);
2361 // Load image if not loaded or URI has changed (e.g. due to scaling)
2362 var loadImage = false;
2363 if (undefined == this.prefetchedImgs[index]) {
2364 //console.log('no image for ' + index);
2366 } else if (pageURI != this.prefetchedImgs[index].uri) {
2367 //console.log('uri changed for ' + index);
2372 //console.log('prefetching ' + index);
2373 var img = document.createElement("img");
2375 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2376 this.prefetchedImgs[index] = img;
2381 // prepareFlipLeftToRight()
2383 //______________________________________________________________________________
2385 // Prepare to flip the left page towards the right. This corresponds to moving
2386 // backward when the page progression is left to right.
2387 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2389 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2391 this.prefetchImg(prevL);
2392 this.prefetchImg(prevR);
2394 var height = this._getPageHeight(prevL);
2395 var width = this._getPageWidth(prevL);
2396 var middle = this.twoPage.middle;
2397 var top = this.twoPageTop();
2398 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2400 // The gutter is the dividing line between the left and right pages.
2401 // It is offset from the middle to create the illusion of thickness to the pages
2402 var gutter = middle + this.gutterOffsetForIndex(prevL);
2404 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2405 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2406 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2409 position: 'absolute',
2410 left: gutter-scaledW+'px',
2411 right: '', // clear right property
2413 height: this.twoPage.height,
2414 width: scaledW+'px',
2415 backgroundColor: this.getPageBackgroundColor(prevL),
2416 borderRight: '1px solid black',
2420 $(this.prefetchedImgs[prevL]).css(leftCSS);
2422 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2424 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2427 position: 'absolute',
2431 height: this.twoPage.height,
2433 backgroundColor: this.getPageBackgroundColor(prevR),
2434 borderLeft: '1px solid black',
2438 $(this.prefetchedImgs[prevR]).css(rightCSS);
2440 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2444 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2445 // prepareFlipRightToLeft()
2446 //______________________________________________________________________________
2447 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2449 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2452 this.prefetchImg(nextL);
2453 this.prefetchImg(nextR);
2455 var height = this._getPageHeight(nextR);
2456 var width = this._getPageWidth(nextR);
2457 var middle = this.twoPage.middle;
2458 var top = this.twoPageTop();
2459 var scaledW = this.twoPage.height*width/height;
2461 var gutter = middle + this.gutterOffsetForIndex(nextL);
2463 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2464 $(this.prefetchedImgs[nextR]).css({
2465 position: 'absolute',
2468 backgroundColor: this.getPageBackgroundColor(nextR),
2469 height: this.twoPage.height,
2470 width: scaledW+'px',
2471 borderLeft: '1px solid black',
2475 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2477 height = this._getPageHeight(nextL);
2478 width = this._getPageWidth(nextL);
2479 scaledW = this.twoPage.height*width/height;
2481 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2482 $(this.prefetchedImgs[nextL]).css({
2483 position: 'absolute',
2484 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2486 backgroundColor: this.getPageBackgroundColor(nextL),
2487 height: this.twoPage.height,
2488 width: 0+'px', // Start at 0 width, then grow to the left
2489 borderRight: '1px solid black',
2493 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2497 // getNextLeafs() -- NOT RTL AWARE
2498 //______________________________________________________________________________
2499 // BookReader.prototype.getNextLeafs = function(o) {
2500 // //TODO: we might have two left or two right leafs in a row (damaged book)
2501 // //For now, assume that leafs are contiguous.
2503 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2504 // o.L = this.twoPage.currentIndexL+2;
2505 // o.R = this.twoPage.currentIndexL+3;
2508 // getprevLeafs() -- NOT RTL AWARE
2509 //______________________________________________________________________________
2510 // BookReader.prototype.getPrevLeafs = function(o) {
2511 // //TODO: we might have two left or two right leafs in a row (damaged book)
2512 // //For now, assume that leafs are contiguous.
2514 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2515 // o.L = this.twoPage.currentIndexL-2;
2516 // o.R = this.twoPage.currentIndexL-1;
2519 // pruneUnusedImgs()
2520 //______________________________________________________________________________
2521 BookReader.prototype.pruneUnusedImgs = function() {
2522 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2523 for (var key in this.prefetchedImgs) {
2524 //console.log('key is ' + key);
2525 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2526 //console.log('removing key '+ key);
2527 $(this.prefetchedImgs[key]).remove();
2529 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2530 //console.log('deleting key '+ key);
2531 delete this.prefetchedImgs[key];
2537 //______________________________________________________________________________
2538 BookReader.prototype.prefetch = function() {
2540 // $$$ We should check here if the current indices have finished
2541 // loading (with some timeout) before loading more page images
2542 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2544 // prefetch visible pages first
2545 this.prefetchImg(this.twoPage.currentIndexL);
2546 this.prefetchImg(this.twoPage.currentIndexR);
2548 var adjacentPagesToLoad = 3;
2550 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2551 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2553 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2554 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2556 // Load images spreading out from current
2557 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2558 var goingDown = lowCurrent - i;
2559 if (goingDown >= start) {
2560 this.prefetchImg(goingDown);
2562 var goingUp = highCurrent + i;
2563 if (goingUp <= end) {
2564 this.prefetchImg(goingUp);
2569 var lim = this.twoPage.currentIndexL-4;
2571 lim = Math.max(lim, 0);
2572 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2573 this.prefetchImg(i);
2576 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2577 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2578 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2579 this.prefetchImg(i);
2585 // getPageWidth2UP()
2586 //______________________________________________________________________________
2587 BookReader.prototype.getPageWidth2UP = function(index) {
2588 // We return the width based on the dominant height
2589 var height = this._getPageHeight(index);
2590 var width = this._getPageWidth(index);
2591 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2595 //______________________________________________________________________________
2596 BookReader.prototype.search = function(term) {
2597 term = term.replace(/\//g, ' '); // strip slashes
2598 this.searchTerm = term;
2599 $('#BookReaderSearchScript').remove();
2600 var script = document.createElement("script");
2601 script.setAttribute('id', 'BookReaderSearchScript');
2602 script.setAttribute("type", "text/javascript");
2603 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2604 document.getElementsByTagName('head')[0].appendChild(script);
2605 $('#BookReaderSearchBox').val(term);
2606 $('#BookReaderSearchResults').html('Searching...');
2609 // BRSearchCallback()
2610 //______________________________________________________________________________
2611 BookReader.prototype.BRSearchCallback = function(txt) {
2613 if (jQuery.browser.msie) {
2614 var dom=new ActiveXObject("Microsoft.XMLDOM");
2618 var parser = new DOMParser();
2619 var dom = parser.parseFromString(txt, "text/xml");
2622 $('#BookReaderSearchResults').empty();
2623 $('#BookReaderSearchResults').append('<ul>');
2625 for (var key in this.searchResults) {
2626 if (null != this.searchResults[key].div) {
2627 $(this.searchResults[key].div).remove();
2629 delete this.searchResults[key];
2632 var pages = dom.getElementsByTagName('PAGE');
2634 if (0 == pages.length) {
2635 // $$$ it would be nice to echo the (sanitized) search result here
2636 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2638 for (var i = 0; i < pages.length; i++){
2639 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2642 var re = new RegExp (/_(\d{4})\.djvu/);
2643 var reMatch = re.exec(pages[i].getAttribute('file'));
2644 var index = parseInt(reMatch[1], 10);
2645 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2647 var children = pages[i].childNodes;
2649 for (var j=0; j<children.length; j++) {
2650 //console.log(j + ' - ' + children[j].nodeName);
2651 //console.log(children[j].firstChild.nodeValue);
2652 if ('CONTEXT' == children[j].nodeName) {
2653 context += children[j].firstChild.nodeValue;
2654 } else if ('WORD' == children[j].nodeName) {
2655 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2657 var index = this.leafNumToIndex(index);
2658 if (null != index) {
2659 //coordinates are [left, bottom, right, top, [baseline]]
2660 //we'll skip baseline for now...
2661 var coords = children[j].getAttribute('coords').split(',',4);
2662 if (4 == coords.length) {
2663 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2668 var pageName = this.getPageName(index);
2669 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2670 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2671 //TODO: remove hardcoded instance name
2672 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2675 $('#BookReaderSearchResults').append('</ul>');
2677 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2678 $('#BookReaderSearchBox').val(this.searchTerm);
2680 this.updateSearchHilites();
2683 // updateSearchHilites()
2684 //______________________________________________________________________________
2685 BookReader.prototype.updateSearchHilites = function() {
2686 if (2 == this.mode) {
2687 this.updateSearchHilites2UP();
2689 this.updateSearchHilites1UP();
2693 // showSearchHilites1UP()
2694 //______________________________________________________________________________
2695 BookReader.prototype.updateSearchHilites1UP = function() {
2697 for (var key in this.searchResults) {
2699 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2700 var result = this.searchResults[key];
2701 if (null == result.div) {
2702 result.div = document.createElement('div');
2703 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2704 //console.log('appending ' + key);
2707 width: (result.r-result.l)/this.reduce + 'px',
2708 height: (result.b-result.t)/this.reduce + 'px',
2709 left: (result.l)/this.reduce + 'px',
2710 top: (result.t)/this.reduce +'px'
2714 //console.log(key + ' not displayed');
2715 this.searchResults[key].div=null;
2721 //______________________________________________________________________________
2722 // Returns the position of the gutter (line between the page images)
2723 BookReader.prototype.twoPageGutter = function() {
2724 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2728 //______________________________________________________________________________
2729 // Returns the offset for the top of the page images
2730 BookReader.prototype.twoPageTop = function() {
2731 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2734 // twoPageCoverWidth()
2735 //______________________________________________________________________________
2736 // Returns the width of the cover div given the total page width
2737 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2738 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2741 // twoPageGetViewCenter()
2742 //______________________________________________________________________________
2743 // Returns the percentage offset into twopageview div at the center of container div
2744 // { percentageX: float, percentageY: float }
2745 BookReader.prototype.twoPageGetViewCenter = function() {
2748 var containerOffset = $('#BRcontainer').offset();
2749 var viewOffset = $('#BRtwopageview').offset();
2750 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2751 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2756 // twoPageCenterView(percentageX, percentageY)
2757 //______________________________________________________________________________
2758 // Centers the point given by percentage from left,top of twopageview
2759 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2760 if ('undefined' == typeof(percentageX)) {
2763 if ('undefined' == typeof(percentageY)) {
2767 var viewWidth = $('#BRtwopageview').width();
2768 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2769 var intoViewX = percentageX * viewWidth;
2771 var viewHeight = $('#BRtwopageview').height();
2772 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2773 var intoViewY = percentageY * viewHeight;
2775 if (viewWidth < containerClientWidth) {
2776 // Can fit width without scrollbars - center by adjusting offset
2777 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2779 // Need to scroll to center
2780 $('#BRtwopageview').css('left', 0);
2781 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2784 if (viewHeight < containerClientHeight) {
2785 // Fits with scrollbars - add offset
2786 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2788 $('#BRtwopageview').css('top', 0);
2789 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2793 // twoPageFlipAreaHeight
2794 //______________________________________________________________________________
2795 // Returns the integer height of the click-to-flip areas at the edges of the book
2796 BookReader.prototype.twoPageFlipAreaHeight = function() {
2797 return parseInt(this.twoPage.height);
2800 // twoPageFlipAreaWidth
2801 //______________________________________________________________________________
2802 // Returns the integer width of the flip areas
2803 BookReader.prototype.twoPageFlipAreaWidth = function() {
2804 var max = 100; // $$$ TODO base on view width?
2807 var width = this.twoPage.width * 0.15;
2808 return parseInt(BookReader.util.clamp(width, min, max));
2811 // twoPageFlipAreaTop
2812 //______________________________________________________________________________
2813 // Returns integer top offset for flip areas
2814 BookReader.prototype.twoPageFlipAreaTop = function() {
2815 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2818 // twoPageLeftFlipAreaLeft
2819 //______________________________________________________________________________
2820 // Left offset for left flip area
2821 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2822 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2825 // twoPageRightFlipAreaLeft
2826 //______________________________________________________________________________
2827 // Left offset for right flip area
2828 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2829 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2832 // twoPagePlaceFlipAreas
2833 //______________________________________________________________________________
2834 // Readjusts position of flip areas based on current layout
2835 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2836 // We don't set top since it shouldn't change relative to view
2837 $(this.twoPage.leftFlipArea).css({
2838 left: this.twoPageLeftFlipAreaLeft() + 'px',
2839 width: this.twoPageFlipAreaWidth() + 'px'
2841 $(this.twoPage.rightFlipArea).css({
2842 left: this.twoPageRightFlipAreaLeft() + 'px',
2843 width: this.twoPageFlipAreaWidth() + 'px'
2847 // showSearchHilites2UP()
2848 //______________________________________________________________________________
2849 BookReader.prototype.updateSearchHilites2UP = function() {
2851 for (var key in this.searchResults) {
2852 key = parseInt(key, 10);
2853 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2854 var result = this.searchResults[key];
2855 if (null == result.div) {
2856 result.div = document.createElement('div');
2857 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2858 //console.log('appending ' + key);
2861 // We calculate the reduction factor for the specific page because it can be different
2862 // for each page in the spread
2863 var height = this._getPageHeight(key);
2864 var width = this._getPageWidth(key)
2865 var reduce = this.twoPage.height/height;
2866 var scaledW = parseInt(width*reduce);
2868 var gutter = this.twoPageGutter();
2870 if ('L' == this.getPageSide(key)) {
2871 pageL = gutter-scaledW;
2875 var pageT = this.twoPageTop();
2878 width: (result.r-result.l)*reduce + 'px',
2879 height: (result.b-result.t)*reduce + 'px',
2880 left: pageL+(result.l)*reduce + 'px',
2881 top: pageT+(result.t)*reduce +'px'
2885 //console.log(key + ' not displayed');
2886 if (null != this.searchResults[key].div) {
2887 //console.log('removing ' + key);
2888 $(this.searchResults[key].div).remove();
2890 this.searchResults[key].div=null;
2895 // removeSearchHilites()
2896 //______________________________________________________________________________
2897 BookReader.prototype.removeSearchHilites = function() {
2898 for (var key in this.searchResults) {
2899 if (null != this.searchResults[key].div) {
2900 $(this.searchResults[key].div).remove();
2901 this.searchResults[key].div=null;
2907 //______________________________________________________________________________
2908 BookReader.prototype.printPage = function() {
2909 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2911 /* iframe implementation
2913 if (null != this.printPopup) { // check if already showing
2916 this.printPopup = document.createElement("div");
2917 $(this.printPopup).css({
2918 position: 'absolute',
2920 left: ($('#BRcontainer').width()-400)/2 + 'px',
2923 border: "3px double #999999",
2925 backgroundColor: "#fff"
2926 }).appendTo('#BookReader');
2929 if (this.constMode1up == this.mode) {
2930 indexToPrint = this.firstIndex;
2932 indexToPrint = this.twoPage.currentIndexL;
2935 this.indexToPrint = indexToPrint;
2937 var htmlStr = '<div style="text-align: center;">';
2938 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2939 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2940 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2941 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2942 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2943 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2945 htmlStr += '</div>';
2946 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2947 htmlStr += '</div>';
2949 this.printPopup.innerHTML = htmlStr;
2951 var iframe = document.createElement('iframe');
2952 iframe.id = 'printFrame';
2953 iframe.name = 'printFrame';
2954 iframe.width = '233px'; // 8.5 x 11 aspect
2955 iframe.height = '300px';
2957 var self = this; // closure
2959 $(iframe).load(function() {
2960 var doc = BookReader.util.getIFrameDocument(this);
2961 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2964 $('#printDiv').prepend(iframe);
2968 // Get print URI from current indices and mode
2969 BookReader.prototype.getPrintURI = function() {
2971 if (this.constMode2up == this.mode) {
2972 indexToPrint = this.twoPage.currentIndexL;
2974 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2977 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2978 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2979 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2981 if (this.constMode2up == this.mode) {
2982 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2983 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2984 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2986 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2989 return '/bookreader/print.php?' + options;
2992 /* iframe implementation
2993 BookReader.prototype.getPrintFrameContent = function(index) {
2994 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2995 // 8.5x11 so we should end up not overflowing on either paper size.
2996 var paperAspect = 8.5 / 11;
2997 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
3001 // Rotate if possible and appropriate, to get larger image size on printed page
3002 if (this.canRotatePage(index)) {
3003 if (imageAspect > 1 && imageAspect > paperAspect) {
3004 // more wide than square, and more wide than paper
3006 imageAspect = 1/imageAspect;
3011 if (imageAspect > paperAspect) {
3012 // wider than paper, fit width
3013 fitAttrs = 'width="95%"';
3015 // taller than paper, fit height
3016 fitAttrs = 'height="95%"';
3019 var imageURL = this._getPageURI(index, 1, rotate);
3020 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
3021 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
3022 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
3023 iframeStr += '</div>';
3024 iframeStr += '</body></html>';
3029 BookReader.prototype.updatePrintFrame = function(delta) {
3030 var newIndex = this.indexToPrint + delta;
3031 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
3032 if (newIndex == this.indexToPrint) {
3035 this.indexToPrint = newIndex;
3036 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
3037 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
3042 //______________________________________________________________________________
3043 BookReader.prototype.showEmbedCode = function() {
3044 if (null != this.embedPopup) { // check if already showing
3048 this.embedPopup = document.createElement("div");
3049 $(this.embedPopup).css({
3050 position: 'absolute',
3052 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
3055 border: "3px double #999999",
3057 backgroundColor: "#fff"
3058 }).appendTo('#BookReader');
3060 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
3061 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>';
3062 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
3063 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
3065 this.embedPopup.innerHTML = htmlStr;
3066 $(this.embedPopup).find('input').bind('click', function() {
3072 //______________________________________________________________________________
3073 BookReader.prototype.autoToggle = function() {
3075 var bComingFrom1up = false;
3076 if (2 != this.mode) {
3077 bComingFrom1up = true;
3081 // Change to autofit if book is too large
3082 if (this.reduce < this.twoPageGetAutofitReduce()) {
3087 if (null == this.autoTimer) {
3088 this.flipSpeed = 2000;
3090 // $$$ Draw events currently cause layout problems when they occur during animation.
3091 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3092 // we workaround for now by not triggering immediate animation in that case.
3093 // See https://bugs.launchpad.net/gnubook/+bug/328327
3094 if (('rl' == this.pageProgression) && bComingFrom1up) {
3095 // don't flip immediately -- wait until timer fires
3098 this.flipFwdToIndex();
3101 $('#BRtoolbar .play').hide();
3102 $('#BRtoolbar .pause').show();
3103 this.autoTimer=setInterval(function(){
3104 if (self.animating) {return;}
3106 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3107 self.flipBackToIndex(1); // $$$ really what we want?
3109 self.flipFwdToIndex();
3118 //______________________________________________________________________________
3119 // Stop autoplay mode, allowing animations to finish
3120 BookReader.prototype.autoStop = function() {
3121 if (null != this.autoTimer) {
3122 clearInterval(this.autoTimer);
3123 this.flipSpeed = 'fast';
3124 $('#BRtoolbar .pause').hide();
3125 $('#BRtoolbar .play').show();
3126 this.autoTimer = null;
3130 // stopFlipAnimations
3131 //______________________________________________________________________________
3132 // Immediately stop flip animations. Callbacks are triggered.
3133 BookReader.prototype.stopFlipAnimations = function() {
3135 this.autoStop(); // Clear timers
3137 // Stop animation, clear queue, trigger callbacks
3138 if (this.leafEdgeTmp) {
3139 $(this.leafEdgeTmp).stop(false, true);
3141 jQuery.each(this.prefetchedImgs, function() {
3142 $(this).stop(false, true);
3145 // And again since animations also queued in callbacks
3146 if (this.leafEdgeTmp) {
3147 $(this.leafEdgeTmp).stop(false, true);
3149 jQuery.each(this.prefetchedImgs, function() {
3150 $(this).stop(false, true);
3155 // keyboardNavigationIsDisabled(event)
3156 // - returns true if keyboard navigation should be disabled for the event
3157 //______________________________________________________________________________
3158 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3159 if (event.target.tagName == "INPUT") {
3165 // gutterOffsetForIndex
3166 //______________________________________________________________________________
3168 // Returns the gutter offset for the spread containing the given index.
3169 // This function supports RTL
3170 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3172 // To find the offset of the gutter from the middle we calculate our percentage distance
3173 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3174 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3176 // But then again for RTL it's the opposite
3177 if ('rl' == this.pageProgression) {
3185 //______________________________________________________________________________
3186 // Returns the width of the leaf edge div for the page with index given
3187 BookReader.prototype.leafEdgeWidth = function(pindex) {
3188 // $$$ could there be single pixel rounding errors for L vs R?
3189 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3190 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3192 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3196 // jumpIndexForLeftEdgePageX
3197 //______________________________________________________________________________
3198 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3199 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3200 if ('rl' != this.pageProgression) {
3201 // LTR - flipping backward
3202 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3204 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3205 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3209 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3210 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3215 // jumpIndexForRightEdgePageX
3216 //______________________________________________________________________________
3217 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3218 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3219 if ('rl' != this.pageProgression) {
3221 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3222 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3225 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3226 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3231 BookReader.prototype.initToolbar = function(mode, ui) {
3233 $("#BookReader").append("<div id='BRtoolbar'>"
3234 + "<span id='BRtoolbarbuttons' style='float: right'>"
3235 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3236 + "<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>"
3237 + "<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>"
3238 + "<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>"
3239 + "<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>"
3240 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3244 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3245 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3246 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3247 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3248 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3249 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3250 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3253 + "<span id='#BRbooktitle'>"
3254 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3258 this.updateToolbarZoom(this.reduce); // Pretty format
3260 if (ui == "embed") {
3261 $("#BookReader a.logo").attr("target","_blank");
3264 // $$$ turn this into a member variable
3265 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3267 // We build in mode 2
3270 this.bindToolbarNavHandlers(jToolbar);
3272 // Setup tooltips -- later we could load these from a file for i18n
3273 var titles = { '.logo': 'Go to Archive.org',
3274 '.zoom_in': 'Zoom in',
3275 '.zoom_out': 'Zoom out',
3276 '.one_page_mode': 'One-page view',
3277 '.two_page_mode': 'Two-page view',
3278 '.thumbnail_mode': 'Thumbnail view',
3279 '.print': 'Print this page',
3280 '.embed': 'Embed bookreader',
3281 '.book_left': 'Flip left',
3282 '.book_right': 'Flip right',
3283 '.book_up': 'Page up',
3284 '.book_down': 'Page down',
3287 '.book_top': 'First page',
3288 '.book_bottom': 'Last page'
3290 if ('rl' == this.pageProgression) {
3291 titles['.book_leftmost'] = 'Last page';
3292 titles['.book_rightmost'] = 'First page';
3294 titles['.book_leftmost'] = 'First page';
3295 titles['.book_rightmost'] = 'Last page';
3298 for (var icon in titles) {
3299 jToolbar.find(icon).attr('title', titles[icon]);
3302 // Hide mode buttons and autoplay if 2up is not available
3303 // $$$ if we end up with more than two modes we should show the applicable buttons
3304 if ( !this.canSwitchToMode(this.constMode2up) ) {
3305 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3308 // Switch to requested mode -- binds other click handlers
3309 this.switchToolbarMode(mode);
3314 // switchToolbarMode
3315 //______________________________________________________________________________
3316 // Update the toolbar for the given mode (changes navigation buttons)
3317 // $$$ we should soon split the toolbar out into its own module
3318 BookReader.prototype.switchToolbarMode = function(mode) {
3321 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3322 $('#BRtoolbar .BRtoolbarmode2').hide();
3323 $('#BRtoolbar .BRtoolbarmode3').hide();
3324 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3325 } else if (2 == mode) {
3327 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3328 $('#BRtoolbar .BRtoolbarmode1').hide();
3329 $('#BRtoolbar .BRtoolbarmode3').hide();
3330 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3333 $('#BRtoolbar .BRtoolbarzoom').hide();
3334 $('#BRtoolbar .BRtoolbarmode2').hide();
3335 $('#BRtoolbar .BRtoolbarmode1').hide();
3336 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3340 // bindToolbarNavHandlers
3341 //______________________________________________________________________________
3342 // Binds the toolbar handlers
3343 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3345 var self = this; // closure
3347 jToolbar.find('.book_left').bind('click', function(e) {
3352 jToolbar.find('.book_right').bind('click', function(e) {
3357 jToolbar.find('.book_up').bind('click', function(e) {
3358 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3366 jToolbar.find('.book_down').bind('click', function(e) {
3367 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3375 jToolbar.find('.print').bind('click', function(e) {
3380 jToolbar.find('.embed').bind('click', function(e) {
3381 self.showEmbedCode();
3385 jToolbar.find('.play').bind('click', function(e) {
3390 jToolbar.find('.pause').bind('click', function(e) {
3395 jToolbar.find('.book_top').bind('click', function(e) {
3400 jToolbar.find('.book_bottom').bind('click', function(e) {
3405 jToolbar.find('.book_leftmost').bind('click', function(e) {
3410 jToolbar.find('.book_rightmost').bind('click', function(e) {
3416 // updateToolbarZoom(reduce)
3417 //______________________________________________________________________________
3418 // Update the displayed zoom factor based on reduction factor
3419 BookReader.prototype.updateToolbarZoom = function(reduce) {
3421 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3424 value = (100 / reduce).toFixed(2);
3425 // Strip trailing zeroes and decimal if all zeroes
3426 value = value.replace(/0+$/,'');
3427 value = value.replace(/\.$/,'');
3430 $('#BRzoom').text(value);
3433 // firstDisplayableIndex
3434 //______________________________________________________________________________
3435 // Returns the index of the first visible page, dependent on the mode.
3436 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3437 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3438 BookReader.prototype.firstDisplayableIndex = function() {
3439 if (this.mode != this.constMode2up) {
3443 if ('rl' != this.pageProgression) {
3445 if (this.getPageSide(0) == 'L') {
3452 if (this.getPageSide(0) == 'R') {
3460 // lastDisplayableIndex
3461 //______________________________________________________________________________
3462 // Returns the index of the last visible page, dependent on the mode.
3463 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3464 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3465 BookReader.prototype.lastDisplayableIndex = function() {
3467 var lastIndex = this.numLeafs - 1;
3469 if (this.mode != this.constMode2up) {
3473 if ('rl' != this.pageProgression) {
3475 if (this.getPageSide(lastIndex) == 'R') {
3478 return lastIndex + 1;
3482 if (this.getPageSide(lastIndex) == 'L') {
3485 return lastIndex + 1;
3490 // shortTitle(maximumCharacters)
3492 // Returns a shortened version of the title with the maximum number of characters
3493 BookReader.prototype.shortTitle = function(maximumCharacters) {
3494 if (this.bookTitle.length < maximumCharacters) {
3495 return this.bookTitle;
3498 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3503 // Parameter related functions
3505 // updateFromParams(params)
3507 // Update ourselves from the params object.
3509 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3510 BookReader.prototype.updateFromParams = function(params) {
3511 if ('undefined' != typeof(params.mode)) {
3512 this.switchMode(params.mode);
3516 if ('undefined' != typeof(params.searchTerm)) {
3517 if (this.searchTerm != params.searchTerm) {
3518 this.search(params.searchTerm);
3522 // $$$ process /zoom
3524 // We only respect page if index is not set
3525 if ('undefined' != typeof(params.index)) {
3526 if (params.index != this.currentIndex()) {
3527 this.jumpToIndex(params.index);
3529 } else if ('undefined' != typeof(params.page)) {
3530 // $$$ this assumes page numbers are unique
3531 if (params.page != this.getPageNum(this.currentIndex())) {
3532 this.jumpToPage(params.page);
3536 // $$$ process /region
3537 // $$$ process /highlight
3540 // paramsFromFragment(urlFragment)
3542 // Returns a object with configuration parametes from a URL fragment.
3544 // E.g paramsFromFragment(window.location.hash)
3545 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3546 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3550 // For convenience we allow an initial # character (as from window.location.hash)
3551 // but don't require it
3552 if (urlFragment.substr(0,1) == '#') {
3553 urlFragment = urlFragment.substr(1);
3556 // Simple #nn syntax
3557 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3558 if ( !isNaN(oldStyleLeafNum) ) {
3559 params.index = oldStyleLeafNum;
3561 // Done processing if using old-style syntax
3565 // Split into key-value pairs
3566 var urlArray = urlFragment.split('/');
3568 for (var i = 0; i < urlArray.length; i += 2) {
3569 urlHash[urlArray[i]] = urlArray[i+1];
3573 if ('1up' == urlHash['mode']) {
3574 params.mode = this.constMode1up;
3575 } else if ('2up' == urlHash['mode']) {
3576 params.mode = this.constMode2up;
3577 } else if ('thumb' == urlHash['mode']) {
3578 params.mode = this.constModeThumb;
3582 if ('undefined' != typeof(urlHash['page'])) {
3583 // page was set -- may not be int
3584 params.page = urlHash['page'];
3587 // $$$ process /region
3588 // $$$ process /search
3590 if (urlHash['search'] != undefined) {
3591 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3594 // $$$ process /highlight
3599 // paramsFromCurrent()
3601 // Create a params object from the current parameters.
3602 BookReader.prototype.paramsFromCurrent = function() {
3606 var index = this.currentIndex();
3607 var pageNum = this.getPageNum(index);
3608 if ((pageNum === 0) || pageNum) {
3609 params.page = pageNum;
3612 params.index = index;
3613 params.mode = this.mode;
3619 if (this.searchHighlightVisible()) {
3620 params.searchTerm = this.searchTerm;
3626 // fragmentFromParams(params)
3628 // Create a fragment string from the params object.
3629 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3630 BookReader.prototype.fragmentFromParams = function(params) {
3631 var separator = '/';
3635 if ('undefined' != typeof(params.page)) {
3636 fragments.push('page', params.page);
3638 // Don't have page numbering -- use index instead
3639 fragments.push('page', 'n' + params.index);
3646 if ('undefined' != typeof(params.mode)) {
3647 if (params.mode == this.constMode1up) {
3648 fragments.push('mode', '1up');
3649 } else if (params.mode == this.constMode2up) {
3650 fragments.push('mode', '2up');
3651 } else if (params.mode == this.constModeThumb) {
3652 fragments.push('mode', 'thumb');
3654 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3659 if (params.searchTerm) {
3660 fragments.push('search', params.searchTerm);
3663 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3666 // getPageIndex(pageNum)
3668 // Returns the *highest* index the given page number, or undefined
3669 BookReader.prototype.getPageIndex = function(pageNum) {
3670 var pageIndices = this.getPageIndices(pageNum);
3672 if (pageIndices.length > 0) {
3673 return pageIndices[pageIndices.length - 1];
3679 // getPageIndices(pageNum)
3681 // Returns an array (possibly empty) of the indices with the given page number
3682 BookReader.prototype.getPageIndices = function(pageNum) {
3685 // Check for special "nXX" page number
3686 if (pageNum.slice(0,1) == 'n') {
3688 var pageIntStr = pageNum.slice(1, pageNum.length);
3689 var pageIndex = parseInt(pageIntStr);
3690 indices.push(pageIndex);
3693 // Do nothing... will run through page names and see if one matches
3698 for (i=0; i<this.numLeafs; i++) {
3699 if (this.getPageNum(i) == pageNum) {
3707 // getPageName(index)
3709 // Returns the name of the page as it should be displayed in the user interface
3710 BookReader.prototype.getPageName = function(index) {
3711 return 'Page ' + this.getPageNum(index);
3714 // updateLocationHash
3716 // Update the location hash from the current parameters. Call this instead of manually
3717 // using window.location.replace
3718 BookReader.prototype.updateLocationHash = function() {
3719 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3720 window.location.replace(newHash);
3722 // This is the variable checked in the timer. Only user-generated changes
3723 // to the URL will trigger the event.
3724 this.oldLocationHash = newHash;
3727 // startLocationPolling
3729 // Starts polling of window.location to see hash fragment changes
3730 BookReader.prototype.startLocationPolling = function() {
3731 var self = this; // remember who I am
3732 self.oldLocationHash = window.location.hash;
3734 if (this.locationPollId) {
3735 clearInterval(this.locationPollID);
3736 this.locationPollId = null;
3739 this.locationPollId = setInterval(function() {
3740 var newHash = window.location.hash;
3741 if (newHash != self.oldLocationHash) {
3742 if (newHash != self.oldUserHash) { // Only process new user hash once
3743 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3745 // Queue change if animating
3746 if (self.animating) {
3748 self.animationFinishedCallback = function() {
3749 self.updateFromParams(self.paramsFromFragment(newHash));
3751 } else { // update immediately
3752 self.updateFromParams(self.paramsFromFragment(newHash));
3754 self.oldUserHash = newHash;
3762 // Returns true if we can switch to the requested mode
3763 BookReader.prototype.canSwitchToMode = function(mode) {
3764 if (mode == this.constMode2up) {
3765 // check there are enough pages to display
3766 // $$$ this is a workaround for the mis-feature that we can't display
3767 // short books in 2up mode
3768 if (this.numLeafs < 6) {
3776 // searchHighlightVisible
3778 // Returns true if a search highlight is currently being displayed
3779 BookReader.prototype.searchHighlightVisible = function() {
3780 if (this.constMode2up == this.mode) {
3781 if (this.searchResults[this.twoPage.currentIndexL]
3782 || this.searchResults[this.twoPage.currentIndexR]) {
3786 if (this.searchResults[this.currentIndex()]) {
3793 // getPageBackgroundColor
3795 // Returns a CSS property string for the background color for the given page
3796 // $$$ turn into regular CSS?
3797 BookReader.prototype.getPageBackgroundColor = function(index) {
3798 if (index >= 0 && index < this.numLeafs) {
3800 return this.pageDefaultBackgroundColor;
3808 // Returns the page width for the given index, or first or last page if out of range
3809 BookReader.prototype._getPageWidth = function(index) {
3810 // Synthesize a page width for pages not actually present in book.
3811 // May or may not be the best approach.
3812 // If index is out of range we return the width of first or last page
3813 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3814 return this.getPageWidth(index);
3819 // Returns the page height for the given index, or first or last page if out of range
3820 BookReader.prototype._getPageHeight= function(index) {
3821 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3822 return this.getPageHeight(index);
3827 // Returns the page URI or transparent image if out of range
3828 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3829 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3830 return this.imagesBaseURL + "/transparent.png";
3833 if ('undefined' == typeof(reduce)) {
3834 // reduce not passed in
3835 // $$$ this probably won't work for thumbnail mode
3836 var ratio = this.getPageHeight(index) / this.twoPage.height;
3838 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3841 } else if (ratio < 4) {
3843 } else if (ratio < 8) {
3845 } else if (ratio < 16) {
3847 } else if (ratio < 32) {
3855 return this.getPageURI(index, reduce, rotate);
3858 // Library functions
3860 disableSelect: function(jObject) {
3861 // Bind mouse handlers
3862 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3863 jObject.bind('mousedown', function(e) {
3864 // $$$ check here for right-click and don't disable. Also use jQuery style
3865 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3868 // Special hack for IE7
3869 jObject[0].onselectstart = function(e) { return false; };
3872 clamp: function(value, min, max) {
3873 return Math.min(Math.max(value, min), max);
3876 notInArray: function(value, array) {
3877 // inArray returns -1 or undefined if value not in array
3878 return ! (jQuery.inArray(value, array) >= 0);
3881 getIFrameDocument: function(iframe) {
3882 // Adapted from http://xkr.us/articles/dom/iframe-document/
3883 var outer = (iframe.contentWindow || iframe.contentDocument);
3884 return (outer.document || outer);
3887 decodeURIComponentPlus: function(value) {
3888 // Decodes a URI component and converts '+' to ' '
3889 return decodeURIComponent(value).replace(/\+/g, ' ');
3892 encodeURIComponentPlus: function(value) {
3893 // Encodes a URI component and converts ' ' to '+'
3894 return encodeURIComponent(value).replace(/%20/g, '+');
3896 // The final property here must NOT have a comma after it - IE7