2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of BookReader.
6 BookReader is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 BookReader is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with BookReader. If not, see <http://www.gnu.org/licenses/>.
19 The BookReader source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
38 function BookReader() {
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
45 this.thumbWidth = 100; // will be overridden during prepareThumbnailView
46 this.thumbRowBuffer = 2; // number of rows to pre-cache out a view
47 this.thumbColumns = 6; // default
48 this.thumbMaxLoading = 4; // number of thumbnails to load at once
49 this.displayedRows=[];
51 this.displayedIndices = [];
52 //this.indicesToDisplay = [];
54 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
57 this.animating = false;
59 this.autoTimer = null;
60 this.flipSpeed = 'fast';
62 this.twoPagePopUp = null;
63 this.leafEdgeTmp = null;
64 this.embedPopup = null;
65 this.printPopup = null;
68 this.searchResults = {};
70 this.firstIndex = null;
72 this.lastDisplayableIndex2up = null;
74 // We link to index.php to avoid redirect which breaks back button
75 this.logoURL = 'http://www.archive.org/index.php';
77 // Base URL for images
78 this.imagesBaseURL = '/bookreader/images/';
81 this.constMode1up = 1;
82 this.constMode2up = 2;
83 this.constModeThumb = 3;
86 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
88 // Object to hold parameters related to 2up mode
90 coverInternalPadding: 10, // Width of cover
91 coverExternalPadding: 10, // Padding outside of cover
92 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
96 // Background color for pages (e.g. when loading page image)
97 // $$$ TODO dynamically calculate based on page images
98 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
104 //______________________________________________________________________________
105 BookReader.prototype.init = function() {
107 var startIndex = undefined;
108 this.pageScale = this.reduce; // preserve current reduce
110 // Find start index and mode if set in location hash
111 var params = this.paramsFromFragment(window.location.hash);
113 if ('undefined' != typeof(params.index)) {
114 startIndex = params.index;
115 } else if ('undefined' != typeof(params.page)) {
116 startIndex = this.getPageIndex(params.page);
119 if ('undefined' == typeof(startIndex)) {
120 if ('undefined' != typeof(this.titleLeaf)) {
121 startIndex = this.leafNumToIndex(this.titleLeaf);
125 if ('undefined' == typeof(startIndex)) {
129 if ('undefined' != typeof(params.mode)) {
130 this.mode = params.mode;
133 // Set document title -- may have already been set in enclosing html for
134 // search engine visibility
135 document.title = this.shortTitle(50);
137 // Sanitize parameters
138 if ( !this.canSwitchToMode( this.mode ) ) {
139 this.mode = this.constMode1up;
142 $("#BookReader").empty();
143 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
144 $("#BookReader").append("<div id='BRcontainer'></div>");
145 $("#BRcontainer").append("<div id='BRpageview'></div>");
147 $("#BRcontainer").bind('scroll', this, function(e) {
151 this.setupKeyListeners();
152 this.startLocationPolling();
154 $(window).bind('resize', this, function(e) {
155 //console.log('resize!');
156 if (1 == e.data.mode) {
157 //console.log('centering 1page view');
158 e.data.centerPageView();
159 $('#BRpageview').empty()
160 e.data.displayedIndices = [];
161 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
163 } else if (3 == e.data.mode){
164 e.data.prepareThumbnailView();
166 //console.log('drawing 2 page view');
168 // We only need to prepare again in autofit (size of spread changes)
169 if (e.data.twoPage.autofit) {
170 e.data.prepareTwoPageView();
172 // Re-center if the scrollbars have disappeared
173 var center = e.data.twoPageGetViewCenter();
174 var doRecenter = false;
175 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
176 center.percentageX = 0.5;
179 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
180 center.percentageY = 0.5;
184 e.data.twoPageCenterView(center.percentageX, center.percentageY);
190 $('.BRpagediv1up').bind('mousedown', this, function(e) {
191 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
192 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
196 // $$$ refactor this so it's enough to set the first index and call preparePageView
197 // (get rid of mode-specific logic at this point)
198 if (1 == this.mode) {
199 this.resizePageView();
200 this.firstIndex = startIndex;
201 this.jumpToIndex(startIndex);
202 } else if (3 == this.mode) {
203 this.firstIndex = startIndex;
204 this.prepareThumbnailView();
205 this.jumpToIndex(startIndex);
207 //this.resizePageView();
209 this.displayedIndices=[0];
210 this.firstIndex = startIndex;
211 this.displayedIndices = [this.firstIndex];
212 //console.log('titleLeaf: %d', this.titleLeaf);
213 //console.log('displayedIndices: %s', this.displayedIndices);
214 this.prepareTwoPageView();
217 // Enact other parts of initial params
218 this.updateFromParams(params);
221 BookReader.prototype.setupKeyListeners = function() {
234 // We use document here instead of window to avoid a bug in jQuery on IE7
235 $(document).keydown(function(e) {
237 // Keyboard navigation
238 if (!self.keyboardNavigationIsDisabled(e)) {
242 // In 1up mode page scrolling is handled by browser
243 if (2 == self.mode) {
250 if (2 == self.mode) {
264 if (2 == self.mode) {
270 if (2 == self.mode) {
281 //______________________________________________________________________________
282 BookReader.prototype.drawLeafs = function() {
283 if (1 == this.mode) {
284 this.drawLeafsOnePage();
285 } else if (3 == this.mode) {
286 this.drawLeafsThumbnail();
288 this.drawLeafsTwoPage();
294 //______________________________________________________________________________
295 BookReader.prototype.setDragHandler = function(div) {
296 div.dragging = false;
298 $(div).unbind('mousedown').bind('mousedown', function(e) {
301 //console.log('mousedown at ' + e.pageY);
303 this.dragging = true;
304 this.prevMouseX = e.pageX;
305 this.prevMouseY = e.pageY;
307 var startX = e.pageX;
308 var startY = e.pageY;
309 var startTop = $('#BRcontainer').attr('scrollTop');
310 var startLeft = $('#BRcontainer').attr('scrollLeft');
314 $(div).unbind('mousemove').bind('mousemove', function(ee) {
317 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
319 var offsetX = ee.pageX - this.prevMouseX;
320 var offsetY = ee.pageY - this.prevMouseY;
323 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
324 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
327 this.prevMouseX = ee.pageX;
328 this.prevMouseY = ee.pageY;
332 $(div).unbind('mouseup').bind('mouseup', function(ee) {
334 //console.log('mouseup');
336 this.dragging = false;
339 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
341 //console.log('mouseleave');
343 this.dragging = false;
346 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
348 //console.log('mouseenter');
350 this.dragging = false;
354 // setDragHandler2UP()
355 //______________________________________________________________________________
356 BookReader.prototype.setDragHandler2UP = function(div) {
357 div.dragging = false;
359 $(div).unbind('mousedown').bind('mousedown', function(e) {
362 //console.log('mousedown at ' + e.pageY);
364 this.dragStart = {x: e.pageX, y: e.pageY };
365 this.mouseDown = true;
366 this.dragging = false; // wait until drag distance
367 this.prevMouseX = e.pageX;
368 this.prevMouseY = e.pageY;
370 var startX = e.pageX;
371 var startY = e.pageY;
372 var startTop = $('#BRcontainer').attr('scrollTop');
373 var startLeft = $('#BRcontainer').attr('scrollLeft');
377 $(div).unbind('mousemove').bind('mousemove', function(ee) {
380 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
382 var offsetX = ee.pageX - this.prevMouseX;
383 var offsetY = ee.pageY - this.prevMouseY;
385 var minDragDistance = 5; // $$$ constant
387 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
389 if (this.mouseDown && (distance > minDragDistance)) {
390 //console.log('drag start!');
392 this.dragging = true;
396 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
397 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
398 this.prevMouseX = ee.pageX;
399 this.prevMouseY = ee.pageY;
406 $(div).unbind('mouseup').bind('mouseup', function(ee) {
408 //console.log('mouseup');
410 this.dragging = false;
411 this.mouseDown = false;
416 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
418 //console.log('mouseleave');
420 this.dragging = false;
421 this.mouseDown = false;
424 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
426 //console.log('mouseenter');
428 this.dragging = false;
429 this.mouseDown = false;
433 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
434 //console.log('setting handler');
435 //console.log(element.tagName);
437 $(element).unbind('click').bind('click', data, function(e) {
440 //console.log('click!');
442 if (this.mouseDown && (!this.dragging)) {
443 //console.log('click not dragging!');
447 this.dragging = false;
448 this.mouseDown = false;
452 // drawLeafsOnePage()
453 //______________________________________________________________________________
454 BookReader.prototype.drawLeafsOnePage = function() {
455 //alert('drawing leafs!');
459 var scrollTop = $('#BRcontainer').attr('scrollTop');
460 var scrollBottom = scrollTop + $('#BRcontainer').height();
461 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
463 var indicesToDisplay = [];
468 for (i=0; i<this.numLeafs; i++) {
469 var height = parseInt(this._getPageHeight(i)/this.reduce);
471 leafBottom += height;
472 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
473 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
474 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
475 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
476 if (topInView | bottomInView | middleInView) {
477 //console.log('displayed: ' + this.displayedIndices);
478 //console.log('to display: ' + i);
479 indicesToDisplay.push(i);
481 leafTop += height +10;
485 var firstIndexToDraw = indicesToDisplay[0];
486 this.firstIndex = firstIndexToDraw;
488 // Update hash, but only if we're currently displaying a leaf
489 // Hack that fixes #365790
490 if (this.displayedIndices.length > 0) {
491 this.updateLocationHash();
494 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
496 indicesToDisplay.unshift(firstIndexToDraw);
499 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
500 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
501 indicesToDisplay.push(lastIndexToDraw+1);
506 for (i=0; i<firstIndexToDraw; i++) {
507 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
510 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
511 var viewWidth = $('#BRcontainer').attr('scrollWidth');
514 for (i=0; i<indicesToDisplay.length; i++) {
515 var index = indicesToDisplay[i];
516 var height = parseInt(this._getPageHeight(index)/this.reduce);
518 if (BookReader.util.notInArray(indicesToDisplay[i], this.displayedIndices)) {
519 var width = parseInt(this._getPageWidth(index)/this.reduce);
520 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
521 var div = document.createElement("div");
522 div.className = 'BRpagediv1up';
523 div.id = 'pagediv'+index;
524 div.style.position = "absolute";
525 $(div).css('top', leafTop + 'px');
526 var left = (viewWidth-width)>>1;
527 if (left<0) left = 0;
528 $(div).css('left', left+'px');
529 $(div).css('width', width+'px');
530 $(div).css('height', height+'px');
531 //$(div).text('loading...');
533 this.setDragHandler(div);
535 $('#BRpageview').append(div);
537 var img = document.createElement("img");
538 img.src = this._getPageURI(index, this.reduce, 0);
539 $(img).css('width', width+'px');
540 $(img).css('height', height+'px');
544 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
547 leafTop += height +10;
551 for (i=0; i<this.displayedIndices.length; i++) {
552 if (BookReader.util.notInArray(this.displayedIndices[i], indicesToDisplay)) {
553 var index = this.displayedIndices[i];
554 //console.log('Removing leaf ' + index);
555 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
556 $('#pagediv'+index).remove();
558 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
562 this.displayedIndices = indicesToDisplay.slice();
563 this.updateSearchHilites();
565 if (null != this.getPageNum(firstIndexToDraw)) {
566 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
568 $("#BRpagenum").val('');
571 this.updateToolbarZoom(this.reduce);
575 // drawLeafsThumbnail()
576 //______________________________________________________________________________
577 BookReader.prototype.drawLeafsThumbnail = function() {
578 //alert('drawing leafs!');
581 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
583 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
597 // Calculate the position of every thumbnail. $$$ cache instead of calculating on every draw
598 for (i=0; i<this.numLeafs; i++) {
599 leafWidth = this.thumbWidth;
600 if (rightPos + (leafWidth + this.padding) > viewWidth){
606 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
607 if (leafMap[currentRow].leafs===undefined) {
608 leafMap[currentRow].leafs = [];
609 leafMap[currentRow].height = 0;
610 leafMap[currentRow].top = 0;
612 leafMap[currentRow].leafs[leafIndex] = {};
613 leafMap[currentRow].leafs[leafIndex].num = i;
614 leafMap[currentRow].leafs[leafIndex].left = rightPos;
616 leafHeight = parseInt((this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)*this.thumbWidth)/this.getPageWidth(leafMap[currentRow].leafs[leafIndex].num), 10);
617 if (leafHeight > leafMap[currentRow].height) {
618 leafMap[currentRow].height = leafHeight;
620 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
621 rightPos += leafWidth + this.padding;
622 if (rightPos > maxRight) { maxRight = rightPos; }
626 // reset the bottom position based on thumbnails
627 $('#BRpageview').height(bottomPos);
629 var pageViewBuffer = Math.floor(($('#BRcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
630 var scrollTop = $('#BRcontainer').attr('scrollTop');
631 var scrollBottom = scrollTop + $('#BRcontainer').height();
635 var rowsToDisplay = [];
637 // Visible leafs with least/greatest index
638 var leastVisible = this.numLeafs - 1;
641 // Determine the thumbnails in view
642 for (i=0; i<leafMap.length; i++) {
643 leafBottom += this.padding + leafMap[i].height;
644 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
645 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
646 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
647 if (topInView | bottomInView | middleInView) {
648 //console.log('row to display: ' + j);
649 rowsToDisplay.push(i);
650 if (leafMap[i].leafs[0].num < leastVisible) {
651 leastVisible = leafMap[i].leafs[0].num;
653 if (leafMap[i].leafs[leafMap[i].leafs.length - 1].num > mostVisible) {
654 mostVisible = leafMap[i].leafs[leafMap[i].leafs.length - 1].num;
657 if (leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
658 leafTop = leafBottom;
661 // create a buffer of preloaded rows before and after the visible rows
662 var firstRow = rowsToDisplay[0];
663 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
664 for (i=1; i<this.thumbRowBuffer+1; i++) {
665 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
667 for (i=1; i<this.thumbRowBuffer+1; i++) {
668 if (firstRow-i >= 0) { rowsToDisplay.push(firstRow-i); }
671 // Create the thumbnail divs and images (lazy loaded)
680 for (i=0; i<rowsToDisplay.length; i++) {
681 if (BookReader.util.notInArray(rowsToDisplay[i], this.displayedRows)) {
682 row = rowsToDisplay[i];
684 for (j=0; j<leafMap[row].leafs.length; j++) {
686 leaf = leafMap[row].leafs[j].num;
688 leafWidth = this.thumbWidth;
689 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
690 leafTop = leafMap[row].top;
691 left = leafMap[row].leafs[index].left + pageViewBuffer;
692 if ('rl' == this.pageProgression){
693 left = viewWidth - leafWidth - left;
696 div = document.createElement("div");
697 div.id = 'pagediv'+leaf;
698 div.style.position = "absolute";
699 div.className = "BRpagedivthumb";
701 left += this.padding;
702 $(div).css('top', leafTop + 'px');
703 $(div).css('left', left+'px');
704 $(div).css('width', leafWidth+'px');
705 $(div).css('height', leafHeight+'px');
706 //$(div).text('loading...');
708 // link to page in single page mode
709 link = document.createElement("a");
710 $(link).data('leaf', leaf);
711 $(link).bind('click', function(event) {
712 self.firstIndex = $(this).data('leaf');
713 self.switchMode(self.constMode1up);
714 event.preventDefault();
717 // $$$ we don't actually go to this URL (click is handled in handler above)
718 link.href = '#page/' + (this.getPageNum(leaf)) +'/mode/1up' ;
721 $('#BRpageview').append(div);
723 img = document.createElement("img");
724 var thumbReduce = Math.floor(this.getPageWidth(leaf) / this.thumbWidth);
726 $(img).attr('src', this.imagesBaseURL + 'transparent.png')
727 .css({'width': leafWidth+'px', 'height': leafHeight+'px' })
728 .addClass('BRlazyload')
729 // Store the URL of the image that will replace this one
730 .data('srcURL', this._getPageURI(leaf, thumbReduce));
732 //console.log('displaying thumbnail: ' + leaf);
737 // Remove thumbnails that are not to be displayed
739 for (i=0; i<this.displayedRows.length; i++) {
740 if (BookReader.util.notInArray(this.displayedRows[i], rowsToDisplay)) {
741 row = this.displayedRows[i];
743 // $$$ Safari doesn't like the comprehension
744 //var rowLeafs = [leaf.num for each (leaf in leafMap[row].leafs)];
745 //console.log('Removing row ' + row + ' ' + rowLeafs);
747 for (k=0; k<leafMap[row].leafs.length; k++) {
748 index = leafMap[row].leafs[k].num;
749 //console.log('Removing leaf ' + index);
750 $('#pagediv'+index).remove();
754 var mRow = this.displayedRows[i];
755 var mLeafs = '[' + [leaf.num for each (leaf in leafMap[mRow].leafs)] + ']';
756 console.log('NOT Removing row ' + mRow + ' ' + mLeafs);
761 // Update which page is considered current to make sure a visible page is the current one
762 var currentIndex = this.currentIndex();
763 // console.log('current ' + currentIndex);
764 // console.log('least visible ' + leastVisible + ' most visible ' + mostVisible);
765 if (currentIndex < leastVisible) {
766 this.setCurrentIndex(leastVisible);
767 } else if (currentIndex > mostVisible) {
768 this.setCurrentIndex(mostVisible);
771 this.displayedRows = rowsToDisplay.slice();
773 // Update hash, but only if we're currently displaying a leaf
774 // Hack that fixes #365790
775 if (this.displayedRows.length > 0) {
776 this.updateLocationHash();
779 // remove previous highlights
780 $('.BRpagedivthumb_highlight').removeClass('BRpagedivthumb_highlight');
782 // highlight current page
783 $('#pagediv'+this.currentIndex()).addClass('BRpagedivthumb_highlight');
785 this.lazyLoadThumbnails();
787 // Update page number box. $$$ refactor to function
788 if (null !== this.getPageNum(this.currentIndex())) {
789 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
791 $("#BRpagenum").val('');
794 this.updateToolbarZoom(this.reduce);
797 BookReader.prototype.lazyLoadThumbnails = function() {
799 // console.log('lazy load');
801 // We check the complete property since load may not be fired if loading from the cache
802 $('.BRlazyloading').filter('[complete=true]').removeClass('BRlazyloading');
804 var loading = $('.BRlazyloading').length;
805 var toLoad = this.thumbMaxLoading - loading;
807 // console.log(' ' + loading + ' thumbnails loading');
808 // console.log(' this.thumbMaxLoading ' + this.thumbMaxLoading);
813 // $$$ TODO load those near top (but not beyond) page view first
814 $('#BRpageview img.BRlazyload').filter(':lt(' + toLoad + ')').each( function() {
815 self.lazyLoadImage(this);
820 BookReader.prototype.lazyLoadImage = function (dummyImage) {
821 //console.log(' lazy load started for ' + $(dummyImage).data('srcURL').match('([0-9]{4}).jp2')[1] );
823 var img = new Image();
827 .addClass('BRlazyloading')
828 .one('load', function() {
829 //if (console) { console.log(' onload ' + $(this).attr('src').match('([0-9]{4}).jp2')[1]); };
831 $(this).removeClass('BRlazyloading');
833 // $$$ Calling lazyLoadThumbnails here was causing stack overflow on IE so
834 // we call the function after a slight delay. Also the img.complete property
835 // is not yet set in IE8 inside this onload handler
836 setTimeout(function() { self.lazyLoadThumbnails(); }, 100);
838 .one('error', function() {
839 // Remove class so we no longer count as loading
840 $(this).removeClass('BRlazyloading');
842 .attr( { width: $(dummyImage).width(),
843 height: $(dummyImage).height(),
844 src: $(dummyImage).data('srcURL')
847 // replace with the new img
848 $(dummyImage).before(img).remove();
850 img = null; // tidy up closure
854 // drawLeafsTwoPage()
855 //______________________________________________________________________________
856 BookReader.prototype.drawLeafsTwoPage = function() {
857 var scrollTop = $('#BRtwopageview').attr('scrollTop');
858 var scrollBottom = scrollTop + $('#BRtwopageview').height();
860 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
862 var indexL = this.twoPage.currentIndexL;
864 var heightL = this._getPageHeight(indexL);
865 var widthL = this._getPageWidth(indexL);
867 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
868 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
869 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
870 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
871 //console.log(leafEdgeWidthL);
873 var middle = this.twoPage.middle; // $$$ getter instead?
874 var top = this.twoPageTop();
875 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
877 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
878 this.twoPage.gutter = this.twoPageGutter();
880 this.prefetchImg(indexL);
881 $(this.prefetchedImgs[indexL]).css({
882 position: 'absolute',
883 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
886 backgroundColor: this.getPageBackgroundColor(indexL),
887 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
888 width: this.twoPage.scaledWL + 'px',
889 borderRight: '1px solid black',
891 }).appendTo('#BRtwopageview');
893 var indexR = this.twoPage.currentIndexR;
894 var heightR = this._getPageHeight(indexR);
895 var widthR = this._getPageWidth(indexR);
897 // $$$ should use getwidth2up?
898 //var scaledWR = this.twoPage.height*widthR/heightR;
899 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
900 this.prefetchImg(indexR);
901 $(this.prefetchedImgs[indexR]).css({
902 position: 'absolute',
903 left: this.twoPage.gutter+'px',
906 backgroundColor: this.getPageBackgroundColor(indexR),
907 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
908 width: this.twoPage.scaledWR + 'px',
909 borderLeft: '1px solid black',
911 }).appendTo('#BRtwopageview');
914 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
915 this.setMouseHandlers2UP();
916 this.twoPageSetCursor();
918 this.updatePageNumBox2UP();
919 this.updateToolbarZoom(this.reduce);
921 // this.twoPagePlaceFlipAreas(); // No longer used
925 // updatePageNumBox2UP
926 //______________________________________________________________________________
927 BookReader.prototype.updatePageNumBox2UP = function() {
928 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
929 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
931 $("#BRpagenum").val('');
933 this.updateLocationHash();
937 //______________________________________________________________________________
938 BookReader.prototype.loadLeafs = function() {
942 if (null == this.timer) {
943 this.timer=setTimeout(function(){self.drawLeafs()},250);
945 clearTimeout(this.timer);
946 this.timer=setTimeout(function(){self.drawLeafs()},250);
952 // Pass 1 to zoom in, anything else to zoom out
953 //______________________________________________________________________________
954 BookReader.prototype.zoom = function(direction) {
956 case this.constMode1up:
957 return this.zoom1up(direction);
958 case this.constMode2up:
959 return this.zoom2up(direction);
960 case this.constModeThumb:
961 return this.zoomThumb(direction);
966 //______________________________________________________________________________
967 BookReader.prototype.zoom1up = function(dir) {
969 if (2 == this.mode) { //can only zoom in 1-page mode
974 // $$$ with flexible zoom we could "snap" to /2 page reductions
975 // for better scaling
977 if (this.reduce <= 0.5) return;
978 this.reduce*=0.5; //zoom in
980 if (this.reduce >= 8) return;
981 this.reduce*=2; //zoom out
984 this.pageScale = this.reduce; // preserve current reduce
985 this.resizePageView();
987 $('#BRpageview').empty()
988 this.displayedIndices = [];
991 this.updateToolbarZoom(this.reduce);
993 // Recalculate search hilites
994 this.removeSearchHilites();
995 this.updateSearchHilites();
1000 //______________________________________________________________________________
1001 BookReader.prototype.resizePageView = function() {
1003 // $$$ This code assumes 1up mode
1004 // e.g. does not preserve position in thumbnail mode
1005 // See http://bugs.launchpad.net/bookreader/+bug/552972
1009 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
1010 var viewWidth = $('#BRcontainer').attr('clientWidth');
1012 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
1013 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
1014 var oldPageViewHeight = $('#BRpageview').height();
1015 var oldPageViewWidth = $('#BRpageview').width();
1017 var oldCenterY = this.centerY1up();
1018 var oldCenterX = this.centerX1up();
1020 if (0 != oldPageViewHeight) {
1021 var scrollRatio = oldCenterY / oldPageViewHeight;
1023 var scrollRatio = 0;
1026 for (i=0; i<this.numLeafs; i++) {
1027 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
1028 var width = parseInt(this._getPageWidth(i)/this.reduce);
1029 if (width>viewWidth) viewWidth=width;
1031 $('#BRpageview').height(viewHeight);
1032 $('#BRpageview').width(viewWidth);
1034 var newCenterY = scrollRatio*viewHeight;
1035 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
1036 $('#BRcontainer').attr('scrollTop', newTop);
1038 // We use clientWidth here to avoid miscalculating due to scroll bar
1039 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
1040 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
1041 newLeft = Math.max(newLeft, 0);
1042 $('#BRcontainer').attr('scrollLeft', newLeft);
1043 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
1045 //this.centerPageView();
1048 // $$$ jump to index here? index is not preserved when resizing in thumb mode
1050 // Not really needed until there is 1up autofit
1051 this.removeSearchHilites();
1052 this.updateSearchHilites();
1056 //______________________________________________________________________________
1057 // Returns the current offset of the viewport center in scaled document coordinates.
1058 BookReader.prototype.centerX1up = function() {
1060 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
1061 centerX = $('#BRpageview').width();
1063 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
1065 centerX = Math.floor(centerX);
1070 //______________________________________________________________________________
1071 // Returns the current offset of the viewport center in scaled document coordinates.
1072 BookReader.prototype.centerY1up = function() {
1073 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
1074 return Math.floor(centerY);
1078 //______________________________________________________________________________
1079 BookReader.prototype.centerPageView = function() {
1081 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
1082 var clientWidth = $('#BRcontainer').attr('clientWidth');
1083 //console.log('sW='+scrollWidth+' cW='+clientWidth);
1084 if (scrollWidth > clientWidth) {
1085 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
1090 // zoom2up(direction)
1091 //______________________________________________________________________________
1092 BookReader.prototype.zoom2up = function(direction) {
1094 // Hard stop autoplay
1095 this.stopFlipAnimations();
1097 // Get new zoom state
1098 var newZoom = this.twoPageNextReduce(this.reduce, direction);
1099 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
1102 this.twoPage.autofit = newZoom.autofit;
1103 this.reduce = newZoom.reduce;
1104 this.pageScale = this.reduce; // preserve current reduce
1106 // Preserve view center position
1107 var oldCenter = this.twoPageGetViewCenter();
1109 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
1110 // $$$ An improvement would be to use the low res image until the larger one is loaded.
1111 if (1 == direction) {
1112 for (var img in this.prefetchedImgs) {
1113 delete this.prefetchedImgs[img];
1117 // Prepare view with new center to minimize visual glitches
1118 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
1121 BookReader.prototype.zoomThumb = function(direction) {
1122 var oldColumns = this.thumbColumns;
1123 switch (direction) {
1125 this.thumbColumns += 1;
1128 this.thumbColumns -= 1;
1133 if (this.thumbColumns < 2) {
1134 this.thumbColumns = 2;
1135 } else if (this.thumbColumns > 8) {
1136 this.thumbColumns = 8;
1139 if (this.thumbColumns != oldColumns) {
1140 this.prepareThumbnailView();
1141 this.jumpToIndex(this.currentIndex());
1145 // Returns the width per thumbnail to display the requested number of columns
1146 // Note: #BRpageview must already exist since its width is used to calculate the
1148 BookReader.prototype.getThumbnailWidth = function(thumbnailColumns) {
1149 var padding = (thumbnailColumns + 1) * this.padding;
1150 var width = ($('#BRpageview').width() - padding) / (thumbnailColumns + 0.5); // extra 0.5 is for some space at sides
1151 return parseInt(width);
1154 // quantizeReduce(reduce)
1155 //______________________________________________________________________________
1156 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
1157 BookReader.prototype.quantizeReduce = function(reduce) {
1158 var quantized = this.reductionFactors[0];
1159 var distance = Math.abs(reduce - quantized);
1160 for (var i = 1; i < this.reductionFactors.length; i++) {
1161 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1162 if (newDistance < distance) {
1163 distance = newDistance;
1164 quantized = this.reductionFactors[i];
1171 // twoPageNextReduce()
1172 //______________________________________________________________________________
1173 // Returns the next reduction level
1174 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
1176 var autofitReduce = this.twoPageGetAutofitReduce();
1178 if (0 == direction) { // autofit
1179 result.autofit = true;
1180 result.reduce = autofitReduce;
1182 } else if (1 == direction) { // zoom in
1183 var newReduce = this.reductionFactors[0];
1185 for (var i = 1; i < this.reductionFactors.length; i++) {
1186 if (this.reductionFactors[i] < reduce) {
1187 newReduce = this.reductionFactors[i];
1191 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1193 result.autofit = true;
1194 result.reduce = autofitReduce;
1196 result.autofit = false;
1197 result.reduce = newReduce;
1200 } else { // zoom out
1201 var lastIndex = this.reductionFactors.length - 1;
1202 var newReduce = this.reductionFactors[lastIndex];
1204 for (var i = lastIndex; i >= 0; i--) {
1205 if (this.reductionFactors[i] > reduce) {
1206 newReduce = this.reductionFactors[i];
1210 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1212 result.autofit = true;
1213 result.reduce = autofitReduce;
1215 result.autofit = false;
1216 result.reduce = newReduce;
1224 //______________________________________________________________________________
1225 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1226 BookReader.prototype.jumpToPage = function(pageNum) {
1228 var pageIndex = this.getPageIndex(pageNum);
1230 if ('undefined' != typeof(pageIndex)) {
1233 this.jumpToIndex(pageIndex);
1234 $('#BRcontainer').attr('scrollTop', leafTop);
1243 //______________________________________________________________________________
1244 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
1246 if (2 == this.mode) {
1249 // By checking against min/max we do nothing if requested index
1251 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1252 this.flipBackToIndex(index);
1253 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1254 this.flipFwdToIndex(index);
1257 } else if (3 == this.mode) {
1258 var viewWidth = $('#BRcontainer').attr('scrollWidth') - 20; // width minus buffer
1268 for (i=0; i<(index+1); i++) {
1269 leafWidth = this.thumbWidth;
1270 if (rightPos + (leafWidth + this.padding) > viewWidth){
1276 // $$$ leaf is not defined in this function -- leaking in from somewhere else
1277 leafHeight = parseInt((this.getPageHeight(leaf)*this.thumbWidth)/this.getPageWidth(leaf), 10);
1278 if (leafHeight > rowHeight) { rowHeight = leafHeight; }
1279 if (leafIndex==0) { leafTop = bottomPos; }
1280 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1281 rightPos += leafWidth + this.padding;
1284 this.firstIndex=index;
1285 if ($('#BRcontainer').attr('scrollTop') == leafTop) {
1288 $('#BRcontainer').animate({scrollTop: leafTop },'fast');
1295 for (i=0; i<index; i++) {
1296 h = parseInt(this._getPageHeight(i)/this.reduce);
1297 leafTop += h + this.padding;
1301 //console.log('pageY ' + pageY);
1302 var offset = parseInt( (pageY) / this.reduce);
1303 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
1304 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1309 var offset = parseInt( (pageX) / this.reduce);
1310 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
1314 //$('#BRcontainer').attr('scrollTop', leafTop);
1315 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1321 //______________________________________________________________________________
1322 BookReader.prototype.switchMode = function(mode) {
1324 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1326 if (mode == this.mode) {
1330 if (!this.canSwitchToMode(mode)) {
1335 this.removeSearchHilites();
1338 this.switchToolbarMode(mode);
1340 // reinstate scale if moving from thumbnail view
1341 if (this.pageScale != this.reduce) {
1342 this.reduce = this.pageScale;
1345 // $$$ TODO preserve center of view when switching between mode
1346 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1349 this.reduce = this.quantizeReduce(this.reduce);
1350 this.prepareOnePageView();
1351 } else if (3 == mode) {
1352 this.reduce = this.quantizeReduce(this.reduce);
1353 this.prepareThumbnailView();
1354 this.jumpToIndex(this.currentIndex());
1356 // $$$ why don't we save autofit?
1357 this.twoPage.autofit = false; // Take zoom level from other mode
1358 this.reduce = this.quantizeReduce(this.reduce);
1359 this.prepareTwoPageView();
1360 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1365 //prepareOnePageView()
1366 //______________________________________________________________________________
1367 BookReader.prototype.prepareOnePageView = function() {
1369 // var startLeaf = this.displayedIndices[0];
1370 var startLeaf = this.currentIndex();
1372 $('#BRcontainer').empty();
1373 $('#BRcontainer').css({
1374 overflowY: 'scroll',
1378 $("#BRcontainer").append("<div id='BRpageview'></div>");
1379 // $$$ keep select enabled for now since disabling it breaks keyboard
1380 // nav in FF 3.6 (https://bugs.edge.launchpad.net/bookreader/+bug/544666)
1381 // BookReader.util.disableSelect($('#BRpageview'));
1383 this.resizePageView();
1385 this.jumpToIndex(startLeaf);
1386 this.displayedIndices = [];
1388 this.drawLeafsOnePage();
1391 //prepareThumbnailView()
1392 //______________________________________________________________________________
1393 BookReader.prototype.prepareThumbnailView = function() {
1395 $('#BRcontainer').empty();
1396 $('#BRcontainer').css({
1397 overflowY: 'scroll',
1401 $("#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 var startLeaf = this.currentIndex();
1408 this.thumbWidth = this.getThumbnailWidth(this.thumbColumns);
1409 this.reduce = this.getPageWidth(0)/this.thumbWidth;
1411 this.resizePageView();
1413 this.displayedRows = [];
1415 // $$$ resizePageView will do a delayed load -- this will make it happen faster
1416 this.drawLeafsThumbnail();
1419 // prepareTwoPageView()
1420 //______________________________________________________________________________
1421 // Some decisions about two page view:
1423 // Both pages will be displayed at the same height, even if they were different physical/scanned
1424 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1425 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1426 // aspect ratio to determine the height.
1428 // The two page view div is resized to keep the middle of the book in the middle of the div
1429 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1430 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1431 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1432 $('#BRcontainer').empty();
1433 $('#BRcontainer').css('overflow', 'auto');
1435 // We want to display two facing pages. We may be missing
1436 // one side of the spread because it is the first/last leaf,
1437 // foldouts, missing pages, etc
1439 //var targetLeaf = this.displayedIndices[0];
1440 var targetLeaf = this.firstIndex;
1442 if (targetLeaf < this.firstDisplayableIndex()) {
1443 targetLeaf = this.firstDisplayableIndex();
1446 if (targetLeaf > this.lastDisplayableIndex()) {
1447 targetLeaf = this.lastDisplayableIndex();
1450 //this.twoPage.currentIndexL = null;
1451 //this.twoPage.currentIndexR = null;
1452 //this.pruneUnusedImgs();
1454 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1455 this.twoPage.currentIndexL = currentSpreadIndices[0];
1456 this.twoPage.currentIndexR = currentSpreadIndices[1];
1457 this.firstIndex = this.twoPage.currentIndexL;
1459 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1461 this.pruneUnusedImgs();
1462 this.prefetch(); // Preload images or reload if scaling has changed
1464 //console.dir(this.twoPage);
1466 // Add the two page view
1467 // $$$ Can we get everything set up and then append?
1468 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1470 // $$$ calculate first then set
1471 $('#BRtwopageview').css( {
1472 height: this.twoPage.totalHeight + 'px',
1473 width: this.twoPage.totalWidth + 'px',
1474 position: 'absolute'
1477 // If there will not be scrollbars (e.g. when zooming out) we center the book
1478 // since otherwise the book will be stuck off-center
1479 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1480 centerPercentageX = 0.5;
1482 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1483 centerPercentageY = 0.5;
1486 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1488 this.twoPage.coverDiv = document.createElement('div');
1489 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1490 border: '1px solid rgb(68, 25, 17)',
1491 width: this.twoPage.bookCoverDivWidth + 'px',
1492 height: this.twoPage.bookCoverDivHeight+'px',
1493 visibility: 'visible',
1494 position: 'absolute',
1495 backgroundColor: '#663929',
1496 left: this.twoPage.bookCoverDivLeft + 'px',
1497 top: this.twoPage.bookCoverDivTop+'px',
1498 MozBorderRadiusTopleft: '7px',
1499 MozBorderRadiusTopright: '7px',
1500 MozBorderRadiusBottomright: '7px',
1501 MozBorderRadiusBottomleft: '7px'
1502 }).appendTo('#BRtwopageview');
1504 this.leafEdgeR = document.createElement('div');
1505 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1506 $(this.leafEdgeR).css({
1507 borderStyle: 'solid solid solid none',
1508 borderColor: 'rgb(51, 51, 34)',
1509 borderWidth: '1px 1px 1px 0px',
1510 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1511 width: this.twoPage.leafEdgeWidthR + 'px',
1512 height: this.twoPage.height-1 + 'px',
1514 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1515 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1516 position: 'absolute'
1517 }).appendTo('#BRtwopageview');
1519 this.leafEdgeL = document.createElement('div');
1520 this.leafEdgeL.className = 'leafEdgeL';
1521 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1522 borderStyle: 'solid none solid solid',
1523 borderColor: 'rgb(51, 51, 34)',
1524 borderWidth: '1px 0px 1px 1px',
1525 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1526 width: this.twoPage.leafEdgeWidthL + 'px',
1527 height: this.twoPage.height-1 + 'px',
1528 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1529 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1530 position: 'absolute'
1531 }).appendTo('#BRtwopageview');
1533 div = document.createElement('div');
1534 $(div).attr('id', 'BRbookspine').css({
1535 border: '1px solid rgb(68, 25, 17)',
1536 width: this.twoPage.bookSpineDivWidth+'px',
1537 height: this.twoPage.bookSpineDivHeight+'px',
1538 position: 'absolute',
1539 backgroundColor: 'rgb(68, 25, 17)',
1540 left: this.twoPage.bookSpineDivLeft+'px',
1541 top: this.twoPage.bookSpineDivTop+'px'
1542 }).appendTo('#BRtwopageview');
1544 var self = this; // for closure
1546 /* Flip areas no longer used
1547 this.twoPage.leftFlipArea = document.createElement('div');
1548 this.twoPage.leftFlipArea.className = 'BRfliparea';
1549 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1551 width: this.twoPageFlipAreaWidth() + 'px',
1552 height: this.twoPageFlipAreaHeight() + 'px',
1553 position: 'absolute',
1554 left: this.twoPageLeftFlipAreaLeft() + 'px',
1555 top: this.twoPageFlipAreaTop() + 'px',
1558 }).bind('click', function(e) {
1560 }).bind('mousedown', function(e) {
1562 }).appendTo('#BRtwopageview');
1564 this.twoPage.rightFlipArea = document.createElement('div');
1565 this.twoPage.rightFlipArea.className = 'BRfliparea';
1566 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1568 width: this.twoPageFlipAreaWidth() + 'px',
1569 height: this.twoPageFlipAreaHeight() + 'px',
1570 position: 'absolute',
1571 left: this.twoPageRightFlipAreaLeft() + 'px',
1572 top: this.twoPageFlipAreaTop() + 'px',
1575 }).bind('click', function(e) {
1577 }).bind('mousedown', function(e) {
1579 }).appendTo('#BRtwopageview');
1582 this.prepareTwoPagePopUp();
1584 this.displayedIndices = [];
1586 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1587 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1589 this.drawLeafsTwoPage();
1590 this.updateToolbarZoom(this.reduce);
1594 this.removeSearchHilites();
1595 this.updateSearchHilites();
1599 // prepareTwoPagePopUp()
1601 // This function prepares the "View Page n" popup that shows while the mouse is
1602 // over the left/right "stack of sheets" edges. It also binds the mouse
1603 // events for these divs.
1604 //______________________________________________________________________________
1605 BookReader.prototype.prepareTwoPagePopUp = function() {
1607 this.twoPagePopUp = document.createElement('div');
1608 $(this.twoPagePopUp).css({
1609 border: '1px solid black',
1611 position: 'absolute',
1612 fontFamily: 'sans-serif',
1615 backgroundColor: 'rgb(255, 255, 238)',
1617 }).appendTo('#BRcontainer');
1618 $(this.twoPagePopUp).hide();
1620 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1621 $(e.data.twoPagePopUp).show();
1624 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1625 $(e.data.twoPagePopUp).hide();
1628 $(this.leafEdgeL).bind('click', this, function(e) {
1630 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1631 e.data.jumpToIndex(jumpIndex);
1634 $(this.leafEdgeR).bind('click', this, function(e) {
1636 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1637 e.data.jumpToIndex(jumpIndex);
1640 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1642 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1643 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1645 // $$$ TODO: Make sure popup is positioned so that it is in view
1646 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1647 $(e.data.twoPagePopUp).css({
1648 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1649 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1653 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1655 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1656 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1658 // $$$ TODO: Make sure popup is positioned so that it is in view
1659 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1660 $(e.data.twoPagePopUp).css({
1661 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1662 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1667 // calculateSpreadSize()
1668 //______________________________________________________________________________
1669 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1670 // this.twoPage.currentIndexR
1671 // This function sets this.twoPage.height, twoPage.width
1673 BookReader.prototype.calculateSpreadSize = function() {
1675 var firstIndex = this.twoPage.currentIndexL;
1676 var secondIndex = this.twoPage.currentIndexR;
1677 //console.log('first page is ' + firstIndex);
1679 // Calculate page sizes and total leaf width
1681 if ( this.twoPage.autofit) {
1682 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1684 // set based on reduction factor
1685 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1688 // Both pages together
1689 this.twoPage.height = spreadSize.height;
1690 this.twoPage.width = spreadSize.width;
1693 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1694 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1697 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1698 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1699 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1703 // The width of the book cover div. The combined width of both pages, twice the width
1704 // of the book cover internal padding (2*10) and the page edges
1705 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1706 // The height of the book cover div
1707 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1710 // We calculate the total width and height for the div so that we can make the book
1712 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1713 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1714 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1715 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1716 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1717 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1719 // We want to minimize the unused space in two-up mode (maximize the amount of page
1720 // shown). We give width to the leaf edges and these widths change (though the sum
1721 // of the two remains constant) as we flip through the book. With the book
1722 // cover centered and fixed in the BRcontainer div the page images will meet
1723 // at the "gutter" which is generally offset from the center.
1724 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1725 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1727 // The left edge of the book cover moves depending on the width of the pages
1728 // $$$ change to getter
1729 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1730 // The top edge of the book cover stays a fixed distance from the top
1731 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1734 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1735 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1736 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1739 this.reduce = spreadSize.reduce; // $$$ really set this here?
1742 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1745 // We check which page is closest to a "normal" page and use that to set the height
1746 // for both pages. This means that foldouts and other odd size pages will be displayed
1747 // smaller than the nominal zoom amount.
1748 var canon5Dratio = 1.5;
1751 height: this._getPageHeight(firstIndex),
1752 width: this._getPageWidth(firstIndex)
1756 height: this._getPageHeight(secondIndex),
1757 width: this._getPageWidth(secondIndex)
1760 var firstIndexRatio = first.height / first.width;
1761 var secondIndexRatio = second.height / second.width;
1762 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1765 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1766 ratio = firstIndexRatio;
1767 //console.log('using firstIndexRatio ' + ratio);
1769 ratio = secondIndexRatio;
1770 //console.log('using secondIndexRatio ' + ratio);
1773 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1774 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1775 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1777 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1778 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1780 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1781 ideal.width -= 10; // $$$ fudge factor
1782 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1783 ideal.height -= 20; // fudge factor
1784 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1786 if (ideal.height/ratio <= ideal.width) {
1788 ideal.width = parseInt(ideal.height/ratio);
1791 ideal.height = parseInt(ideal.width*ratio);
1794 // $$$ check this logic with large spreads
1795 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1800 // getSpreadSizeFromReduce()
1801 //______________________________________________________________________________
1802 // Returns the spread size calculated from the reduction factor for the given pages
1803 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1804 var spreadSize = {};
1805 // $$$ Scale this based on reduce?
1806 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1807 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1808 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1810 // $$$ Possibly incorrect -- we should make height "dominant"
1811 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1812 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1813 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1814 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1815 spreadSize.reduce = reduce;
1820 // twoPageGetAutofitReduce()
1821 //______________________________________________________________________________
1822 // Returns the current ideal reduction factor
1823 BookReader.prototype.twoPageGetAutofitReduce = function() {
1824 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1825 return spreadSize.reduce;
1828 // twoPageSetCursor()
1829 //______________________________________________________________________________
1830 // Set the cursor for two page view
1831 BookReader.prototype.twoPageSetCursor = function() {
1832 // console.log('setting cursor');
1833 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1834 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1835 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1836 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1838 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1839 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1844 //______________________________________________________________________________
1845 // Returns the currently active index.
1846 BookReader.prototype.currentIndex = function() {
1847 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1848 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1849 return this.firstIndex; // $$$ TODO page in center of view would be better
1850 } else if (this.mode == this.constMode2up) {
1851 // Only allow indices that are actually present in book
1852 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1854 throw 'currentIndex called for unimplemented mode ' + this.mode;
1858 // setCurrentIndex(index)
1859 //______________________________________________________________________________
1860 // Sets the idea of current index without triggering other actions such as animation.
1861 // Compare to jumpToIndex which animates to that index
1862 BookReader.prototype.setCurrentIndex = function(index) {
1863 this.firstIndex = index;
1867 // Returns the current index if visible, or the logically current visible
1869 BookReader.prototype.currentIndexOrVisibleThumb = function() {
1870 // XXX finish implementation
1871 var index = this.currentIndex();
1872 if (!this.indexIsVisbleThumb(this.currentIndex()) {
1873 // XXX search for visible
1878 // Returns true if the given index is visible
1879 BookReader.prototype.indexIsVisibleThumb = function(index, onlyCompletelyVisible = true) {
1881 // $$$ I'd prefer to go through a stored leaf map instead of DOM
1889 //______________________________________________________________________________
1890 // Flip the right page over onto the left
1891 BookReader.prototype.right = function() {
1892 if ('rl' != this.pageProgression) {
1902 //______________________________________________________________________________
1903 // Flip to the rightmost page
1904 BookReader.prototype.rightmost = function() {
1905 if ('rl' != this.pageProgression) {
1913 //______________________________________________________________________________
1914 // Flip the left page over onto the right.
1915 BookReader.prototype.left = function() {
1916 if ('rl' != this.pageProgression) {
1926 //______________________________________________________________________________
1927 // Flip to the leftmost page
1928 BookReader.prototype.leftmost = function() {
1929 if ('rl' != this.pageProgression) {
1937 //______________________________________________________________________________
1938 BookReader.prototype.next = function() {
1939 if (2 == this.mode) {
1941 this.flipFwdToIndex(null);
1943 if (this.firstIndex < this.lastDisplayableIndex()) {
1944 this.jumpToIndex(this.firstIndex+1);
1950 //______________________________________________________________________________
1951 BookReader.prototype.prev = function() {
1952 if (2 == this.mode) {
1954 this.flipBackToIndex(null);
1956 if (this.firstIndex >= 1) {
1957 this.jumpToIndex(this.firstIndex-1);
1962 BookReader.prototype.first = function() {
1963 this.jumpToIndex(this.firstDisplayableIndex());
1966 BookReader.prototype.last = function() {
1967 this.jumpToIndex(this.lastDisplayableIndex());
1971 //______________________________________________________________________________
1972 // Scrolls down one screen view
1973 BookReader.prototype.scrollDown = function() {
1974 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1975 $('#BRcontainer').animate(
1976 { scrollTop: '+=' + $('#BRcontainer').height() * 0.95 + 'px'},
1977 450, 'easeInOutQuint'
1986 //______________________________________________________________________________
1987 // Scrolls up one screen view
1988 BookReader.prototype.scrollUp = function() {
1989 if ($.inArray(this.mode, [this.constMode2up, this.constModeThumb]) >= 0) {
1990 $('#BRcontainer').animate(
1991 { scrollTop: '-=' + $('#BRcontainer').height() * 0.95 + 'px'},
1992 450, 'easeInOutQuint'
2001 // flipBackToIndex()
2002 //______________________________________________________________________________
2003 // to flip back one spread, pass index=null
2004 BookReader.prototype.flipBackToIndex = function(index) {
2006 if (1 == this.mode) return;
2008 var leftIndex = this.twoPage.currentIndexL;
2010 if (this.animating) return;
2012 if (null != this.leafEdgeTmp) {
2013 alert('error: leafEdgeTmp should be null!');
2017 if (null == index) {
2018 index = leftIndex-2;
2020 //if (index<0) return;
2022 var previousIndices = this.getSpreadIndices(index);
2024 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
2028 this.animating = true;
2030 if ('rl' != this.pageProgression) {
2031 // Assume LTR and we are going backward
2032 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
2033 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
2035 // RTL and going backward
2036 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
2037 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
2041 // flipLeftToRight()
2042 //______________________________________________________________________________
2043 // Flips the page on the left towards the page on the right
2044 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
2046 var leftLeaf = this.twoPage.currentIndexL;
2048 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2049 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2050 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
2052 var currWidthL = this.getPageWidth2UP(leftLeaf);
2053 var newWidthL = this.getPageWidth2UP(newIndexL);
2054 var newWidthR = this.getPageWidth2UP(newIndexR);
2056 var top = this.twoPageTop();
2057 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
2059 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
2060 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
2062 //animation strategy:
2063 // 0. remove search highlight, if any.
2064 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
2065 // of the left leaf and where the user clicked in the leaf edge.
2066 // Note that if this function was triggered by left() and not a
2067 // mouse click, the width of leafEdgeTmp is very small (zero px).
2068 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
2069 // leftLeaf to width=0.
2070 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
2071 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
2072 // its new full width.
2073 // 4. After step 3 is finished, do the following:
2074 // - remove leafEdgeTmp from the dom.
2075 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
2076 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
2077 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
2078 // and width=newLeafEdgeWidthL.
2079 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
2080 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
2081 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
2082 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
2083 // - prefetch new adjacent leafs.
2084 // - set up click handlers for both new left and right leafs.
2085 // - redraw the search highlight.
2086 // - update the pagenum box and the url.
2089 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
2091 this.leafEdgeTmp = document.createElement('div');
2092 $(this.leafEdgeTmp).css({
2093 borderStyle: 'solid none solid solid',
2094 borderColor: 'rgb(51, 51, 34)',
2095 borderWidth: '1px 0px 1px 1px',
2096 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2097 width: leafEdgeTmpW + 'px',
2098 height: this.twoPage.height-1 + 'px',
2099 left: leftEdgeTmpLeft + 'px',
2101 position: 'absolute',
2103 }).appendTo('#BRtwopageview');
2105 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
2106 $(this.leafEdgeL).css({
2107 width: newLeafEdgeWidthL+'px',
2108 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
2111 // Left gets the offset of the current left leaf from the document
2112 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
2113 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
2114 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
2116 // We change the left leaf to right positioning
2117 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
2118 $(this.prefetchedImgs[leftLeaf]).css({
2123 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
2124 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
2128 this.removeSearchHilites();
2130 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
2131 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
2133 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
2134 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
2136 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
2137 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
2138 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
2140 $(self.leafEdgeR).css({
2141 // Moves the right leaf edge
2142 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
2143 left: gutter+newWidthR+'px'
2146 $(self.leafEdgeL).css({
2147 // Moves and resizes the left leaf edge
2148 width: newLeafEdgeWidthL+'px',
2149 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2152 // Resizes the brown border div
2153 $(self.twoPage.coverDiv).css({
2154 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2155 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
2158 $(self.leafEdgeTmp).remove();
2159 self.leafEdgeTmp = null;
2161 // $$$ TODO refactor with opposite direction flip
2163 self.twoPage.currentIndexL = newIndexL;
2164 self.twoPage.currentIndexR = newIndexR;
2165 self.twoPage.scaledWL = newWidthL;
2166 self.twoPage.scaledWR = newWidthR;
2167 self.twoPage.gutter = gutter;
2169 self.firstIndex = self.twoPage.currentIndexL;
2170 self.displayedIndices = [newIndexL, newIndexR];
2171 self.pruneUnusedImgs();
2173 self.animating = false;
2175 self.updateSearchHilites2UP();
2176 self.updatePageNumBox2UP();
2178 // self.twoPagePlaceFlipAreas(); // No longer used
2179 self.setMouseHandlers2UP();
2180 self.twoPageSetCursor();
2182 if (self.animationFinishedCallback) {
2183 self.animationFinishedCallback();
2184 self.animationFinishedCallback = null;
2192 //______________________________________________________________________________
2193 // Whether we flip left or right is dependent on the page progression
2194 // to flip forward one spread, pass index=null
2195 BookReader.prototype.flipFwdToIndex = function(index) {
2197 if (this.animating) return;
2199 if (null != this.leafEdgeTmp) {
2200 alert('error: leafEdgeTmp should be null!');
2204 if (null == index) {
2205 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
2207 if (index > this.lastDisplayableIndex()) return;
2209 this.animating = true;
2211 var nextIndices = this.getSpreadIndices(index);
2213 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
2215 if ('rl' != this.pageProgression) {
2216 // We did not specify RTL
2217 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
2218 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2221 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2222 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2226 // flipRightToLeft(nextL, nextR, gutter)
2227 // $$$ better not to have to pass gutter in
2228 //______________________________________________________________________________
2229 // Flip from left to right and show the nextL and nextR indices on those sides
2230 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2231 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2232 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2233 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2234 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2236 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2238 var top = this.twoPageTop();
2239 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2241 var middle = this.twoPage.middle;
2242 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2244 this.leafEdgeTmp = document.createElement('div');
2245 $(this.leafEdgeTmp).css({
2246 borderStyle: 'solid none solid solid',
2247 borderColor: 'rgb(51, 51, 34)',
2248 borderWidth: '1px 0px 1px 1px',
2249 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2250 width: leafEdgeTmpW + 'px',
2251 height: this.twoPage.height-1 + 'px',
2252 left: gutter+scaledW+'px',
2254 position: 'absolute',
2256 }).appendTo('#BRtwopageview');
2258 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2259 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2261 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2262 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2263 var newWidthL = this.getPageWidth2UP(newIndexL);
2264 var newWidthR = this.getPageWidth2UP(newIndexR);
2266 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2268 var self = this; // closure-tastic!
2270 var speed = this.flipSpeed;
2272 this.removeSearchHilites();
2274 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2275 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2276 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2277 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2278 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2280 $(self.leafEdgeL).css({
2281 width: newLeafEdgeWidthL+'px',
2282 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2285 // Resizes the book cover
2286 $(self.twoPage.coverDiv).css({
2287 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2288 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2291 $(self.leafEdgeTmp).remove();
2292 self.leafEdgeTmp = null;
2294 self.twoPage.currentIndexL = newIndexL;
2295 self.twoPage.currentIndexR = newIndexR;
2296 self.twoPage.scaledWL = newWidthL;
2297 self.twoPage.scaledWR = newWidthR;
2298 self.twoPage.gutter = gutter;
2300 self.firstIndex = self.twoPage.currentIndexL;
2301 self.displayedIndices = [newIndexL, newIndexR];
2302 self.pruneUnusedImgs();
2304 self.animating = false;
2307 self.updateSearchHilites2UP();
2308 self.updatePageNumBox2UP();
2310 // self.twoPagePlaceFlipAreas(); // No longer used
2311 self.setMouseHandlers2UP();
2312 self.twoPageSetCursor();
2314 if (self.animationFinishedCallback) {
2315 self.animationFinishedCallback();
2316 self.animationFinishedCallback = null;
2322 // setMouseHandlers2UP
2323 //______________________________________________________________________________
2324 BookReader.prototype.setMouseHandlers2UP = function() {
2326 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2331 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2338 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2339 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2346 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2347 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2350 e.data.self.right();
2356 //______________________________________________________________________________
2357 BookReader.prototype.prefetchImg = function(index) {
2358 var pageURI = this._getPageURI(index);
2360 // Load image if not loaded or URI has changed (e.g. due to scaling)
2361 var loadImage = false;
2362 if (undefined == this.prefetchedImgs[index]) {
2363 //console.log('no image for ' + index);
2365 } else if (pageURI != this.prefetchedImgs[index].uri) {
2366 //console.log('uri changed for ' + index);
2371 //console.log('prefetching ' + index);
2372 var img = document.createElement("img");
2374 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2375 this.prefetchedImgs[index] = img;
2380 // prepareFlipLeftToRight()
2382 //______________________________________________________________________________
2384 // Prepare to flip the left page towards the right. This corresponds to moving
2385 // backward when the page progression is left to right.
2386 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2388 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2390 this.prefetchImg(prevL);
2391 this.prefetchImg(prevR);
2393 var height = this._getPageHeight(prevL);
2394 var width = this._getPageWidth(prevL);
2395 var middle = this.twoPage.middle;
2396 var top = this.twoPageTop();
2397 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2399 // The gutter is the dividing line between the left and right pages.
2400 // It is offset from the middle to create the illusion of thickness to the pages
2401 var gutter = middle + this.gutterOffsetForIndex(prevL);
2403 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2404 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2405 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2408 position: 'absolute',
2409 left: gutter-scaledW+'px',
2410 right: '', // clear right property
2412 height: this.twoPage.height,
2413 width: scaledW+'px',
2414 backgroundColor: this.getPageBackgroundColor(prevL),
2415 borderRight: '1px solid black',
2419 $(this.prefetchedImgs[prevL]).css(leftCSS);
2421 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
2423 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2426 position: 'absolute',
2430 height: this.twoPage.height,
2432 backgroundColor: this.getPageBackgroundColor(prevR),
2433 borderLeft: '1px solid black',
2437 $(this.prefetchedImgs[prevR]).css(rightCSS);
2439 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
2443 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2444 // prepareFlipRightToLeft()
2445 //______________________________________________________________________________
2446 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2448 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2451 this.prefetchImg(nextL);
2452 this.prefetchImg(nextR);
2454 var height = this._getPageHeight(nextR);
2455 var width = this._getPageWidth(nextR);
2456 var middle = this.twoPage.middle;
2457 var top = this.twoPageTop();
2458 var scaledW = this.twoPage.height*width/height;
2460 var gutter = middle + this.gutterOffsetForIndex(nextL);
2462 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2463 $(this.prefetchedImgs[nextR]).css({
2464 position: 'absolute',
2467 backgroundColor: this.getPageBackgroundColor(nextR),
2468 height: this.twoPage.height,
2469 width: scaledW+'px',
2470 borderLeft: '1px solid black',
2474 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2476 height = this._getPageHeight(nextL);
2477 width = this._getPageWidth(nextL);
2478 scaledW = this.twoPage.height*width/height;
2480 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2481 $(this.prefetchedImgs[nextL]).css({
2482 position: 'absolute',
2483 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2485 backgroundColor: this.getPageBackgroundColor(nextL),
2486 height: this.twoPage.height,
2487 width: 0+'px', // Start at 0 width, then grow to the left
2488 borderRight: '1px solid black',
2492 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2496 // getNextLeafs() -- NOT RTL AWARE
2497 //______________________________________________________________________________
2498 // BookReader.prototype.getNextLeafs = function(o) {
2499 // //TODO: we might have two left or two right leafs in a row (damaged book)
2500 // //For now, assume that leafs are contiguous.
2502 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2503 // o.L = this.twoPage.currentIndexL+2;
2504 // o.R = this.twoPage.currentIndexL+3;
2507 // getprevLeafs() -- NOT RTL AWARE
2508 //______________________________________________________________________________
2509 // BookReader.prototype.getPrevLeafs = function(o) {
2510 // //TODO: we might have two left or two right leafs in a row (damaged book)
2511 // //For now, assume that leafs are contiguous.
2513 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2514 // o.L = this.twoPage.currentIndexL-2;
2515 // o.R = this.twoPage.currentIndexL-1;
2518 // pruneUnusedImgs()
2519 //______________________________________________________________________________
2520 BookReader.prototype.pruneUnusedImgs = function() {
2521 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2522 for (var key in this.prefetchedImgs) {
2523 //console.log('key is ' + key);
2524 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2525 //console.log('removing key '+ key);
2526 $(this.prefetchedImgs[key]).remove();
2528 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2529 //console.log('deleting key '+ key);
2530 delete this.prefetchedImgs[key];
2536 //______________________________________________________________________________
2537 BookReader.prototype.prefetch = function() {
2539 // $$$ We should check here if the current indices have finished
2540 // loading (with some timeout) before loading more page images
2541 // See https://bugs.edge.launchpad.net/bookreader/+bug/511391
2543 // prefetch visible pages first
2544 this.prefetchImg(this.twoPage.currentIndexL);
2545 this.prefetchImg(this.twoPage.currentIndexR);
2547 var adjacentPagesToLoad = 3;
2549 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2550 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2552 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2553 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2555 // Load images spreading out from current
2556 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2557 var goingDown = lowCurrent - i;
2558 if (goingDown >= start) {
2559 this.prefetchImg(goingDown);
2561 var goingUp = highCurrent + i;
2562 if (goingUp <= end) {
2563 this.prefetchImg(goingUp);
2568 var lim = this.twoPage.currentIndexL-4;
2570 lim = Math.max(lim, 0);
2571 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2572 this.prefetchImg(i);
2575 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2576 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2577 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2578 this.prefetchImg(i);
2584 // getPageWidth2UP()
2585 //______________________________________________________________________________
2586 BookReader.prototype.getPageWidth2UP = function(index) {
2587 // We return the width based on the dominant height
2588 var height = this._getPageHeight(index);
2589 var width = this._getPageWidth(index);
2590 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2594 //______________________________________________________________________________
2595 BookReader.prototype.search = function(term) {
2596 term = term.replace(/\//g, ' '); // strip slashes
2597 this.searchTerm = term;
2598 $('#BookReaderSearchScript').remove();
2599 var script = document.createElement("script");
2600 script.setAttribute('id', 'BookReaderSearchScript');
2601 script.setAttribute("type", "text/javascript");
2602 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2603 document.getElementsByTagName('head')[0].appendChild(script);
2604 $('#BookReaderSearchBox').val(term);
2605 $('#BookReaderSearchResults').html('Searching...');
2608 // BRSearchCallback()
2609 //______________________________________________________________________________
2610 BookReader.prototype.BRSearchCallback = function(txt) {
2612 if (jQuery.browser.msie) {
2613 var dom=new ActiveXObject("Microsoft.XMLDOM");
2617 var parser = new DOMParser();
2618 var dom = parser.parseFromString(txt, "text/xml");
2621 $('#BookReaderSearchResults').empty();
2622 $('#BookReaderSearchResults').append('<ul>');
2624 for (var key in this.searchResults) {
2625 if (null != this.searchResults[key].div) {
2626 $(this.searchResults[key].div).remove();
2628 delete this.searchResults[key];
2631 var pages = dom.getElementsByTagName('PAGE');
2633 if (0 == pages.length) {
2634 // $$$ it would be nice to echo the (sanitized) search result here
2635 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2637 for (var i = 0; i < pages.length; i++){
2638 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2641 var re = new RegExp (/_(\d{4})\.djvu/);
2642 var reMatch = re.exec(pages[i].getAttribute('file'));
2643 var index = parseInt(reMatch[1], 10);
2644 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2646 var children = pages[i].childNodes;
2648 for (var j=0; j<children.length; j++) {
2649 //console.log(j + ' - ' + children[j].nodeName);
2650 //console.log(children[j].firstChild.nodeValue);
2651 if ('CONTEXT' == children[j].nodeName) {
2652 context += children[j].firstChild.nodeValue;
2653 } else if ('WORD' == children[j].nodeName) {
2654 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2656 var index = this.leafNumToIndex(index);
2657 if (null != index) {
2658 //coordinates are [left, bottom, right, top, [baseline]]
2659 //we'll skip baseline for now...
2660 var coords = children[j].getAttribute('coords').split(',',4);
2661 if (4 == coords.length) {
2662 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2667 var pageName = this.getPageName(index);
2668 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2669 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2670 //TODO: remove hardcoded instance name
2671 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2674 $('#BookReaderSearchResults').append('</ul>');
2676 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2677 $('#BookReaderSearchBox').val(this.searchTerm);
2679 this.updateSearchHilites();
2682 // updateSearchHilites()
2683 //______________________________________________________________________________
2684 BookReader.prototype.updateSearchHilites = function() {
2685 if (2 == this.mode) {
2686 this.updateSearchHilites2UP();
2688 this.updateSearchHilites1UP();
2692 // showSearchHilites1UP()
2693 //______________________________________________________________________________
2694 BookReader.prototype.updateSearchHilites1UP = function() {
2696 for (var key in this.searchResults) {
2698 if (jQuery.inArray(parseInt(key), this.displayedIndices) >= 0) {
2699 var result = this.searchResults[key];
2700 if (null == result.div) {
2701 result.div = document.createElement('div');
2702 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2703 //console.log('appending ' + key);
2706 width: (result.r-result.l)/this.reduce + 'px',
2707 height: (result.b-result.t)/this.reduce + 'px',
2708 left: (result.l)/this.reduce + 'px',
2709 top: (result.t)/this.reduce +'px'
2713 //console.log(key + ' not displayed');
2714 this.searchResults[key].div=null;
2720 //______________________________________________________________________________
2721 // Returns the position of the gutter (line between the page images)
2722 BookReader.prototype.twoPageGutter = function() {
2723 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2727 //______________________________________________________________________________
2728 // Returns the offset for the top of the page images
2729 BookReader.prototype.twoPageTop = function() {
2730 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2733 // twoPageCoverWidth()
2734 //______________________________________________________________________________
2735 // Returns the width of the cover div given the total page width
2736 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2737 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2740 // twoPageGetViewCenter()
2741 //______________________________________________________________________________
2742 // Returns the percentage offset into twopageview div at the center of container div
2743 // { percentageX: float, percentageY: float }
2744 BookReader.prototype.twoPageGetViewCenter = function() {
2747 var containerOffset = $('#BRcontainer').offset();
2748 var viewOffset = $('#BRtwopageview').offset();
2749 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2750 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2755 // twoPageCenterView(percentageX, percentageY)
2756 //______________________________________________________________________________
2757 // Centers the point given by percentage from left,top of twopageview
2758 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2759 if ('undefined' == typeof(percentageX)) {
2762 if ('undefined' == typeof(percentageY)) {
2766 var viewWidth = $('#BRtwopageview').width();
2767 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2768 var intoViewX = percentageX * viewWidth;
2770 var viewHeight = $('#BRtwopageview').height();
2771 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2772 var intoViewY = percentageY * viewHeight;
2774 if (viewWidth < containerClientWidth) {
2775 // Can fit width without scrollbars - center by adjusting offset
2776 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2778 // Need to scroll to center
2779 $('#BRtwopageview').css('left', 0);
2780 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2783 if (viewHeight < containerClientHeight) {
2784 // Fits with scrollbars - add offset
2785 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2787 $('#BRtwopageview').css('top', 0);
2788 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2792 // twoPageFlipAreaHeight
2793 //______________________________________________________________________________
2794 // Returns the integer height of the click-to-flip areas at the edges of the book
2795 BookReader.prototype.twoPageFlipAreaHeight = function() {
2796 return parseInt(this.twoPage.height);
2799 // twoPageFlipAreaWidth
2800 //______________________________________________________________________________
2801 // Returns the integer width of the flip areas
2802 BookReader.prototype.twoPageFlipAreaWidth = function() {
2803 var max = 100; // $$$ TODO base on view width?
2806 var width = this.twoPage.width * 0.15;
2807 return parseInt(BookReader.util.clamp(width, min, max));
2810 // twoPageFlipAreaTop
2811 //______________________________________________________________________________
2812 // Returns integer top offset for flip areas
2813 BookReader.prototype.twoPageFlipAreaTop = function() {
2814 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2817 // twoPageLeftFlipAreaLeft
2818 //______________________________________________________________________________
2819 // Left offset for left flip area
2820 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2821 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2824 // twoPageRightFlipAreaLeft
2825 //______________________________________________________________________________
2826 // Left offset for right flip area
2827 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2828 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2831 // twoPagePlaceFlipAreas
2832 //______________________________________________________________________________
2833 // Readjusts position of flip areas based on current layout
2834 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2835 // We don't set top since it shouldn't change relative to view
2836 $(this.twoPage.leftFlipArea).css({
2837 left: this.twoPageLeftFlipAreaLeft() + 'px',
2838 width: this.twoPageFlipAreaWidth() + 'px'
2840 $(this.twoPage.rightFlipArea).css({
2841 left: this.twoPageRightFlipAreaLeft() + 'px',
2842 width: this.twoPageFlipAreaWidth() + 'px'
2846 // showSearchHilites2UP()
2847 //______________________________________________________________________________
2848 BookReader.prototype.updateSearchHilites2UP = function() {
2850 for (var key in this.searchResults) {
2851 key = parseInt(key, 10);
2852 if (jQuery.inArray(key, this.displayedIndices) >= 0) {
2853 var result = this.searchResults[key];
2854 if (null == result.div) {
2855 result.div = document.createElement('div');
2856 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2857 //console.log('appending ' + key);
2860 // We calculate the reduction factor for the specific page because it can be different
2861 // for each page in the spread
2862 var height = this._getPageHeight(key);
2863 var width = this._getPageWidth(key)
2864 var reduce = this.twoPage.height/height;
2865 var scaledW = parseInt(width*reduce);
2867 var gutter = this.twoPageGutter();
2869 if ('L' == this.getPageSide(key)) {
2870 pageL = gutter-scaledW;
2874 var pageT = this.twoPageTop();
2877 width: (result.r-result.l)*reduce + 'px',
2878 height: (result.b-result.t)*reduce + 'px',
2879 left: pageL+(result.l)*reduce + 'px',
2880 top: pageT+(result.t)*reduce +'px'
2884 //console.log(key + ' not displayed');
2885 if (null != this.searchResults[key].div) {
2886 //console.log('removing ' + key);
2887 $(this.searchResults[key].div).remove();
2889 this.searchResults[key].div=null;
2894 // removeSearchHilites()
2895 //______________________________________________________________________________
2896 BookReader.prototype.removeSearchHilites = function() {
2897 for (var key in this.searchResults) {
2898 if (null != this.searchResults[key].div) {
2899 $(this.searchResults[key].div).remove();
2900 this.searchResults[key].div=null;
2906 //______________________________________________________________________________
2907 BookReader.prototype.printPage = function() {
2908 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2910 /* iframe implementation
2912 if (null != this.printPopup) { // check if already showing
2915 this.printPopup = document.createElement("div");
2916 $(this.printPopup).css({
2917 position: 'absolute',
2919 left: ($('#BRcontainer').width()-400)/2 + 'px',
2922 border: "3px double #999999",
2924 backgroundColor: "#fff"
2925 }).appendTo('#BookReader');
2928 if (this.constMode1up == this.mode) {
2929 indexToPrint = this.firstIndex;
2931 indexToPrint = this.twoPage.currentIndexL;
2934 this.indexToPrint = indexToPrint;
2936 var htmlStr = '<div style="text-align: center;">';
2937 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>';
2938 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2939 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2940 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2941 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2942 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2944 htmlStr += '</div>';
2945 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2946 htmlStr += '</div>';
2948 this.printPopup.innerHTML = htmlStr;
2950 var iframe = document.createElement('iframe');
2951 iframe.id = 'printFrame';
2952 iframe.name = 'printFrame';
2953 iframe.width = '233px'; // 8.5 x 11 aspect
2954 iframe.height = '300px';
2956 var self = this; // closure
2958 $(iframe).load(function() {
2959 var doc = BookReader.util.getIFrameDocument(this);
2960 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2963 $('#printDiv').prepend(iframe);
2967 // Get print URI from current indices and mode
2968 BookReader.prototype.getPrintURI = function() {
2970 if (this.constMode2up == this.mode) {
2971 indexToPrint = this.twoPage.currentIndexL;
2973 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2976 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2977 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2978 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2980 if (this.constMode2up == this.mode) {
2981 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2982 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2983 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2985 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2988 return '/bookreader/print.php?' + options;
2991 /* iframe implementation
2992 BookReader.prototype.getPrintFrameContent = function(index) {
2993 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2994 // 8.5x11 so we should end up not overflowing on either paper size.
2995 var paperAspect = 8.5 / 11;
2996 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
3000 // Rotate if possible and appropriate, to get larger image size on printed page
3001 if (this.canRotatePage(index)) {
3002 if (imageAspect > 1 && imageAspect > paperAspect) {
3003 // more wide than square, and more wide than paper
3005 imageAspect = 1/imageAspect;
3010 if (imageAspect > paperAspect) {
3011 // wider than paper, fit width
3012 fitAttrs = 'width="95%"';
3014 // taller than paper, fit height
3015 fitAttrs = 'height="95%"';
3018 var imageURL = this._getPageURI(index, 1, rotate);
3019 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
3020 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
3021 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
3022 iframeStr += '</div>';
3023 iframeStr += '</body></html>';
3028 BookReader.prototype.updatePrintFrame = function(delta) {
3029 var newIndex = this.indexToPrint + delta;
3030 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
3031 if (newIndex == this.indexToPrint) {
3034 this.indexToPrint = newIndex;
3035 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
3036 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
3041 //______________________________________________________________________________
3042 BookReader.prototype.showEmbedCode = function() {
3043 if (null != this.embedPopup) { // check if already showing
3047 this.embedPopup = document.createElement("div");
3048 $(this.embedPopup).css({
3049 position: 'absolute',
3051 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
3054 border: "3px double #999999",
3056 backgroundColor: "#fff"
3057 }).appendTo('#BookReader');
3059 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
3060 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>';
3061 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
3062 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
3064 this.embedPopup.innerHTML = htmlStr;
3065 $(this.embedPopup).find('input').bind('click', function() {
3071 //______________________________________________________________________________
3072 BookReader.prototype.autoToggle = function() {
3074 var bComingFrom1up = false;
3075 if (2 != this.mode) {
3076 bComingFrom1up = true;
3080 // Change to autofit if book is too large
3081 if (this.reduce < this.twoPageGetAutofitReduce()) {
3086 if (null == this.autoTimer) {
3087 this.flipSpeed = 2000;
3089 // $$$ Draw events currently cause layout problems when they occur during animation.
3090 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
3091 // we workaround for now by not triggering immediate animation in that case.
3092 // See https://bugs.launchpad.net/gnubook/+bug/328327
3093 if (('rl' == this.pageProgression) && bComingFrom1up) {
3094 // don't flip immediately -- wait until timer fires
3097 this.flipFwdToIndex();
3100 $('#BRtoolbar .play').hide();
3101 $('#BRtoolbar .pause').show();
3102 this.autoTimer=setInterval(function(){
3103 if (self.animating) {return;}
3105 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
3106 self.flipBackToIndex(1); // $$$ really what we want?
3108 self.flipFwdToIndex();
3117 //______________________________________________________________________________
3118 // Stop autoplay mode, allowing animations to finish
3119 BookReader.prototype.autoStop = function() {
3120 if (null != this.autoTimer) {
3121 clearInterval(this.autoTimer);
3122 this.flipSpeed = 'fast';
3123 $('#BRtoolbar .pause').hide();
3124 $('#BRtoolbar .play').show();
3125 this.autoTimer = null;
3129 // stopFlipAnimations
3130 //______________________________________________________________________________
3131 // Immediately stop flip animations. Callbacks are triggered.
3132 BookReader.prototype.stopFlipAnimations = function() {
3134 this.autoStop(); // Clear timers
3136 // Stop animation, clear queue, trigger callbacks
3137 if (this.leafEdgeTmp) {
3138 $(this.leafEdgeTmp).stop(false, true);
3140 jQuery.each(this.prefetchedImgs, function() {
3141 $(this).stop(false, true);
3144 // And again since animations also queued in callbacks
3145 if (this.leafEdgeTmp) {
3146 $(this.leafEdgeTmp).stop(false, true);
3148 jQuery.each(this.prefetchedImgs, function() {
3149 $(this).stop(false, true);
3154 // keyboardNavigationIsDisabled(event)
3155 // - returns true if keyboard navigation should be disabled for the event
3156 //______________________________________________________________________________
3157 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
3158 if (event.target.tagName == "INPUT") {
3164 // gutterOffsetForIndex
3165 //______________________________________________________________________________
3167 // Returns the gutter offset for the spread containing the given index.
3168 // This function supports RTL
3169 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
3171 // To find the offset of the gutter from the middle we calculate our percentage distance
3172 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
3173 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
3175 // But then again for RTL it's the opposite
3176 if ('rl' == this.pageProgression) {
3184 //______________________________________________________________________________
3185 // Returns the width of the leaf edge div for the page with index given
3186 BookReader.prototype.leafEdgeWidth = function(pindex) {
3187 // $$$ could there be single pixel rounding errors for L vs R?
3188 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
3189 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3191 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
3195 // jumpIndexForLeftEdgePageX
3196 //______________________________________________________________________________
3197 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
3198 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
3199 if ('rl' != this.pageProgression) {
3200 // LTR - flipping backward
3201 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3203 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
3204 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
3208 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
3209 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
3214 // jumpIndexForRightEdgePageX
3215 //______________________________________________________________________________
3216 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
3217 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
3218 if ('rl' != this.pageProgression) {
3220 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
3221 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3224 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3225 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3230 BookReader.prototype.initToolbar = function(mode, ui) {
3232 $("#BookReader").append("<div id='BRtoolbar'>"
3233 + "<span id='BRtoolbarbuttons' style='float: right'>"
3234 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
3235 + "<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>"
3236 + "<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>"
3237 + "<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>"
3238 + "<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>"
3239 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
3243 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
3244 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
3245 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
3246 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3247 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
3248 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
3249 + " <button class='BRicon rollover thumbnail_mode' onclick='br.switchMode(3); return false;'/>"
3252 + "<span id='#BRbooktitle'>"
3253 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3257 this.updateToolbarZoom(this.reduce); // Pretty format
3259 if (ui == "embed") {
3260 $("#BookReader a.logo").attr("target","_blank");
3263 // $$$ turn this into a member variable
3264 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
3266 // We build in mode 2
3269 this.bindToolbarNavHandlers(jToolbar);
3271 // Setup tooltips -- later we could load these from a file for i18n
3272 var titles = { '.logo': 'Go to Archive.org',
3273 '.zoom_in': 'Zoom in',
3274 '.zoom_out': 'Zoom out',
3275 '.one_page_mode': 'One-page view',
3276 '.two_page_mode': 'Two-page view',
3277 '.thumbnail_mode': 'Thumbnail view',
3278 '.print': 'Print this page',
3279 '.embed': 'Embed bookreader',
3280 '.book_left': 'Flip left',
3281 '.book_right': 'Flip right',
3282 '.book_up': 'Page up',
3283 '.book_down': 'Page down',
3286 '.book_top': 'First page',
3287 '.book_bottom': 'Last page'
3289 if ('rl' == this.pageProgression) {
3290 titles['.book_leftmost'] = 'Last page';
3291 titles['.book_rightmost'] = 'First page';
3293 titles['.book_leftmost'] = 'First page';
3294 titles['.book_rightmost'] = 'Last page';
3297 for (var icon in titles) {
3298 jToolbar.find(icon).attr('title', titles[icon]);
3301 // Hide mode buttons and autoplay if 2up is not available
3302 // $$$ if we end up with more than two modes we should show the applicable buttons
3303 if ( !this.canSwitchToMode(this.constMode2up) ) {
3304 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3307 // Switch to requested mode -- binds other click handlers
3308 this.switchToolbarMode(mode);
3313 // switchToolbarMode
3314 //______________________________________________________________________________
3315 // Update the toolbar for the given mode (changes navigation buttons)
3316 // $$$ we should soon split the toolbar out into its own module
3317 BookReader.prototype.switchToolbarMode = function(mode) {
3320 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3321 $('#BRtoolbar .BRtoolbarmode2').hide();
3322 $('#BRtoolbar .BRtoolbarmode3').hide();
3323 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
3324 } else if (2 == mode) {
3326 $('#BRtoolbar .BRtoolbarzoom').show().css('display', 'inline');
3327 $('#BRtoolbar .BRtoolbarmode1').hide();
3328 $('#BRtoolbar .BRtoolbarmode3').hide();
3329 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
3332 $('#BRtoolbar .BRtoolbarzoom').hide();
3333 $('#BRtoolbar .BRtoolbarmode2').hide();
3334 $('#BRtoolbar .BRtoolbarmode1').hide();
3335 $('#BRtoolbar .BRtoolbarmode3').show().css('display', 'inline');
3339 // bindToolbarNavHandlers
3340 //______________________________________________________________________________
3341 // Binds the toolbar handlers
3342 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
3344 var self = this; // closure
3346 jToolbar.find('.book_left').bind('click', function(e) {
3351 jToolbar.find('.book_right').bind('click', function(e) {
3356 jToolbar.find('.book_up').bind('click', function(e) {
3357 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3365 jToolbar.find('.book_down').bind('click', function(e) {
3366 if ($.inArray(self.mode, [self.constMode2up, self.constModeThumb]) >= 0) {
3374 jToolbar.find('.print').bind('click', function(e) {
3379 jToolbar.find('.embed').bind('click', function(e) {
3380 self.showEmbedCode();
3384 jToolbar.find('.play').bind('click', function(e) {
3389 jToolbar.find('.pause').bind('click', function(e) {
3394 jToolbar.find('.book_top').bind('click', function(e) {
3399 jToolbar.find('.book_bottom').bind('click', function(e) {
3404 jToolbar.find('.book_leftmost').bind('click', function(e) {
3409 jToolbar.find('.book_rightmost').bind('click', function(e) {
3415 // updateToolbarZoom(reduce)
3416 //______________________________________________________________________________
3417 // Update the displayed zoom factor based on reduction factor
3418 BookReader.prototype.updateToolbarZoom = function(reduce) {
3420 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3423 value = (100 / reduce).toFixed(2);
3424 // Strip trailing zeroes and decimal if all zeroes
3425 value = value.replace(/0+$/,'');
3426 value = value.replace(/\.$/,'');
3429 $('#BRzoom').text(value);
3432 // firstDisplayableIndex
3433 //______________________________________________________________________________
3434 // Returns the index of the first visible page, dependent on the mode.
3435 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3436 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3437 BookReader.prototype.firstDisplayableIndex = function() {
3438 if (this.mode != this.constMode2up) {
3442 if ('rl' != this.pageProgression) {
3444 if (this.getPageSide(0) == 'L') {
3451 if (this.getPageSide(0) == 'R') {
3459 // lastDisplayableIndex
3460 //______________________________________________________________________________
3461 // Returns the index of the last visible page, dependent on the mode.
3462 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3463 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3464 BookReader.prototype.lastDisplayableIndex = function() {
3466 var lastIndex = this.numLeafs - 1;
3468 if (this.mode != this.constMode2up) {
3472 if ('rl' != this.pageProgression) {
3474 if (this.getPageSide(lastIndex) == 'R') {
3477 return lastIndex + 1;
3481 if (this.getPageSide(lastIndex) == 'L') {
3484 return lastIndex + 1;
3489 // shortTitle(maximumCharacters)
3491 // Returns a shortened version of the title with the maximum number of characters
3492 BookReader.prototype.shortTitle = function(maximumCharacters) {
3493 if (this.bookTitle.length < maximumCharacters) {
3494 return this.bookTitle;
3497 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3502 // Parameter related functions
3504 // updateFromParams(params)
3506 // Update ourselves from the params object.
3508 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3509 BookReader.prototype.updateFromParams = function(params) {
3510 if ('undefined' != typeof(params.mode)) {
3511 this.switchMode(params.mode);
3515 if ('undefined' != typeof(params.searchTerm)) {
3516 if (this.searchTerm != params.searchTerm) {
3517 this.search(params.searchTerm);
3521 // $$$ process /zoom
3523 // We only respect page if index is not set
3524 if ('undefined' != typeof(params.index)) {
3525 if (params.index != this.currentIndex()) {
3526 this.jumpToIndex(params.index);
3528 } else if ('undefined' != typeof(params.page)) {
3529 // $$$ this assumes page numbers are unique
3530 if (params.page != this.getPageNum(this.currentIndex())) {
3531 this.jumpToPage(params.page);
3535 // $$$ process /region
3536 // $$$ process /highlight
3539 // paramsFromFragment(urlFragment)
3541 // Returns a object with configuration parametes from a URL fragment.
3543 // E.g paramsFromFragment(window.location.hash)
3544 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3545 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3549 // For convenience we allow an initial # character (as from window.location.hash)
3550 // but don't require it
3551 if (urlFragment.substr(0,1) == '#') {
3552 urlFragment = urlFragment.substr(1);
3555 // Simple #nn syntax
3556 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3557 if ( !isNaN(oldStyleLeafNum) ) {
3558 params.index = oldStyleLeafNum;
3560 // Done processing if using old-style syntax
3564 // Split into key-value pairs
3565 var urlArray = urlFragment.split('/');
3567 for (var i = 0; i < urlArray.length; i += 2) {
3568 urlHash[urlArray[i]] = urlArray[i+1];
3572 if ('1up' == urlHash['mode']) {
3573 params.mode = this.constMode1up;
3574 } else if ('2up' == urlHash['mode']) {
3575 params.mode = this.constMode2up;
3576 } else if ('thumb' == urlHash['mode']) {
3577 params.mode = this.constModeThumb;
3581 if ('undefined' != typeof(urlHash['page'])) {
3582 // page was set -- may not be int
3583 params.page = urlHash['page'];
3586 // $$$ process /region
3587 // $$$ process /search
3589 if (urlHash['search'] != undefined) {
3590 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3593 // $$$ process /highlight
3598 // paramsFromCurrent()
3600 // Create a params object from the current parameters.
3601 BookReader.prototype.paramsFromCurrent = function() {
3605 var index = this.currentIndex();
3606 var pageNum = this.getPageNum(index);
3607 if ((pageNum === 0) || pageNum) {
3608 params.page = pageNum;
3611 params.index = index;
3612 params.mode = this.mode;
3618 if (this.searchHighlightVisible()) {
3619 params.searchTerm = this.searchTerm;
3625 // fragmentFromParams(params)
3627 // Create a fragment string from the params object.
3628 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3629 BookReader.prototype.fragmentFromParams = function(params) {
3630 var separator = '/';
3634 if ('undefined' != typeof(params.page)) {
3635 fragments.push('page', params.page);
3637 // Don't have page numbering -- use index instead
3638 fragments.push('page', 'n' + params.index);
3645 if ('undefined' != typeof(params.mode)) {
3646 if (params.mode == this.constMode1up) {
3647 fragments.push('mode', '1up');
3648 } else if (params.mode == this.constMode2up) {
3649 fragments.push('mode', '2up');
3650 } else if (params.mode == this.constModeThumb) {
3651 fragments.push('mode', 'thumb');
3653 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3658 if (params.searchTerm) {
3659 fragments.push('search', params.searchTerm);
3662 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3665 // getPageIndex(pageNum)
3667 // Returns the *highest* index the given page number, or undefined
3668 BookReader.prototype.getPageIndex = function(pageNum) {
3669 var pageIndices = this.getPageIndices(pageNum);
3671 if (pageIndices.length > 0) {
3672 return pageIndices[pageIndices.length - 1];
3678 // getPageIndices(pageNum)
3680 // Returns an array (possibly empty) of the indices with the given page number
3681 BookReader.prototype.getPageIndices = function(pageNum) {
3684 // Check for special "nXX" page number
3685 if (pageNum.slice(0,1) == 'n') {
3687 var pageIntStr = pageNum.slice(1, pageNum.length);
3688 var pageIndex = parseInt(pageIntStr);
3689 indices.push(pageIndex);
3692 // Do nothing... will run through page names and see if one matches
3697 for (i=0; i<this.numLeafs; i++) {
3698 if (this.getPageNum(i) == pageNum) {
3706 // getPageName(index)
3708 // Returns the name of the page as it should be displayed in the user interface
3709 BookReader.prototype.getPageName = function(index) {
3710 return 'Page ' + this.getPageNum(index);
3713 // updateLocationHash
3715 // Update the location hash from the current parameters. Call this instead of manually
3716 // using window.location.replace
3717 BookReader.prototype.updateLocationHash = function() {
3718 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3719 window.location.replace(newHash);
3721 // This is the variable checked in the timer. Only user-generated changes
3722 // to the URL will trigger the event.
3723 this.oldLocationHash = newHash;
3726 // startLocationPolling
3728 // Starts polling of window.location to see hash fragment changes
3729 BookReader.prototype.startLocationPolling = function() {
3730 var self = this; // remember who I am
3731 self.oldLocationHash = window.location.hash;
3733 if (this.locationPollId) {
3734 clearInterval(this.locationPollID);
3735 this.locationPollId = null;
3738 this.locationPollId = setInterval(function() {
3739 var newHash = window.location.hash;
3740 if (newHash != self.oldLocationHash) {
3741 if (newHash != self.oldUserHash) { // Only process new user hash once
3742 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3744 // Queue change if animating
3745 if (self.animating) {
3747 self.animationFinishedCallback = function() {
3748 self.updateFromParams(self.paramsFromFragment(newHash));
3750 } else { // update immediately
3751 self.updateFromParams(self.paramsFromFragment(newHash));
3753 self.oldUserHash = newHash;
3761 // Returns true if we can switch to the requested mode
3762 BookReader.prototype.canSwitchToMode = function(mode) {
3763 if (mode == this.constMode2up) {
3764 // check there are enough pages to display
3765 // $$$ this is a workaround for the mis-feature that we can't display
3766 // short books in 2up mode
3767 if (this.numLeafs < 6) {
3775 // searchHighlightVisible
3777 // Returns true if a search highlight is currently being displayed
3778 BookReader.prototype.searchHighlightVisible = function() {
3779 if (this.constMode2up == this.mode) {
3780 if (this.searchResults[this.twoPage.currentIndexL]
3781 || this.searchResults[this.twoPage.currentIndexR]) {
3785 if (this.searchResults[this.currentIndex()]) {
3792 // getPageBackgroundColor
3794 // Returns a CSS property string for the background color for the given page
3795 // $$$ turn into regular CSS?
3796 BookReader.prototype.getPageBackgroundColor = function(index) {
3797 if (index >= 0 && index < this.numLeafs) {
3799 return this.pageDefaultBackgroundColor;
3807 // Returns the page width for the given index, or first or last page if out of range
3808 BookReader.prototype._getPageWidth = function(index) {
3809 // Synthesize a page width for pages not actually present in book.
3810 // May or may not be the best approach.
3811 // If index is out of range we return the width of first or last page
3812 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3813 return this.getPageWidth(index);
3818 // Returns the page height for the given index, or first or last page if out of range
3819 BookReader.prototype._getPageHeight= function(index) {
3820 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3821 return this.getPageHeight(index);
3826 // Returns the page URI or transparent image if out of range
3827 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3828 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3829 return this.imagesBaseURL + "/transparent.png";
3832 if ('undefined' == typeof(reduce)) {
3833 // reduce not passed in
3834 // $$$ this probably won't work for thumbnail mode
3835 var ratio = this.getPageHeight(index) / this.twoPage.height;
3837 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3840 } else if (ratio < 4) {
3842 } else if (ratio < 8) {
3844 } else if (ratio < 16) {
3846 } else if (ratio < 32) {
3854 return this.getPageURI(index, reduce, rotate);
3857 // Library functions
3859 disableSelect: function(jObject) {
3860 // Bind mouse handlers
3861 // Disable mouse click to avoid selected/highlighted page images - bug 354239
3862 jObject.bind('mousedown', function(e) {
3863 // $$$ check here for right-click and don't disable. Also use jQuery style
3864 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
3867 // Special hack for IE7
3868 jObject[0].onselectstart = function(e) { return false; };
3871 clamp: function(value, min, max) {
3872 return Math.min(Math.max(value, min), max);
3875 notInArray: function(value, array) {
3876 // inArray returns -1 or undefined if value not in array
3877 return ! (jQuery.inArray(value, array) >= 0);
3880 getIFrameDocument: function(iframe) {
3881 // Adapted from http://xkr.us/articles/dom/iframe-document/
3882 var outer = (iframe.contentWindow || iframe.contentDocument);
3883 return (outer.document || outer);
3886 decodeURIComponentPlus: function(value) {
3887 // Decodes a URI component and converts '+' to ' '
3888 return decodeURIComponent(value).replace(/\+/g, ' ');
3891 encodeURIComponentPlus: function(value) {
3892 // Encodes a URI component and converts ' ' to '+'
3893 return encodeURIComponent(value).replace(/%20/g, '+');
3895 // The final property here must NOT have a comma after it - IE7