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 or 2
42 this.ui = 'full'; // UI mode
44 this.displayedIndices = [];
45 //this.indicesToDisplay = [];
47 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
50 this.animating = false;
52 this.autoTimer = null;
53 this.flipSpeed = 'fast';
55 this.twoPagePopUp = null;
56 this.leafEdgeTmp = null;
57 this.embedPopup = null;
58 this.printPopup = null;
61 this.searchResults = {};
63 this.firstIndex = null;
65 this.lastDisplayableIndex2up = null;
67 // We link to index.php to avoid redirect which breaks back button
68 this.logoURL = 'http://www.archive.org/index.php';
70 // Base URL for images
71 this.imagesBaseURL = '/bookreader/images/';
74 this.constMode1up = 1;
75 this.constMode2up = 2;
78 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
80 // Object to hold parameters related to 2up mode
82 coverInternalPadding: 10, // Width of cover
83 coverExternalPadding: 10, // Padding outside of cover
84 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
88 // Background color for pages (e.g. when loading page image)
89 // $$$ TODO dynamically calculate based on page images
90 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
94 //______________________________________________________________________________
95 BookReader.prototype.init = function() {
97 var startIndex = undefined;
99 // Find start index and mode if set in location hash
100 var params = this.paramsFromFragment(window.location.hash);
102 if ('undefined' != typeof(params.index)) {
103 startIndex = params.index;
104 } else if ('undefined' != typeof(params.page)) {
105 startIndex = this.getPageIndex(params.page);
108 if ('undefined' == typeof(startIndex)) {
109 if ('undefined' != typeof(this.titleLeaf)) {
110 startIndex = this.leafNumToIndex(this.titleLeaf);
114 if ('undefined' == typeof(startIndex)) {
118 if ('undefined' != typeof(params.mode)) {
119 this.mode = params.mode;
122 // Set document title -- may have already been set in enclosing html for
123 // search engine visibility
124 document.title = this.shortTitle(50);
126 // Sanitize parameters
127 if ( !this.canSwitchToMode( this.mode ) ) {
128 this.mode = this.constMode1up;
131 $("#BookReader").empty();
132 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
133 $("#BookReader").append("<div id='BRcontainer'></div>");
134 $("#BRcontainer").append("<div id='BRpageview'></div>");
136 $("#BRcontainer").bind('scroll', this, function(e) {
140 this.setupKeyListeners();
141 this.startLocationPolling();
143 $(window).bind('resize', this, function(e) {
144 //console.log('resize!');
145 if (1 == e.data.mode) {
146 //console.log('centering 1page view');
147 e.data.centerPageView();
148 $('#BRpageview').empty()
149 e.data.displayedIndices = [];
150 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
153 //console.log('drawing 2 page view');
155 // We only need to prepare again in autofit (size of spread changes)
156 if (e.data.twoPage.autofit) {
157 e.data.prepareTwoPageView();
159 // Re-center if the scrollbars have disappeared
160 var center = e.data.twoPageGetViewCenter();
161 var doRecenter = false;
162 if (e.data.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
163 center.percentageX = 0.5;
166 if (e.data.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
167 center.percentageY = 0.5;
171 e.data.twoPageCenterView(center.percentageX, center.percentageY);
177 $('.BRpagediv1up').bind('mousedown', this, function(e) {
178 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
179 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
182 if (1 == this.mode) {
183 this.resizePageView();
184 this.firstIndex = startIndex;
185 this.jumpToIndex(startIndex);
187 //this.resizePageView();
189 this.displayedIndices=[0];
190 this.firstIndex = startIndex;
191 this.displayedIndices = [this.firstIndex];
192 //console.log('titleLeaf: %d', this.titleLeaf);
193 //console.log('displayedIndices: %s', this.displayedIndices);
194 this.prepareTwoPageView();
197 // Enact other parts of initial params
198 this.updateFromParams(params);
201 BookReader.prototype.setupKeyListeners = function() {
214 // We use document here instead of window to avoid a bug in jQuery on IE7
215 $(document).keydown(function(e) {
217 // Keyboard navigation
218 if (!self.keyboardNavigationIsDisabled(e)) {
222 // In 1up mode page scrolling is handled by browser
223 if (2 == self.mode) {
230 if (2 == self.mode) {
244 if (2 == self.mode) {
250 if (2 == self.mode) {
261 //______________________________________________________________________________
262 BookReader.prototype.drawLeafs = function() {
263 if (1 == this.mode) {
264 this.drawLeafsOnePage();
266 this.drawLeafsTwoPage();
271 //______________________________________________________________________________
272 BookReader.prototype.setDragHandler = function(div) {
273 div.dragging = false;
275 $(div).unbind('mousedown').bind('mousedown', function(e) {
278 //console.log('mousedown at ' + e.pageY);
280 this.dragging = true;
281 this.prevMouseX = e.pageX;
282 this.prevMouseY = e.pageY;
284 var startX = e.pageX;
285 var startY = e.pageY;
286 var startTop = $('#BRcontainer').attr('scrollTop');
287 var startLeft = $('#BRcontainer').attr('scrollLeft');
291 $(div).unbind('mousemove').bind('mousemove', function(ee) {
294 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
296 var offsetX = ee.pageX - this.prevMouseX;
297 var offsetY = ee.pageY - this.prevMouseY;
300 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
301 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
304 this.prevMouseX = ee.pageX;
305 this.prevMouseY = ee.pageY;
309 $(div).unbind('mouseup').bind('mouseup', function(ee) {
311 //console.log('mouseup');
313 this.dragging = false;
316 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
318 //console.log('mouseleave');
320 this.dragging = false;
323 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
325 //console.log('mouseenter');
327 this.dragging = false;
331 // setDragHandler2UP()
332 //______________________________________________________________________________
333 BookReader.prototype.setDragHandler2UP = function(div) {
334 div.dragging = false;
336 $(div).unbind('mousedown').bind('mousedown', function(e) {
339 //console.log('mousedown at ' + e.pageY);
341 this.dragStart = {x: e.pageX, y: e.pageY };
342 this.mouseDown = true;
343 this.dragging = false; // wait until drag distance
344 this.prevMouseX = e.pageX;
345 this.prevMouseY = e.pageY;
347 var startX = e.pageX;
348 var startY = e.pageY;
349 var startTop = $('#BRcontainer').attr('scrollTop');
350 var startLeft = $('#BRcontainer').attr('scrollLeft');
354 $(div).unbind('mousemove').bind('mousemove', function(ee) {
357 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
359 var offsetX = ee.pageX - this.prevMouseX;
360 var offsetY = ee.pageY - this.prevMouseY;
362 var minDragDistance = 5; // $$$ constant
364 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
366 if (this.mouseDown && (distance > minDragDistance)) {
367 //console.log('drag start!');
369 this.dragging = true;
373 $('#BRcontainer').attr('scrollTop', $('#BRcontainer').attr('scrollTop') - offsetY);
374 $('#BRcontainer').attr('scrollLeft', $('#BRcontainer').attr('scrollLeft') - offsetX);
375 this.prevMouseX = ee.pageX;
376 this.prevMouseY = ee.pageY;
383 $(div).unbind('mouseup').bind('mouseup', function(ee) {
385 //console.log('mouseup');
387 this.dragging = false;
388 this.mouseDown = false;
393 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
395 //console.log('mouseleave');
397 this.dragging = false;
398 this.mouseDown = false;
401 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
403 //console.log('mouseenter');
405 this.dragging = false;
406 this.mouseDown = false;
410 BookReader.prototype.setClickHandler2UP = function( element, data, handler) {
411 //console.log('setting handler');
412 //console.log(element.tagName);
414 $(element).unbind('click').bind('click', data, function(e) {
417 //console.log('click!');
419 if (this.mouseDown && (!this.dragging)) {
420 //console.log('click not dragging!');
424 this.dragging = false;
425 this.mouseDown = false;
429 // drawLeafsOnePage()
430 //______________________________________________________________________________
431 BookReader.prototype.drawLeafsOnePage = function() {
432 //alert('drawing leafs!');
436 var scrollTop = $('#BRcontainer').attr('scrollTop');
437 var scrollBottom = scrollTop + $('#BRcontainer').height();
438 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
440 var indicesToDisplay = [];
445 for (i=0; i<this.numLeafs; i++) {
446 var height = parseInt(this._getPageHeight(i)/this.reduce);
448 leafBottom += height;
449 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
450 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
451 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
452 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
453 if (topInView | bottomInView | middleInView) {
454 //console.log('displayed: ' + this.displayedIndices);
455 //console.log('to display: ' + i);
456 indicesToDisplay.push(i);
458 leafTop += height +10;
462 var firstIndexToDraw = indicesToDisplay[0];
463 this.firstIndex = firstIndexToDraw;
465 // Update hash, but only if we're currently displaying a leaf
466 // Hack that fixes #365790
467 if (this.displayedIndices.length > 0) {
468 this.updateLocationHash();
471 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
473 indicesToDisplay.unshift(firstIndexToDraw);
476 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
477 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
478 indicesToDisplay.push(lastIndexToDraw+1);
483 for (i=0; i<firstIndexToDraw; i++) {
484 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
487 //var viewWidth = $('#BRpageview').width(); //includes scroll bar width
488 var viewWidth = $('#BRcontainer').attr('scrollWidth');
491 for (i=0; i<indicesToDisplay.length; i++) {
492 var index = indicesToDisplay[i];
493 var height = parseInt(this._getPageHeight(index)/this.reduce);
495 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
496 var width = parseInt(this._getPageWidth(index)/this.reduce);
497 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
498 var div = document.createElement("div");
499 div.className = 'BRpagediv1up';
500 div.id = 'pagediv'+index;
501 div.style.position = "absolute";
502 $(div).css('top', leafTop + 'px');
503 var left = (viewWidth-width)>>1;
504 if (left<0) left = 0;
505 $(div).css('left', left+'px');
506 $(div).css('width', width+'px');
507 $(div).css('height', height+'px');
508 //$(div).text('loading...');
510 this.setDragHandler(div);
512 $('#BRpageview').append(div);
514 var img = document.createElement("img");
515 img.src = this._getPageURI(index, this.reduce, 0);
516 $(img).css('width', width+'px');
517 $(img).css('height', height+'px');
521 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
524 leafTop += height +10;
528 for (i=0; i<this.displayedIndices.length; i++) {
529 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
530 var index = this.displayedIndices[i];
531 //console.log('Removing leaf ' + index);
532 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
533 $('#pagediv'+index).remove();
535 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
539 this.displayedIndices = indicesToDisplay.slice();
540 this.updateSearchHilites();
542 if (null != this.getPageNum(firstIndexToDraw)) {
543 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
545 $("#BRpagenum").val('');
548 this.updateToolbarZoom(this.reduce);
552 // drawLeafsTwoPage()
553 //______________________________________________________________________________
554 BookReader.prototype.drawLeafsTwoPage = function() {
555 var scrollTop = $('#BRtwopageview').attr('scrollTop');
556 var scrollBottom = scrollTop + $('#BRtwopageview').height();
558 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
560 var indexL = this.twoPage.currentIndexL;
562 var heightL = this._getPageHeight(indexL);
563 var widthL = this._getPageWidth(indexL);
565 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
566 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
567 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
568 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
569 //console.log(leafEdgeWidthL);
571 var middle = this.twoPage.middle; // $$$ getter instead?
572 var top = this.twoPageTop();
573 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
575 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
576 this.twoPage.gutter = this.twoPageGutter();
578 this.prefetchImg(indexL);
579 $(this.prefetchedImgs[indexL]).css({
580 position: 'absolute',
581 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
584 backgroundColor: this.getPageBackgroundColor(indexL),
585 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
586 width: this.twoPage.scaledWL + 'px',
587 borderRight: '1px solid black',
589 }).appendTo('#BRtwopageview');
591 var indexR = this.twoPage.currentIndexR;
592 var heightR = this._getPageHeight(indexR);
593 var widthR = this._getPageWidth(indexR);
595 // $$$ should use getwidth2up?
596 //var scaledWR = this.twoPage.height*widthR/heightR;
597 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
598 this.prefetchImg(indexR);
599 $(this.prefetchedImgs[indexR]).css({
600 position: 'absolute',
601 left: this.twoPage.gutter+'px',
604 backgroundColor: this.getPageBackgroundColor(indexR),
605 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
606 width: this.twoPage.scaledWR + 'px',
607 borderLeft: '1px solid black',
609 }).appendTo('#BRtwopageview');
612 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
613 this.setMouseHandlers2UP();
614 this.twoPageSetCursor();
616 this.updatePageNumBox2UP();
617 this.updateToolbarZoom(this.reduce);
619 // this.twoPagePlaceFlipAreas(); // No longer used
623 // updatePageNumBox2UP
624 //______________________________________________________________________________
625 BookReader.prototype.updatePageNumBox2UP = function() {
626 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
627 $("#BRpagenum").val(this.getPageNum(this.currentIndex()));
629 $("#BRpagenum").val('');
631 this.updateLocationHash();
635 //______________________________________________________________________________
636 BookReader.prototype.loadLeafs = function() {
640 if (null == this.timer) {
641 this.timer=setTimeout(function(){self.drawLeafs()},250);
643 clearTimeout(this.timer);
644 this.timer=setTimeout(function(){self.drawLeafs()},250);
650 // Pass 1 to zoom in, anything else to zoom out
651 //______________________________________________________________________________
652 BookReader.prototype.zoom = function(direction) {
654 case this.constMode1up:
655 return this.zoom1up(direction);
656 case this.constMode2up:
657 return this.zoom2up(direction);
662 //______________________________________________________________________________
663 BookReader.prototype.zoom1up = function(dir) {
665 if (2 == this.mode) { //can only zoom in 1-page mode
670 // $$$ with flexible zoom we could "snap" to /2 page reductions
671 // for better scaling
673 if (this.reduce <= 0.5) return;
674 this.reduce*=0.5; //zoom in
676 if (this.reduce >= 8) return;
677 this.reduce*=2; //zoom out
680 this.resizePageView();
682 $('#BRpageview').empty()
683 this.displayedIndices = [];
686 this.updateToolbarZoom(this.reduce);
688 // Recalculate search hilites
689 this.removeSearchHilites();
690 this.updateSearchHilites();
695 //______________________________________________________________________________
696 BookReader.prototype.resizePageView = function() {
699 //var viewWidth = $('#BRcontainer').width(); //includes scrollBar
700 var viewWidth = $('#BRcontainer').attr('clientWidth');
702 var oldScrollTop = $('#BRcontainer').attr('scrollTop');
703 var oldScrollLeft = $('#BRcontainer').attr('scrollLeft');
704 var oldPageViewHeight = $('#BRpageview').height();
705 var oldPageViewWidth = $('#BRpageview').width();
707 var oldCenterY = this.centerY1up();
708 var oldCenterX = this.centerX1up();
710 if (0 != oldPageViewHeight) {
711 var scrollRatio = oldCenterY / oldPageViewHeight;
716 for (i=0; i<this.numLeafs; i++) {
717 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
718 var width = parseInt(this._getPageWidth(i)/this.reduce);
719 if (width>viewWidth) viewWidth=width;
721 $('#BRpageview').height(viewHeight);
722 $('#BRpageview').width(viewWidth);
724 var newCenterY = scrollRatio*viewHeight;
725 var newTop = Math.max(0, Math.floor( newCenterY - $('#BRcontainer').height()/2 ));
726 $('#BRcontainer').attr('scrollTop', newTop);
728 // We use clientWidth here to avoid miscalculating due to scroll bar
729 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
730 var newLeft = newCenterX - $('#BRcontainer').attr('clientWidth') / 2;
731 newLeft = Math.max(newLeft, 0);
732 $('#BRcontainer').attr('scrollLeft', newLeft);
733 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
735 //this.centerPageView();
738 // Not really needed until there is 1up autofit
739 this.removeSearchHilites();
740 this.updateSearchHilites();
744 //______________________________________________________________________________
745 // Returns the current offset of the viewport center in scaled document coordinates.
746 BookReader.prototype.centerX1up = function() {
748 if ($('#BRpageview').width() < $('#BRcontainer').attr('clientWidth')) { // fully shown
749 centerX = $('#BRpageview').width();
751 centerX = $('#BRcontainer').attr('scrollLeft') + $('#BRcontainer').attr('clientWidth') / 2;
753 centerX = Math.floor(centerX);
758 //______________________________________________________________________________
759 // Returns the current offset of the viewport center in scaled document coordinates.
760 BookReader.prototype.centerY1up = function() {
761 var centerY = $('#BRcontainer').attr('scrollTop') + $('#BRcontainer').height() / 2;
762 return Math.floor(centerY);
766 //______________________________________________________________________________
767 BookReader.prototype.centerPageView = function() {
769 var scrollWidth = $('#BRcontainer').attr('scrollWidth');
770 var clientWidth = $('#BRcontainer').attr('clientWidth');
771 //console.log('sW='+scrollWidth+' cW='+clientWidth);
772 if (scrollWidth > clientWidth) {
773 $('#BRcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
778 // zoom2up(direction)
779 //______________________________________________________________________________
780 BookReader.prototype.zoom2up = function(direction) {
782 // Hard stop autoplay
783 this.stopFlipAnimations();
785 // Get new zoom state
786 var newZoom = this.twoPageNextReduce(this.reduce, direction);
787 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
790 this.twoPage.autofit = newZoom.autofit;
791 this.reduce = newZoom.reduce;
793 // Preserve view center position
794 var oldCenter = this.twoPageGetViewCenter();
796 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
797 // $$$ An improvement would be to use the low res image until the larger one is loaded.
798 if (1 == direction) {
799 for (var img in this.prefetchedImgs) {
800 delete this.prefetchedImgs[img];
804 // Prepare view with new center to minimize visual glitches
805 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
809 // quantizeReduce(reduce)
810 //______________________________________________________________________________
811 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
812 BookReader.prototype.quantizeReduce = function(reduce) {
813 var quantized = this.reductionFactors[0];
814 var distance = Math.abs(reduce - quantized);
815 for (var i = 1; i < this.reductionFactors.length; i++) {
816 newDistance = Math.abs(reduce - this.reductionFactors[i]);
817 if (newDistance < distance) {
818 distance = newDistance;
819 quantized = this.reductionFactors[i];
826 // twoPageNextReduce()
827 //______________________________________________________________________________
828 // Returns the next reduction level
829 BookReader.prototype.twoPageNextReduce = function(reduce, direction) {
831 var autofitReduce = this.twoPageGetAutofitReduce();
833 if (0 == direction) { // autofit
834 result.autofit = true;
835 result.reduce = autofitReduce;
837 } else if (1 == direction) { // zoom in
838 var newReduce = this.reductionFactors[0];
840 for (var i = 1; i < this.reductionFactors.length; i++) {
841 if (this.reductionFactors[i] < reduce) {
842 newReduce = this.reductionFactors[i];
846 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
848 result.autofit = true;
849 result.reduce = autofitReduce;
851 result.autofit = false;
852 result.reduce = newReduce;
856 var lastIndex = this.reductionFactors.length - 1;
857 var newReduce = this.reductionFactors[lastIndex];
859 for (var i = lastIndex; i >= 0; i--) {
860 if (this.reductionFactors[i] > reduce) {
861 newReduce = this.reductionFactors[i];
865 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
867 result.autofit = true;
868 result.reduce = autofitReduce;
870 result.autofit = false;
871 result.reduce = newReduce;
879 //______________________________________________________________________________
880 // Attempts to jump to page. Returns true if page could be found, false otherwise.
881 BookReader.prototype.jumpToPage = function(pageNum) {
883 var pageIndex = this.getPageIndex(pageNum);
885 if ('undefined' != typeof(pageIndex)) {
888 this.jumpToIndex(pageIndex);
889 $('#BRcontainer').attr('scrollTop', leafTop);
898 //______________________________________________________________________________
899 BookReader.prototype.jumpToIndex = function(index, pageX, pageY) {
901 if (2 == this.mode) {
904 // By checking against min/max we do nothing if requested index
906 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
907 this.flipBackToIndex(index);
908 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
909 this.flipFwdToIndex(index);
917 for (i=0; i<index; i++) {
918 h = parseInt(this._getPageHeight(i)/this.reduce);
919 leafTop += h + this.padding;
923 //console.log('pageY ' + pageY);
924 var offset = parseInt( (pageY) / this.reduce);
925 offset -= $('#BRcontainer').attr('clientHeight') >> 1;
926 //console.log( 'jumping to ' + leafTop + ' ' + offset);
931 var offset = parseInt( (pageX) / this.reduce);
932 offset -= $('#BRcontainer').attr('clientWidth') >> 1;
936 //$('#BRcontainer').attr('scrollTop', leafTop);
937 $('#BRcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
943 //______________________________________________________________________________
944 BookReader.prototype.switchMode = function(mode) {
946 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
948 if (mode == this.mode) return;
950 if (!this.canSwitchToMode(mode)) {
955 this.removeSearchHilites();
959 this.switchToolbarMode(mode);
961 // $$$ TODO preserve center of view when switching between mode
962 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
965 this.reduce = this.quantizeReduce(this.reduce);
966 this.prepareOnePageView();
968 this.twoPage.autofit = false; // Take zoom level from other mode
969 this.reduce = this.quantizeReduce(this.reduce);
970 this.prepareTwoPageView();
971 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
976 //prepareOnePageView()
977 //______________________________________________________________________________
978 BookReader.prototype.prepareOnePageView = function() {
980 // var startLeaf = this.displayedIndices[0];
981 var startLeaf = this.currentIndex();
983 $('#BRcontainer').empty();
984 $('#BRcontainer').css({
989 var brPageView = $("#BRcontainer").append("<div id='BRpageview'></div>");
991 this.resizePageView();
993 this.jumpToIndex(startLeaf);
994 this.displayedIndices = [];
996 this.drawLeafsOnePage();
998 // Bind mouse handlers
999 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1000 brPageView.bind('mousedown', function(e) {
1001 // $$$ check here for right-click and don't disable. Also use jQuery style
1002 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1005 // Special hack for IE7
1006 brPageView[0].onselectstart = function(e) { return false; };
1009 // prepareTwoPageView()
1010 //______________________________________________________________________________
1011 // Some decisions about two page view:
1013 // Both pages will be displayed at the same height, even if they were different physical/scanned
1014 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1015 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1016 // aspect ratio to determine the height.
1018 // The two page view div is resized to keep the middle of the book in the middle of the div
1019 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the BRcontent
1020 // div requires adjusting the offset of BRtwpageview and/or scrolling in BRcontent.
1021 BookReader.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1022 $('#BRcontainer').empty();
1023 $('#BRcontainer').css('overflow', 'auto');
1025 // We want to display two facing pages. We may be missing
1026 // one side of the spread because it is the first/last leaf,
1027 // foldouts, missing pages, etc
1029 //var targetLeaf = this.displayedIndices[0];
1030 var targetLeaf = this.firstIndex;
1032 if (targetLeaf < this.firstDisplayableIndex()) {
1033 targetLeaf = this.firstDisplayableIndex();
1036 if (targetLeaf > this.lastDisplayableIndex()) {
1037 targetLeaf = this.lastDisplayableIndex();
1040 //this.twoPage.currentIndexL = null;
1041 //this.twoPage.currentIndexR = null;
1042 //this.pruneUnusedImgs();
1044 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1045 this.twoPage.currentIndexL = currentSpreadIndices[0];
1046 this.twoPage.currentIndexR = currentSpreadIndices[1];
1047 this.firstIndex = this.twoPage.currentIndexL;
1049 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1051 this.pruneUnusedImgs();
1052 this.prefetch(); // Preload images or reload if scaling has changed
1054 //console.dir(this.twoPage);
1056 // Add the two page view
1057 // $$$ Can we get everything set up and then append?
1058 $('#BRcontainer').append('<div id="BRtwopageview"></div>');
1060 // $$$ calculate first then set
1061 $('#BRtwopageview').css( {
1062 height: this.twoPage.totalHeight + 'px',
1063 width: this.twoPage.totalWidth + 'px',
1064 position: 'absolute'
1067 // If there will not be scrollbars (e.g. when zooming out) we center the book
1068 // since otherwise the book will be stuck off-center
1069 if (this.twoPage.totalWidth < $('#BRcontainer').attr('clientWidth')) {
1070 centerPercentageX = 0.5;
1072 if (this.twoPage.totalHeight < $('#BRcontainer').attr('clientHeight')) {
1073 centerPercentageY = 0.5;
1076 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1078 this.twoPage.coverDiv = document.createElement('div');
1079 $(this.twoPage.coverDiv).attr('id', 'BRbookcover').css({
1080 border: '1px solid rgb(68, 25, 17)',
1081 width: this.twoPage.bookCoverDivWidth + 'px',
1082 height: this.twoPage.bookCoverDivHeight+'px',
1083 visibility: 'visible',
1084 position: 'absolute',
1085 backgroundColor: '#663929',
1086 left: this.twoPage.bookCoverDivLeft + 'px',
1087 top: this.twoPage.bookCoverDivTop+'px',
1088 MozBorderRadiusTopleft: '7px',
1089 MozBorderRadiusTopright: '7px',
1090 MozBorderRadiusBottomright: '7px',
1091 MozBorderRadiusBottomleft: '7px'
1092 }).appendTo('#BRtwopageview');
1094 this.leafEdgeR = document.createElement('div');
1095 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1096 $(this.leafEdgeR).css({
1097 borderStyle: 'solid solid solid none',
1098 borderColor: 'rgb(51, 51, 34)',
1099 borderWidth: '1px 1px 1px 0px',
1100 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1101 width: this.twoPage.leafEdgeWidthR + 'px',
1102 height: this.twoPage.height-1 + 'px',
1104 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1105 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1106 position: 'absolute'
1107 }).appendTo('#BRtwopageview');
1109 this.leafEdgeL = document.createElement('div');
1110 this.leafEdgeL.className = 'leafEdgeL';
1111 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1112 borderStyle: 'solid none solid solid',
1113 borderColor: 'rgb(51, 51, 34)',
1114 borderWidth: '1px 0px 1px 1px',
1115 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1116 width: this.twoPage.leafEdgeWidthL + 'px',
1117 height: this.twoPage.height-1 + 'px',
1118 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1119 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1120 position: 'absolute'
1121 }).appendTo('#BRtwopageview');
1123 div = document.createElement('div');
1124 $(div).attr('id', 'BRbookspine').css({
1125 border: '1px solid rgb(68, 25, 17)',
1126 width: this.twoPage.bookSpineDivWidth+'px',
1127 height: this.twoPage.bookSpineDivHeight+'px',
1128 position: 'absolute',
1129 backgroundColor: 'rgb(68, 25, 17)',
1130 left: this.twoPage.bookSpineDivLeft+'px',
1131 top: this.twoPage.bookSpineDivTop+'px'
1132 }).appendTo('#BRtwopageview');
1134 var self = this; // for closure
1136 /* Flip areas no longer used
1137 this.twoPage.leftFlipArea = document.createElement('div');
1138 this.twoPage.leftFlipArea.className = 'BRfliparea';
1139 $(this.twoPage.leftFlipArea).attr('id', 'BRleftflip').css({
1141 width: this.twoPageFlipAreaWidth() + 'px',
1142 height: this.twoPageFlipAreaHeight() + 'px',
1143 position: 'absolute',
1144 left: this.twoPageLeftFlipAreaLeft() + 'px',
1145 top: this.twoPageFlipAreaTop() + 'px',
1148 }).bind('click', function(e) {
1150 }).bind('mousedown', function(e) {
1152 }).appendTo('#BRtwopageview');
1154 this.twoPage.rightFlipArea = document.createElement('div');
1155 this.twoPage.rightFlipArea.className = 'BRfliparea';
1156 $(this.twoPage.rightFlipArea).attr('id', 'BRrightflip').css({
1158 width: this.twoPageFlipAreaWidth() + 'px',
1159 height: this.twoPageFlipAreaHeight() + 'px',
1160 position: 'absolute',
1161 left: this.twoPageRightFlipAreaLeft() + 'px',
1162 top: this.twoPageFlipAreaTop() + 'px',
1165 }).bind('click', function(e) {
1167 }).bind('mousedown', function(e) {
1169 }).appendTo('#BRtwopageview');
1172 this.prepareTwoPagePopUp();
1174 this.displayedIndices = [];
1176 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1177 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1179 this.drawLeafsTwoPage();
1180 this.updateToolbarZoom(this.reduce);
1184 this.removeSearchHilites();
1185 this.updateSearchHilites();
1189 // prepareTwoPagePopUp()
1191 // This function prepares the "View Page n" popup that shows while the mouse is
1192 // over the left/right "stack of sheets" edges. It also binds the mouse
1193 // events for these divs.
1194 //______________________________________________________________________________
1195 BookReader.prototype.prepareTwoPagePopUp = function() {
1197 this.twoPagePopUp = document.createElement('div');
1198 $(this.twoPagePopUp).css({
1199 border: '1px solid black',
1201 position: 'absolute',
1202 fontFamily: 'sans-serif',
1205 backgroundColor: 'rgb(255, 255, 238)',
1207 }).appendTo('#BRcontainer');
1208 $(this.twoPagePopUp).hide();
1210 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1211 $(e.data.twoPagePopUp).show();
1214 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1215 $(e.data.twoPagePopUp).hide();
1218 $(this.leafEdgeL).bind('click', this, function(e) {
1220 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1221 e.data.jumpToIndex(jumpIndex);
1224 $(this.leafEdgeR).bind('click', this, function(e) {
1226 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1227 e.data.jumpToIndex(jumpIndex);
1230 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1232 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1233 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1235 // $$$ TODO: Make sure popup is positioned so that it is in view
1236 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1237 $(e.data.twoPagePopUp).css({
1238 left: e.pageX- $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() + 20 + 'px',
1239 top: e.pageY - $('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1243 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1245 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1246 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1248 // $$$ TODO: Make sure popup is positioned so that it is in view
1249 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1250 $(e.data.twoPagePopUp).css({
1251 left: e.pageX - $('#BRcontainer').offset().left + $('#BRcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1252 top: e.pageY-$('#BRcontainer').offset().top + $('#BRcontainer').scrollTop() + 'px'
1257 // calculateSpreadSize()
1258 //______________________________________________________________________________
1259 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1260 // this.twoPage.currentIndexR
1261 // This function sets this.twoPage.height, twoPage.width
1263 BookReader.prototype.calculateSpreadSize = function() {
1265 var firstIndex = this.twoPage.currentIndexL;
1266 var secondIndex = this.twoPage.currentIndexR;
1267 //console.log('first page is ' + firstIndex);
1269 // Calculate page sizes and total leaf width
1271 if ( this.twoPage.autofit) {
1272 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1274 // set based on reduction factor
1275 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1278 // Both pages together
1279 this.twoPage.height = spreadSize.height;
1280 this.twoPage.width = spreadSize.width;
1283 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1284 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1287 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1288 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1289 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1293 // The width of the book cover div. The combined width of both pages, twice the width
1294 // of the book cover internal padding (2*10) and the page edges
1295 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1296 // The height of the book cover div
1297 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1300 // We calculate the total width and height for the div so that we can make the book
1302 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1303 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1304 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1305 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1306 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1307 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1309 // We want to minimize the unused space in two-up mode (maximize the amount of page
1310 // shown). We give width to the leaf edges and these widths change (though the sum
1311 // of the two remains constant) as we flip through the book. With the book
1312 // cover centered and fixed in the BRcontainer div the page images will meet
1313 // at the "gutter" which is generally offset from the center.
1314 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1315 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1317 // The left edge of the book cover moves depending on the width of the pages
1318 // $$$ change to getter
1319 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1320 // The top edge of the book cover stays a fixed distance from the top
1321 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1324 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1325 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1326 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1329 this.reduce = spreadSize.reduce; // $$$ really set this here?
1332 BookReader.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1335 // We check which page is closest to a "normal" page and use that to set the height
1336 // for both pages. This means that foldouts and other odd size pages will be displayed
1337 // smaller than the nominal zoom amount.
1338 var canon5Dratio = 1.5;
1341 height: this._getPageHeight(firstIndex),
1342 width: this._getPageWidth(firstIndex)
1346 height: this._getPageHeight(secondIndex),
1347 width: this._getPageWidth(secondIndex)
1350 var firstIndexRatio = first.height / first.width;
1351 var secondIndexRatio = second.height / second.width;
1352 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1355 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1356 ratio = firstIndexRatio;
1357 //console.log('using firstIndexRatio ' + ratio);
1359 ratio = secondIndexRatio;
1360 //console.log('using secondIndexRatio ' + ratio);
1363 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1364 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1);
1365 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1367 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1368 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1370 ideal.width = ($('#BRcontainer').width() - widthOutsidePages) >> 1;
1371 ideal.width -= 10; // $$$ fudge factor
1372 ideal.height = $('#BRcontainer').height() - heightOutsidePages;
1373 ideal.height -= 20; // fudge factor
1374 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1376 if (ideal.height/ratio <= ideal.width) {
1378 ideal.width = parseInt(ideal.height/ratio);
1381 ideal.height = parseInt(ideal.width*ratio);
1384 // $$$ check this logic with large spreads
1385 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1390 // getSpreadSizeFromReduce()
1391 //______________________________________________________________________________
1392 // Returns the spread size calculated from the reduction factor for the given pages
1393 BookReader.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1394 var spreadSize = {};
1395 // $$$ Scale this based on reduce?
1396 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1397 var maxLeafEdgeWidth = parseInt($('#BRcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1398 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1400 // $$$ Possibly incorrect -- we should make height "dominant"
1401 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1402 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1403 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1404 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1405 spreadSize.reduce = reduce;
1410 // twoPageGetAutofitReduce()
1411 //______________________________________________________________________________
1412 // Returns the current ideal reduction factor
1413 BookReader.prototype.twoPageGetAutofitReduce = function() {
1414 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1415 return spreadSize.reduce;
1418 // twoPageSetCursor()
1419 //______________________________________________________________________________
1420 // Set the cursor for two page view
1421 BookReader.prototype.twoPageSetCursor = function() {
1422 // console.log('setting cursor');
1423 if ( ($('#BRtwopageview').width() > $('#BRcontainer').attr('clientWidth')) ||
1424 ($('#BRtwopageview').height() > $('#BRcontainer').attr('clientHeight')) ) {
1425 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1426 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1428 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1429 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1434 //______________________________________________________________________________
1435 // Returns the currently active index.
1436 BookReader.prototype.currentIndex = function() {
1437 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1438 if (this.mode == this.constMode1up) {
1439 return this.firstIndex; // $$$ TODO page in center of view would be better
1440 } else if (this.mode == this.constMode2up) {
1441 // Only allow indices that are actually present in book
1442 return BookReader.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1444 throw 'currentIndex called for unimplemented mode ' + this.mode;
1449 //______________________________________________________________________________
1450 // Flip the right page over onto the left
1451 BookReader.prototype.right = function() {
1452 if ('rl' != this.pageProgression) {
1462 //______________________________________________________________________________
1463 // Flip to the rightmost page
1464 BookReader.prototype.rightmost = function() {
1465 if ('rl' != this.pageProgression) {
1473 //______________________________________________________________________________
1474 // Flip the left page over onto the right.
1475 BookReader.prototype.left = function() {
1476 if ('rl' != this.pageProgression) {
1486 //______________________________________________________________________________
1487 // Flip to the leftmost page
1488 BookReader.prototype.leftmost = function() {
1489 if ('rl' != this.pageProgression) {
1497 //______________________________________________________________________________
1498 BookReader.prototype.next = function() {
1499 if (2 == this.mode) {
1501 this.flipFwdToIndex(null);
1503 if (this.firstIndex < this.lastDisplayableIndex()) {
1504 this.jumpToIndex(this.firstIndex+1);
1510 //______________________________________________________________________________
1511 BookReader.prototype.prev = function() {
1512 if (2 == this.mode) {
1514 this.flipBackToIndex(null);
1516 if (this.firstIndex >= 1) {
1517 this.jumpToIndex(this.firstIndex-1);
1522 BookReader.prototype.first = function() {
1523 this.jumpToIndex(this.firstDisplayableIndex());
1526 BookReader.prototype.last = function() {
1527 this.jumpToIndex(this.lastDisplayableIndex());
1530 // flipBackToIndex()
1531 //______________________________________________________________________________
1532 // to flip back one spread, pass index=null
1533 BookReader.prototype.flipBackToIndex = function(index) {
1535 if (1 == this.mode) return;
1537 var leftIndex = this.twoPage.currentIndexL;
1539 if (this.animating) return;
1541 if (null != this.leafEdgeTmp) {
1542 alert('error: leafEdgeTmp should be null!');
1546 if (null == index) {
1547 index = leftIndex-2;
1549 //if (index<0) return;
1551 var previousIndices = this.getSpreadIndices(index);
1553 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1557 this.animating = true;
1559 if ('rl' != this.pageProgression) {
1560 // Assume LTR and we are going backward
1561 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1562 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1564 // RTL and going backward
1565 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1566 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1570 // flipLeftToRight()
1571 //______________________________________________________________________________
1572 // Flips the page on the left towards the page on the right
1573 BookReader.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1575 var leftLeaf = this.twoPage.currentIndexL;
1577 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1578 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1579 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1581 var currWidthL = this.getPageWidth2UP(leftLeaf);
1582 var newWidthL = this.getPageWidth2UP(newIndexL);
1583 var newWidthR = this.getPageWidth2UP(newIndexR);
1585 var top = this.twoPageTop();
1586 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1588 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1589 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1591 //animation strategy:
1592 // 0. remove search highlight, if any.
1593 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1594 // of the left leaf and where the user clicked in the leaf edge.
1595 // Note that if this function was triggered by left() and not a
1596 // mouse click, the width of leafEdgeTmp is very small (zero px).
1597 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1598 // leftLeaf to width=0.
1599 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1600 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1601 // its new full width.
1602 // 4. After step 3 is finished, do the following:
1603 // - remove leafEdgeTmp from the dom.
1604 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1605 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1606 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1607 // and width=newLeafEdgeWidthL.
1608 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1609 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1610 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1611 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1612 // - prefetch new adjacent leafs.
1613 // - set up click handlers for both new left and right leafs.
1614 // - redraw the search highlight.
1615 // - update the pagenum box and the url.
1618 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1620 this.leafEdgeTmp = document.createElement('div');
1621 $(this.leafEdgeTmp).css({
1622 borderStyle: 'solid none solid solid',
1623 borderColor: 'rgb(51, 51, 34)',
1624 borderWidth: '1px 0px 1px 1px',
1625 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1626 width: leafEdgeTmpW + 'px',
1627 height: this.twoPage.height-1 + 'px',
1628 left: leftEdgeTmpLeft + 'px',
1630 position: 'absolute',
1632 }).appendTo('#BRtwopageview');
1634 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1635 $(this.leafEdgeL).css({
1636 width: newLeafEdgeWidthL+'px',
1637 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1640 // Left gets the offset of the current left leaf from the document
1641 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1642 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1643 var right = $('#BRtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#BRtwopageview').offset().left-2+'px';
1645 // We change the left leaf to right positioning
1646 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1647 $(this.prefetchedImgs[leftLeaf]).css({
1652 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1653 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1657 this.removeSearchHilites();
1659 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1660 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1662 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1663 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1665 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1666 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1667 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1669 $(self.leafEdgeR).css({
1670 // Moves the right leaf edge
1671 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1672 left: gutter+newWidthR+'px'
1675 $(self.leafEdgeL).css({
1676 // Moves and resizes the left leaf edge
1677 width: newLeafEdgeWidthL+'px',
1678 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1681 // Resizes the brown border div
1682 $(self.twoPage.coverDiv).css({
1683 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1684 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1687 $(self.leafEdgeTmp).remove();
1688 self.leafEdgeTmp = null;
1690 // $$$ TODO refactor with opposite direction flip
1692 self.twoPage.currentIndexL = newIndexL;
1693 self.twoPage.currentIndexR = newIndexR;
1694 self.twoPage.scaledWL = newWidthL;
1695 self.twoPage.scaledWR = newWidthR;
1696 self.twoPage.gutter = gutter;
1698 self.firstIndex = self.twoPage.currentIndexL;
1699 self.displayedIndices = [newIndexL, newIndexR];
1700 self.pruneUnusedImgs();
1702 self.animating = false;
1704 self.updateSearchHilites2UP();
1705 self.updatePageNumBox2UP();
1707 // self.twoPagePlaceFlipAreas(); // No longer used
1708 self.setMouseHandlers2UP();
1709 self.twoPageSetCursor();
1711 if (self.animationFinishedCallback) {
1712 self.animationFinishedCallback();
1713 self.animationFinishedCallback = null;
1721 //______________________________________________________________________________
1722 // Whether we flip left or right is dependent on the page progression
1723 // to flip forward one spread, pass index=null
1724 BookReader.prototype.flipFwdToIndex = function(index) {
1726 if (this.animating) return;
1728 if (null != this.leafEdgeTmp) {
1729 alert('error: leafEdgeTmp should be null!');
1733 if (null == index) {
1734 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1736 if (index > this.lastDisplayableIndex()) return;
1738 this.animating = true;
1740 var nextIndices = this.getSpreadIndices(index);
1742 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1744 if ('rl' != this.pageProgression) {
1745 // We did not specify RTL
1746 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1747 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1750 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1751 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1755 // flipRightToLeft(nextL, nextR, gutter)
1756 // $$$ better not to have to pass gutter in
1757 //______________________________________________________________________________
1758 // Flip from left to right and show the nextL and nextR indices on those sides
1759 BookReader.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1760 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1761 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1762 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1763 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1765 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1767 var top = this.twoPageTop();
1768 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1770 var middle = this.twoPage.middle;
1771 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1773 this.leafEdgeTmp = document.createElement('div');
1774 $(this.leafEdgeTmp).css({
1775 borderStyle: 'solid none solid solid',
1776 borderColor: 'rgb(51, 51, 34)',
1777 borderWidth: '1px 0px 1px 1px',
1778 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1779 width: leafEdgeTmpW + 'px',
1780 height: this.twoPage.height-1 + 'px',
1781 left: gutter+scaledW+'px',
1783 position: 'absolute',
1785 }).appendTo('#BRtwopageview');
1787 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1788 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1790 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1791 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1792 var newWidthL = this.getPageWidth2UP(newIndexL);
1793 var newWidthR = this.getPageWidth2UP(newIndexR);
1795 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1797 var self = this; // closure-tastic!
1799 var speed = this.flipSpeed;
1801 this.removeSearchHilites();
1803 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1804 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1805 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1806 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1807 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1809 $(self.leafEdgeL).css({
1810 width: newLeafEdgeWidthL+'px',
1811 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1814 // Resizes the book cover
1815 $(self.twoPage.coverDiv).css({
1816 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1817 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1820 $(self.leafEdgeTmp).remove();
1821 self.leafEdgeTmp = null;
1823 self.twoPage.currentIndexL = newIndexL;
1824 self.twoPage.currentIndexR = newIndexR;
1825 self.twoPage.scaledWL = newWidthL;
1826 self.twoPage.scaledWR = newWidthR;
1827 self.twoPage.gutter = gutter;
1829 self.firstIndex = self.twoPage.currentIndexL;
1830 self.displayedIndices = [newIndexL, newIndexR];
1831 self.pruneUnusedImgs();
1833 self.animating = false;
1836 self.updateSearchHilites2UP();
1837 self.updatePageNumBox2UP();
1839 // self.twoPagePlaceFlipAreas(); // No longer used
1840 self.setMouseHandlers2UP();
1841 self.twoPageSetCursor();
1843 if (self.animationFinishedCallback) {
1844 self.animationFinishedCallback();
1845 self.animationFinishedCallback = null;
1851 // setMouseHandlers2UP
1852 //______________________________________________________________________________
1853 BookReader.prototype.setMouseHandlers2UP = function() {
1855 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1860 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1867 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
1868 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
1875 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
1876 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
1879 e.data.self.right();
1885 //______________________________________________________________________________
1886 BookReader.prototype.prefetchImg = function(index) {
1887 var pageURI = this._getPageURI(index);
1889 // Load image if not loaded or URI has changed (e.g. due to scaling)
1890 var loadImage = false;
1891 if (undefined == this.prefetchedImgs[index]) {
1892 //console.log('no image for ' + index);
1894 } else if (pageURI != this.prefetchedImgs[index].uri) {
1895 //console.log('uri changed for ' + index);
1900 //console.log('prefetching ' + index);
1901 var img = document.createElement("img");
1903 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1904 this.prefetchedImgs[index] = img;
1909 // prepareFlipLeftToRight()
1911 //______________________________________________________________________________
1913 // Prepare to flip the left page towards the right. This corresponds to moving
1914 // backward when the page progression is left to right.
1915 BookReader.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1917 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1919 this.prefetchImg(prevL);
1920 this.prefetchImg(prevR);
1922 var height = this._getPageHeight(prevL);
1923 var width = this._getPageWidth(prevL);
1924 var middle = this.twoPage.middle;
1925 var top = this.twoPageTop();
1926 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1928 // The gutter is the dividing line between the left and right pages.
1929 // It is offset from the middle to create the illusion of thickness to the pages
1930 var gutter = middle + this.gutterOffsetForIndex(prevL);
1932 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1933 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1934 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1937 position: 'absolute',
1938 left: gutter-scaledW+'px',
1939 right: '', // clear right property
1941 height: this.twoPage.height,
1942 width: scaledW+'px',
1943 backgroundColor: this.getPageBackgroundColor(prevL),
1944 borderRight: '1px solid black',
1948 $(this.prefetchedImgs[prevL]).css(leftCSS);
1950 $('#BRtwopageview').append(this.prefetchedImgs[prevL]);
1952 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1955 position: 'absolute',
1959 height: this.twoPage.height,
1961 backgroundColor: this.getPageBackgroundColor(prevR),
1962 borderLeft: '1px solid black',
1966 $(this.prefetchedImgs[prevR]).css(rightCSS);
1968 $('#BRtwopageview').append(this.prefetchedImgs[prevR]);
1972 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1973 // prepareFlipRightToLeft()
1974 //______________________________________________________________________________
1975 BookReader.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1977 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1980 this.prefetchImg(nextL);
1981 this.prefetchImg(nextR);
1983 var height = this._getPageHeight(nextR);
1984 var width = this._getPageWidth(nextR);
1985 var middle = this.twoPage.middle;
1986 var top = this.twoPageTop();
1987 var scaledW = this.twoPage.height*width/height;
1989 var gutter = middle + this.gutterOffsetForIndex(nextL);
1991 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1992 $(this.prefetchedImgs[nextR]).css({
1993 position: 'absolute',
1996 backgroundColor: this.getPageBackgroundColor(nextR),
1997 height: this.twoPage.height,
1998 width: scaledW+'px',
1999 borderLeft: '1px solid black',
2003 $('#BRtwopageview').append(this.prefetchedImgs[nextR]);
2005 height = this._getPageHeight(nextL);
2006 width = this._getPageWidth(nextL);
2007 scaledW = this.twoPage.height*width/height;
2009 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#BRcontainer').width()-gutter);
2010 $(this.prefetchedImgs[nextL]).css({
2011 position: 'absolute',
2012 right: $('#BRtwopageview').attr('clientWidth')-gutter+'px',
2014 backgroundColor: this.getPageBackgroundColor(nextL),
2015 height: this.twoPage.height,
2016 width: 0+'px', // Start at 0 width, then grow to the left
2017 borderRight: '1px solid black',
2021 $('#BRtwopageview').append(this.prefetchedImgs[nextL]);
2025 // getNextLeafs() -- NOT RTL AWARE
2026 //______________________________________________________________________________
2027 // BookReader.prototype.getNextLeafs = function(o) {
2028 // //TODO: we might have two left or two right leafs in a row (damaged book)
2029 // //For now, assume that leafs are contiguous.
2031 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2032 // o.L = this.twoPage.currentIndexL+2;
2033 // o.R = this.twoPage.currentIndexL+3;
2036 // getprevLeafs() -- NOT RTL AWARE
2037 //______________________________________________________________________________
2038 // BookReader.prototype.getPrevLeafs = function(o) {
2039 // //TODO: we might have two left or two right leafs in a row (damaged book)
2040 // //For now, assume that leafs are contiguous.
2042 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2043 // o.L = this.twoPage.currentIndexL-2;
2044 // o.R = this.twoPage.currentIndexL-1;
2047 // pruneUnusedImgs()
2048 //______________________________________________________________________________
2049 BookReader.prototype.pruneUnusedImgs = function() {
2050 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2051 for (var key in this.prefetchedImgs) {
2052 //console.log('key is ' + key);
2053 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2054 //console.log('removing key '+ key);
2055 $(this.prefetchedImgs[key]).remove();
2057 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2058 //console.log('deleting key '+ key);
2059 delete this.prefetchedImgs[key];
2065 //______________________________________________________________________________
2066 BookReader.prototype.prefetch = function() {
2068 // prefetch visible pages first
2069 this.prefetchImg(this.twoPage.currentIndexL);
2070 this.prefetchImg(this.twoPage.currentIndexR);
2072 var adjacentPagesToLoad = 3;
2074 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2075 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2077 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2078 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2080 // Load images spreading out from current
2081 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2082 var goingDown = lowCurrent - i;
2083 if (goingDown >= start) {
2084 this.prefetchImg(goingDown);
2086 var goingUp = highCurrent + i;
2087 if (goingUp <= end) {
2088 this.prefetchImg(goingUp);
2093 var lim = this.twoPage.currentIndexL-4;
2095 lim = Math.max(lim, 0);
2096 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2097 this.prefetchImg(i);
2100 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2101 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2102 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2103 this.prefetchImg(i);
2109 // getPageWidth2UP()
2110 //______________________________________________________________________________
2111 BookReader.prototype.getPageWidth2UP = function(index) {
2112 // We return the width based on the dominant height
2113 var height = this._getPageHeight(index);
2114 var width = this._getPageWidth(index);
2115 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2119 //______________________________________________________________________________
2120 BookReader.prototype.search = function(term) {
2121 term = term.replace(/\//g, ' '); // strip slashes
2122 this.searchTerm = term;
2123 $('#BookReaderSearchScript').remove();
2124 var script = document.createElement("script");
2125 script.setAttribute('id', 'BookReaderSearchScript');
2126 script.setAttribute("type", "text/javascript");
2127 script.setAttribute("src", 'http://'+this.server+'/BookReader/flipbook_search_br.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=br.BRSearchCallback');
2128 document.getElementsByTagName('head')[0].appendChild(script);
2129 $('#BookReaderSearchBox').val(term);
2130 $('#BookReaderSearchResults').html('Searching...');
2133 // BRSearchCallback()
2134 //______________________________________________________________________________
2135 BookReader.prototype.BRSearchCallback = function(txt) {
2137 if (jQuery.browser.msie) {
2138 var dom=new ActiveXObject("Microsoft.XMLDOM");
2142 var parser = new DOMParser();
2143 var dom = parser.parseFromString(txt, "text/xml");
2146 $('#BookReaderSearchResults').empty();
2147 $('#BookReaderSearchResults').append('<ul>');
2149 for (var key in this.searchResults) {
2150 if (null != this.searchResults[key].div) {
2151 $(this.searchResults[key].div).remove();
2153 delete this.searchResults[key];
2156 var pages = dom.getElementsByTagName('PAGE');
2158 if (0 == pages.length) {
2159 // $$$ it would be nice to echo the (sanitized) search result here
2160 $('#BookReaderSearchResults').append('<li>No search results found</li>');
2162 for (var i = 0; i < pages.length; i++){
2163 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2166 var re = new RegExp (/_(\d{4})\.djvu/);
2167 var reMatch = re.exec(pages[i].getAttribute('file'));
2168 var index = parseInt(reMatch[1], 10);
2169 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2171 var children = pages[i].childNodes;
2173 for (var j=0; j<children.length; j++) {
2174 //console.log(j + ' - ' + children[j].nodeName);
2175 //console.log(children[j].firstChild.nodeValue);
2176 if ('CONTEXT' == children[j].nodeName) {
2177 context += children[j].firstChild.nodeValue;
2178 } else if ('WORD' == children[j].nodeName) {
2179 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2181 var index = this.leafNumToIndex(index);
2182 if (null != index) {
2183 //coordinates are [left, bottom, right, top, [baseline]]
2184 //we'll skip baseline for now...
2185 var coords = children[j].getAttribute('coords').split(',',4);
2186 if (4 == coords.length) {
2187 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2192 var pageName = this.getPageName(index);
2193 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2194 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2195 //TODO: remove hardcoded instance name
2196 $('#BookReaderSearchResults').append('<li><b><a href="javascript:br.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2199 $('#BookReaderSearchResults').append('</ul>');
2201 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2202 $('#BookReaderSearchBox').val(this.searchTerm);
2204 this.updateSearchHilites();
2207 // updateSearchHilites()
2208 //______________________________________________________________________________
2209 BookReader.prototype.updateSearchHilites = function() {
2210 if (2 == this.mode) {
2211 this.updateSearchHilites2UP();
2213 this.updateSearchHilites1UP();
2217 // showSearchHilites1UP()
2218 //______________________________________________________________________________
2219 BookReader.prototype.updateSearchHilites1UP = function() {
2221 for (var key in this.searchResults) {
2223 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2224 var result = this.searchResults[key];
2225 if(null == result.div) {
2226 result.div = document.createElement('div');
2227 $(result.div).attr('className', 'BookReaderSearchHilite').appendTo('#pagediv'+key);
2228 //console.log('appending ' + key);
2231 width: (result.r-result.l)/this.reduce + 'px',
2232 height: (result.b-result.t)/this.reduce + 'px',
2233 left: (result.l)/this.reduce + 'px',
2234 top: (result.t)/this.reduce +'px'
2238 //console.log(key + ' not displayed');
2239 this.searchResults[key].div=null;
2245 //______________________________________________________________________________
2246 // Returns the position of the gutter (line between the page images)
2247 BookReader.prototype.twoPageGutter = function() {
2248 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2252 //______________________________________________________________________________
2253 // Returns the offset for the top of the page images
2254 BookReader.prototype.twoPageTop = function() {
2255 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2258 // twoPageCoverWidth()
2259 //______________________________________________________________________________
2260 // Returns the width of the cover div given the total page width
2261 BookReader.prototype.twoPageCoverWidth = function(totalPageWidth) {
2262 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2265 // twoPageGetViewCenter()
2266 //______________________________________________________________________________
2267 // Returns the percentage offset into twopageview div at the center of container div
2268 // { percentageX: float, percentageY: float }
2269 BookReader.prototype.twoPageGetViewCenter = function() {
2272 var containerOffset = $('#BRcontainer').offset();
2273 var viewOffset = $('#BRtwopageview').offset();
2274 center.percentageX = (containerOffset.left - viewOffset.left + ($('#BRcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2275 center.percentageY = (containerOffset.top - viewOffset.top + ($('#BRcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2280 // twoPageCenterView(percentageX, percentageY)
2281 //______________________________________________________________________________
2282 // Centers the point given by percentage from left,top of twopageview
2283 BookReader.prototype.twoPageCenterView = function(percentageX, percentageY) {
2284 if ('undefined' == typeof(percentageX)) {
2287 if ('undefined' == typeof(percentageY)) {
2291 var viewWidth = $('#BRtwopageview').width();
2292 var containerClientWidth = $('#BRcontainer').attr('clientWidth');
2293 var intoViewX = percentageX * viewWidth;
2295 var viewHeight = $('#BRtwopageview').height();
2296 var containerClientHeight = $('#BRcontainer').attr('clientHeight');
2297 var intoViewY = percentageY * viewHeight;
2299 if (viewWidth < containerClientWidth) {
2300 // Can fit width without scrollbars - center by adjusting offset
2301 $('#BRtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2303 // Need to scroll to center
2304 $('#BRtwopageview').css('left', 0);
2305 $('#BRcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2308 if (viewHeight < containerClientHeight) {
2309 // Fits with scrollbars - add offset
2310 $('#BRtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2312 $('#BRtwopageview').css('top', 0);
2313 $('#BRcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2317 // twoPageFlipAreaHeight
2318 //______________________________________________________________________________
2319 // Returns the integer height of the click-to-flip areas at the edges of the book
2320 BookReader.prototype.twoPageFlipAreaHeight = function() {
2321 return parseInt(this.twoPage.height);
2324 // twoPageFlipAreaWidth
2325 //______________________________________________________________________________
2326 // Returns the integer width of the flip areas
2327 BookReader.prototype.twoPageFlipAreaWidth = function() {
2328 var max = 100; // $$$ TODO base on view width?
2331 var width = this.twoPage.width * 0.15;
2332 return parseInt(BookReader.util.clamp(width, min, max));
2335 // twoPageFlipAreaTop
2336 //______________________________________________________________________________
2337 // Returns integer top offset for flip areas
2338 BookReader.prototype.twoPageFlipAreaTop = function() {
2339 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2342 // twoPageLeftFlipAreaLeft
2343 //______________________________________________________________________________
2344 // Left offset for left flip area
2345 BookReader.prototype.twoPageLeftFlipAreaLeft = function() {
2346 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2349 // twoPageRightFlipAreaLeft
2350 //______________________________________________________________________________
2351 // Left offset for right flip area
2352 BookReader.prototype.twoPageRightFlipAreaLeft = function() {
2353 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2356 // twoPagePlaceFlipAreas
2357 //______________________________________________________________________________
2358 // Readjusts position of flip areas based on current layout
2359 BookReader.prototype.twoPagePlaceFlipAreas = function() {
2360 // We don't set top since it shouldn't change relative to view
2361 $(this.twoPage.leftFlipArea).css({
2362 left: this.twoPageLeftFlipAreaLeft() + 'px',
2363 width: this.twoPageFlipAreaWidth() + 'px'
2365 $(this.twoPage.rightFlipArea).css({
2366 left: this.twoPageRightFlipAreaLeft() + 'px',
2367 width: this.twoPageFlipAreaWidth() + 'px'
2371 // showSearchHilites2UP()
2372 //______________________________________________________________________________
2373 BookReader.prototype.updateSearchHilites2UP = function() {
2375 for (var key in this.searchResults) {
2376 key = parseInt(key, 10);
2377 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2378 var result = this.searchResults[key];
2379 if(null == result.div) {
2380 result.div = document.createElement('div');
2381 $(result.div).attr('className', 'BookReaderSearchHilite').css('zIndex', 3).appendTo('#BRtwopageview');
2382 //console.log('appending ' + key);
2385 // We calculate the reduction factor for the specific page because it can be different
2386 // for each page in the spread
2387 var height = this._getPageHeight(key);
2388 var width = this._getPageWidth(key)
2389 var reduce = this.twoPage.height/height;
2390 var scaledW = parseInt(width*reduce);
2392 var gutter = this.twoPageGutter();
2394 if ('L' == this.getPageSide(key)) {
2395 pageL = gutter-scaledW;
2399 var pageT = this.twoPageTop();
2402 width: (result.r-result.l)*reduce + 'px',
2403 height: (result.b-result.t)*reduce + 'px',
2404 left: pageL+(result.l)*reduce + 'px',
2405 top: pageT+(result.t)*reduce +'px'
2409 //console.log(key + ' not displayed');
2410 if (null != this.searchResults[key].div) {
2411 //console.log('removing ' + key);
2412 $(this.searchResults[key].div).remove();
2414 this.searchResults[key].div=null;
2419 // removeSearchHilites()
2420 //______________________________________________________________________________
2421 BookReader.prototype.removeSearchHilites = function() {
2422 for (var key in this.searchResults) {
2423 if (null != this.searchResults[key].div) {
2424 $(this.searchResults[key].div).remove();
2425 this.searchResults[key].div=null;
2431 //______________________________________________________________________________
2432 BookReader.prototype.printPage = function() {
2433 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2435 /* iframe implementation
2437 if (null != this.printPopup) { // check if already showing
2440 this.printPopup = document.createElement("div");
2441 $(this.printPopup).css({
2442 position: 'absolute',
2444 left: ($('#BRcontainer').width()-400)/2 + 'px',
2447 border: "3px double #999999",
2449 backgroundColor: "#fff"
2450 }).appendTo('#BookReader');
2453 if (this.constMode1up == this.mode) {
2454 indexToPrint = this.firstIndex;
2456 indexToPrint = this.twoPage.currentIndexL;
2459 this.indexToPrint = indexToPrint;
2461 var htmlStr = '<div style="text-align: center;">';
2462 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>';
2463 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2464 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2465 //htmlStr += '<button class="BRicon rollover book_up" onclick="br.updatePrintFrame(-1); return false;"></button> ';
2466 //htmlStr += '<button class="BRicon rollover book_down" onclick="br.updatePrintFrame(1); return false;"></button>';
2467 htmlStr += '<a href="#" onclick="br.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="br.updatePrintFrame(1); return false;">Next</a>';
2469 htmlStr += '</div>';
2470 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2471 htmlStr += '</div>';
2473 this.printPopup.innerHTML = htmlStr;
2475 var iframe = document.createElement('iframe');
2476 iframe.id = 'printFrame';
2477 iframe.name = 'printFrame';
2478 iframe.width = '233px'; // 8.5 x 11 aspect
2479 iframe.height = '300px';
2481 var self = this; // closure
2483 $(iframe).load(function() {
2484 var doc = BookReader.util.getIFrameDocument(this);
2485 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2488 $('#printDiv').prepend(iframe);
2492 // Get print URI from current indices and mode
2493 BookReader.prototype.getPrintURI = function() {
2495 if (this.constMode2up == this.mode) {
2496 indexToPrint = this.twoPage.currentIndexL;
2498 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2501 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2502 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2503 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2505 if (this.constMode2up == this.mode) {
2506 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2507 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2508 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2510 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2513 return '/bookreader/print.php?' + options;
2516 /* iframe implementation
2517 BookReader.prototype.getPrintFrameContent = function(index) {
2518 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2519 // 8.5x11 so we should end up not overflowing on either paper size.
2520 var paperAspect = 8.5 / 11;
2521 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2525 // Rotate if possible and appropriate, to get larger image size on printed page
2526 if (this.canRotatePage(index)) {
2527 if (imageAspect > 1 && imageAspect > paperAspect) {
2528 // more wide than square, and more wide than paper
2530 imageAspect = 1/imageAspect;
2535 if (imageAspect > paperAspect) {
2536 // wider than paper, fit width
2537 fitAttrs = 'width="95%"';
2539 // taller than paper, fit height
2540 fitAttrs = 'height="95%"';
2543 var imageURL = this._getPageURI(index, 1, rotate);
2544 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2545 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2546 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2547 iframeStr += '</div>';
2548 iframeStr += '</body></html>';
2553 BookReader.prototype.updatePrintFrame = function(delta) {
2554 var newIndex = this.indexToPrint + delta;
2555 newIndex = BookReader.util.clamp(newIndex, 0, this.numLeafs - 1);
2556 if (newIndex == this.indexToPrint) {
2559 this.indexToPrint = newIndex;
2560 var doc = BookReader.util.getIFrameDocument($('#printFrame')[0]);
2561 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2566 //______________________________________________________________________________
2567 BookReader.prototype.showEmbedCode = function() {
2568 if (null != this.embedPopup) { // check if already showing
2572 this.embedPopup = document.createElement("div");
2573 $(this.embedPopup).css({
2574 position: 'absolute',
2576 left: ($('#BRcontainer').attr('clientWidth')-400)/2 + 'px',
2579 border: "3px double #999999",
2581 backgroundColor: "#fff"
2582 }).appendTo('#BookReader');
2584 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2585 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>';
2586 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2587 htmlStr += '<p style="text-align:center;"><a href="" onclick="br.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2589 this.embedPopup.innerHTML = htmlStr;
2590 $(this.embedPopup).find('input').bind('click', function() {
2596 //______________________________________________________________________________
2597 BookReader.prototype.autoToggle = function() {
2599 var bComingFrom1up = false;
2600 if (2 != this.mode) {
2601 bComingFrom1up = true;
2605 // Change to autofit if book is too large
2606 if (this.reduce < this.twoPageGetAutofitReduce()) {
2611 if (null == this.autoTimer) {
2612 this.flipSpeed = 2000;
2614 // $$$ Draw events currently cause layout problems when they occur during animation.
2615 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2616 // we workaround for now by not triggering immediate animation in that case.
2617 // See https://bugs.launchpad.net/gnubook/+bug/328327
2618 if (('rl' == this.pageProgression) && bComingFrom1up) {
2619 // don't flip immediately -- wait until timer fires
2622 this.flipFwdToIndex();
2625 $('#BRtoolbar .play').hide();
2626 $('#BRtoolbar .pause').show();
2627 this.autoTimer=setInterval(function(){
2628 if (self.animating) {return;}
2630 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2631 self.flipBackToIndex(1); // $$$ really what we want?
2633 self.flipFwdToIndex();
2642 //______________________________________________________________________________
2643 // Stop autoplay mode, allowing animations to finish
2644 BookReader.prototype.autoStop = function() {
2645 if (null != this.autoTimer) {
2646 clearInterval(this.autoTimer);
2647 this.flipSpeed = 'fast';
2648 $('#BRtoolbar .pause').hide();
2649 $('#BRtoolbar .play').show();
2650 this.autoTimer = null;
2654 // stopFlipAnimations
2655 //______________________________________________________________________________
2656 // Immediately stop flip animations. Callbacks are triggered.
2657 BookReader.prototype.stopFlipAnimations = function() {
2659 this.autoStop(); // Clear timers
2661 // Stop animation, clear queue, trigger callbacks
2662 if (this.leafEdgeTmp) {
2663 $(this.leafEdgeTmp).stop(false, true);
2665 jQuery.each(this.prefetchedImgs, function() {
2666 $(this).stop(false, true);
2669 // And again since animations also queued in callbacks
2670 if (this.leafEdgeTmp) {
2671 $(this.leafEdgeTmp).stop(false, true);
2673 jQuery.each(this.prefetchedImgs, function() {
2674 $(this).stop(false, true);
2679 // keyboardNavigationIsDisabled(event)
2680 // - returns true if keyboard navigation should be disabled for the event
2681 //______________________________________________________________________________
2682 BookReader.prototype.keyboardNavigationIsDisabled = function(event) {
2683 if (event.target.tagName == "INPUT") {
2689 // gutterOffsetForIndex
2690 //______________________________________________________________________________
2692 // Returns the gutter offset for the spread containing the given index.
2693 // This function supports RTL
2694 BookReader.prototype.gutterOffsetForIndex = function(pindex) {
2696 // To find the offset of the gutter from the middle we calculate our percentage distance
2697 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2698 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2700 // But then again for RTL it's the opposite
2701 if ('rl' == this.pageProgression) {
2709 //______________________________________________________________________________
2710 // Returns the width of the leaf edge div for the page with index given
2711 BookReader.prototype.leafEdgeWidth = function(pindex) {
2712 // $$$ could there be single pixel rounding errors for L vs R?
2713 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2714 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2716 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2720 // jumpIndexForLeftEdgePageX
2721 //______________________________________________________________________________
2722 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2723 BookReader.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2724 if ('rl' != this.pageProgression) {
2725 // LTR - flipping backward
2726 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2728 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2729 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2733 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2734 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2739 // jumpIndexForRightEdgePageX
2740 //______________________________________________________________________________
2741 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2742 BookReader.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2743 if ('rl' != this.pageProgression) {
2745 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2746 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2749 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2750 jumpIndex = BookReader.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2755 BookReader.prototype.initToolbar = function(mode, ui) {
2757 $("#BookReader").append("<div id='BRtoolbar'>"
2758 + "<span id='BRtoolbarbuttons' style='float: right'>"
2759 + "<button class='BRicon print rollover' /> <button class='BRicon rollover embed' />"
2760 + "<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>"
2761 + "<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>"
2762 + "<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>"
2763 + "<button class='BRicon rollover play' /><button class='BRicon rollover pause' style='display: none' />"
2767 + "<a class='BRicon logo rollover' href='" + this.logoURL + "'> </a>"
2768 + " <button class='BRicon rollover zoom_out' onclick='br.zoom(-1); return false;'/>"
2769 + "<button class='BRicon rollover zoom_in' onclick='br.zoom(1); return false;'/>"
2770 + " <span class='label'>Zoom: <span id='BRzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2771 + " <button class='BRicon rollover one_page_mode' onclick='br.switchMode(1); return false;'/>"
2772 + " <button class='BRicon rollover two_page_mode' onclick='br.switchMode(2); return false;'/>"
2775 + "<span id='#BRbooktitle'>"
2776 + " <a class='BRblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
2780 this.updateToolbarZoom(this.reduce); // Pretty format
2782 if (ui == "embed") {
2783 $("#BookReader a.logo").attr("target","_blank");
2786 // $$$ turn this into a member variable
2787 var jToolbar = $('#BRtoolbar'); // j prefix indicates jQuery object
2789 // We build in mode 2
2792 this.bindToolbarNavHandlers(jToolbar);
2794 // Setup tooltips -- later we could load these from a file for i18n
2795 var titles = { '.logo': 'Go to Archive.org',
2796 '.zoom_in': 'Zoom in',
2797 '.zoom_out': 'Zoom out',
2798 '.one_page_mode': 'One-page view',
2799 '.two_page_mode': 'Two-page view',
2800 '.print': 'Print this page',
2801 '.embed': 'Embed bookreader',
2802 '.book_left': 'Flip left',
2803 '.book_right': 'Flip right',
2804 '.book_up': 'Page up',
2805 '.book_down': 'Page down',
2808 '.book_top': 'First page',
2809 '.book_bottom': 'Last page'
2811 if ('rl' == this.pageProgression) {
2812 titles['.book_leftmost'] = 'Last page';
2813 titles['.book_rightmost'] = 'First page';
2815 titles['.book_leftmost'] = 'First page';
2816 titles['.book_rightmost'] = 'Last page';
2819 for (var icon in titles) {
2820 jToolbar.find(icon).attr('title', titles[icon]);
2823 // Hide mode buttons and autoplay if 2up is not available
2824 // $$$ if we end up with more than two modes we should show the applicable buttons
2825 if ( !this.canSwitchToMode(this.constMode2up) ) {
2826 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2829 // Switch to requested mode -- binds other click handlers
2830 this.switchToolbarMode(mode);
2835 // switchToolbarMode
2836 //______________________________________________________________________________
2837 // Update the toolbar for the given mode (changes navigation buttons)
2838 // $$$ we should soon split the toolbar out into its own module
2839 BookReader.prototype.switchToolbarMode = function(mode) {
2842 $('#BRtoolbar .BRtoolbarmode2').hide();
2843 $('#BRtoolbar .BRtoolbarmode1').show().css('display', 'inline');
2846 $('#BRtoolbar .BRtoolbarmode1').hide();
2847 $('#BRtoolbar .BRtoolbarmode2').show().css('display', 'inline');
2851 // bindToolbarNavHandlers
2852 //______________________________________________________________________________
2853 // Binds the toolbar handlers
2854 BookReader.prototype.bindToolbarNavHandlers = function(jToolbar) {
2856 var self = this; // closure
2858 jToolbar.find('.book_left').bind('click', function(e) {
2863 jToolbar.find('.book_right').bind('click', function(e) {
2868 jToolbar.find('.book_up').bind('click', function(e) {
2873 jToolbar.find('.book_down').bind('click', function(e) {
2878 jToolbar.find('.print').bind('click', function(e) {
2883 jToolbar.find('.embed').bind('click', function(e) {
2884 self.showEmbedCode();
2888 jToolbar.find('.play').bind('click', function(e) {
2893 jToolbar.find('.pause').bind('click', function(e) {
2898 jToolbar.find('.book_top').bind('click', function(e) {
2903 jToolbar.find('.book_bottom').bind('click', function(e) {
2908 jToolbar.find('.book_leftmost').bind('click', function(e) {
2913 jToolbar.find('.book_rightmost').bind('click', function(e) {
2919 // updateToolbarZoom(reduce)
2920 //______________________________________________________________________________
2921 // Update the displayed zoom factor based on reduction factor
2922 BookReader.prototype.updateToolbarZoom = function(reduce) {
2924 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2927 value = (100 / reduce).toFixed(2);
2928 // Strip trailing zeroes and decimal if all zeroes
2929 value = value.replace(/0+$/,'');
2930 value = value.replace(/\.$/,'');
2933 $('#BRzoom').text(value);
2936 // firstDisplayableIndex
2937 //______________________________________________________________________________
2938 // Returns the index of the first visible page, dependent on the mode.
2939 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2940 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2941 BookReader.prototype.firstDisplayableIndex = function() {
2942 if (this.mode != this.constMode2up) {
2946 if ('rl' != this.pageProgression) {
2948 if (this.getPageSide(0) == 'L') {
2955 if (this.getPageSide(0) == 'R') {
2963 // lastDisplayableIndex
2964 //______________________________________________________________________________
2965 // Returns the index of the last visible page, dependent on the mode.
2966 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2967 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2968 BookReader.prototype.lastDisplayableIndex = function() {
2970 var lastIndex = this.numLeafs - 1;
2972 if (this.mode != this.constMode2up) {
2976 if ('rl' != this.pageProgression) {
2978 if (this.getPageSide(lastIndex) == 'R') {
2981 return lastIndex + 1;
2985 if (this.getPageSide(lastIndex) == 'L') {
2988 return lastIndex + 1;
2993 // shortTitle(maximumCharacters)
2995 // Returns a shortened version of the title with the maximum number of characters
2996 BookReader.prototype.shortTitle = function(maximumCharacters) {
2997 if (this.bookTitle.length < maximumCharacters) {
2998 return this.bookTitle;
3001 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3006 // Parameter related functions
3008 // updateFromParams(params)
3010 // Update ourselves from the params object.
3012 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3013 BookReader.prototype.updateFromParams = function(params) {
3014 if ('undefined' != typeof(params.mode)) {
3015 this.switchMode(params.mode);
3019 if ('undefined' != typeof(params.searchTerm)) {
3020 if (this.searchTerm != params.searchTerm) {
3021 this.search(params.searchTerm);
3025 // $$$ process /zoom
3027 // We only respect page if index is not set
3028 if ('undefined' != typeof(params.index)) {
3029 if (params.index != this.currentIndex()) {
3030 this.jumpToIndex(params.index);
3032 } else if ('undefined' != typeof(params.page)) {
3033 // $$$ this assumes page numbers are unique
3034 if (params.page != this.getPageNum(this.currentIndex())) {
3035 this.jumpToPage(params.page);
3039 // $$$ process /region
3040 // $$$ process /highlight
3043 // paramsFromFragment(urlFragment)
3045 // Returns a object with configuration parametes from a URL fragment.
3047 // E.g paramsFromFragment(window.location.hash)
3048 BookReader.prototype.paramsFromFragment = function(urlFragment) {
3049 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3053 // For convenience we allow an initial # character (as from window.location.hash)
3054 // but don't require it
3055 if (urlFragment.substr(0,1) == '#') {
3056 urlFragment = urlFragment.substr(1);
3059 // Simple #nn syntax
3060 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3061 if ( !isNaN(oldStyleLeafNum) ) {
3062 params.index = oldStyleLeafNum;
3064 // Done processing if using old-style syntax
3068 // Split into key-value pairs
3069 var urlArray = urlFragment.split('/');
3071 for (var i = 0; i < urlArray.length; i += 2) {
3072 urlHash[urlArray[i]] = urlArray[i+1];
3076 if ('1up' == urlHash['mode']) {
3077 params.mode = this.constMode1up;
3078 } else if ('2up' == urlHash['mode']) {
3079 params.mode = this.constMode2up;
3083 if ('undefined' != typeof(urlHash['page'])) {
3084 // page was set -- may not be int
3085 params.page = urlHash['page'];
3088 // $$$ process /region
3089 // $$$ process /search
3091 if (urlHash['search'] != undefined) {
3092 params.searchTerm = BookReader.util.decodeURIComponentPlus(urlHash['search']);
3095 // $$$ process /highlight
3100 // paramsFromCurrent()
3102 // Create a params object from the current parameters.
3103 BookReader.prototype.paramsFromCurrent = function() {
3107 var index = this.currentIndex();
3108 var pageNum = this.getPageNum(index);
3109 if ((pageNum === 0) || pageNum) {
3110 params.page = pageNum;
3113 params.index = index;
3114 params.mode = this.mode;
3120 if (this.searchHighlightVisible()) {
3121 params.searchTerm = this.searchTerm;
3127 // fragmentFromParams(params)
3129 // Create a fragment string from the params object.
3130 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3131 BookReader.prototype.fragmentFromParams = function(params) {
3132 var separator = '/';
3136 if ('undefined' != typeof(params.page)) {
3137 fragments.push('page', params.page);
3139 // Don't have page numbering -- use index instead
3140 fragments.push('page', 'n' + params.index);
3147 if ('undefined' != typeof(params.mode)) {
3148 if (params.mode == this.constMode1up) {
3149 fragments.push('mode', '1up');
3150 } else if (params.mode == this.constMode2up) {
3151 fragments.push('mode', '2up');
3153 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3158 if (params.searchTerm) {
3159 fragments.push('search', params.searchTerm);
3162 return BookReader.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3165 // getPageIndex(pageNum)
3167 // Returns the *highest* index the given page number, or undefined
3168 BookReader.prototype.getPageIndex = function(pageNum) {
3169 var pageIndices = this.getPageIndices(pageNum);
3171 if (pageIndices.length > 0) {
3172 return pageIndices[pageIndices.length - 1];
3178 // getPageIndices(pageNum)
3180 // Returns an array (possibly empty) of the indices with the given page number
3181 BookReader.prototype.getPageIndices = function(pageNum) {
3184 // Check for special "nXX" page number
3185 if (pageNum.slice(0,1) == 'n') {
3187 var pageIntStr = pageNum.slice(1, pageNum.length);
3188 var pageIndex = parseInt(pageIntStr);
3189 indices.push(pageIndex);
3192 // Do nothing... will run through page names and see if one matches
3197 for (i=0; i<this.numLeafs; i++) {
3198 if (this.getPageNum(i) == pageNum) {
3206 // getPageName(index)
3208 // Returns the name of the page as it should be displayed in the user interface
3209 BookReader.prototype.getPageName = function(index) {
3210 return 'Page ' + this.getPageNum(index);
3213 // updateLocationHash
3215 // Update the location hash from the current parameters. Call this instead of manually
3216 // using window.location.replace
3217 BookReader.prototype.updateLocationHash = function() {
3218 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3219 window.location.replace(newHash);
3221 // This is the variable checked in the timer. Only user-generated changes
3222 // to the URL will trigger the event.
3223 this.oldLocationHash = newHash;
3226 // startLocationPolling
3228 // Starts polling of window.location to see hash fragment changes
3229 BookReader.prototype.startLocationPolling = function() {
3230 var self = this; // remember who I am
3231 self.oldLocationHash = window.location.hash;
3233 if (this.locationPollId) {
3234 clearInterval(this.locationPollID);
3235 this.locationPollId = null;
3238 this.locationPollId = setInterval(function() {
3239 var newHash = window.location.hash;
3240 if (newHash != self.oldLocationHash) {
3241 if (newHash != self.oldUserHash) { // Only process new user hash once
3242 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3244 // Queue change if animating
3245 if (self.animating) {
3247 self.animationFinishedCallback = function() {
3248 self.updateFromParams(self.paramsFromFragment(newHash));
3250 } else { // update immediately
3251 self.updateFromParams(self.paramsFromFragment(newHash));
3253 self.oldUserHash = newHash;
3261 // Returns true if we can switch to the requested mode
3262 BookReader.prototype.canSwitchToMode = function(mode) {
3263 if (mode == this.constMode2up) {
3264 // check there are enough pages to display
3265 // $$$ this is a workaround for the mis-feature that we can't display
3266 // short books in 2up mode
3267 if (this.numLeafs < 6) {
3275 // searchHighlightVisible
3277 // Returns true if a search highlight is currently being displayed
3278 BookReader.prototype.searchHighlightVisible = function() {
3279 if (this.constMode2up == this.mode) {
3280 if (this.searchResults[this.twoPage.currentIndexL]
3281 || this.searchResults[this.twoPage.currentIndexR]) {
3285 if (this.searchResults[this.currentIndex()]) {
3292 // getPageBackgroundColor
3294 // Returns a CSS property string for the background color for the given page
3295 // $$$ turn into regular CSS?
3296 BookReader.prototype.getPageBackgroundColor = function(index) {
3297 if (index >= 0 && index < this.numLeafs) {
3299 return this.pageDefaultBackgroundColor;
3307 // Returns the page width for the given index, or first or last page if out of range
3308 BookReader.prototype._getPageWidth = function(index) {
3309 // Synthesize a page width for pages not actually present in book.
3310 // May or may not be the best approach.
3311 // If index is out of range we return the width of first or last page
3312 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3313 return this.getPageWidth(index);
3318 // Returns the page height for the given index, or first or last page if out of range
3319 BookReader.prototype._getPageHeight= function(index) {
3320 index = BookReader.util.clamp(index, 0, this.numLeafs - 1);
3321 return this.getPageHeight(index);
3326 // Returns the page URI or transparent image if out of range
3327 BookReader.prototype._getPageURI = function(index, reduce, rotate) {
3328 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3329 return this.imagesBaseURL + "/transparent.png";
3332 if ('undefined' == typeof(reduce)) {
3333 // reduce not passed in
3334 var ratio = this.getPageHeight(index) / this.twoPage.height;
3336 // $$$ we make an assumption here that the scales are available pow2 (like kakadu)
3339 } else if (ratio < 4) {
3341 } else if (ratio < 8) {
3343 } else if (ratio < 16) {
3345 } else if (ratio < 32) {
3353 return this.getPageURI(index, reduce, rotate);
3356 // Library functions
3358 clamp: function(value, min, max) {
3359 return Math.min(Math.max(value, min), max);
3362 getIFrameDocument: function(iframe) {
3363 // Adapted from http://xkr.us/articles/dom/iframe-document/
3364 var outer = (iframe.contentWindow || iframe.contentDocument);
3365 return (outer.document || outer);
3368 decodeURIComponentPlus: function(value) {
3369 // Decodes a URI component and converts '+' to ' '
3370 return decodeURIComponent(value).replace(/\+/g, ' ');
3373 encodeURIComponentPlus: function(value) {
3374 // Encodes a URI component and converts ' ' to '+'
3375 return encodeURIComponent(value).replace(/%20/g, '+');
3377 // The final property here must NOT have a comma after it - IE7