2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook 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 GnuBook 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 GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook 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():
31 // You must also add a numLeafs property before calling init().
36 this.mode = 1; //1 or 2
37 this.ui = 'full'; // UI mode
39 this.displayedIndices = [];
40 //this.indicesToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
45 this.animating = false;
47 this.autoTimer = null;
48 this.flipSpeed = 'fast';
50 this.twoPagePopUp = null;
51 this.leafEdgeTmp = null;
52 this.embedPopup = null;
54 this.searchResults = {};
56 this.firstIndex = null;
58 this.lastDisplayableIndex2up = null;
60 // We link to index.php to avoid redirect which breaks back button
61 this.logoURL = 'http://www.archive.org/index.php';
63 // Base URL for images
64 this.imagesBaseURL = '/bookreader/images/';
67 this.constMode1up = 1;
68 this.constMode2up = 2;
71 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
73 // Object to hold parameters related to 2up mode
75 coverInternalPadding: 10, // Width of cover
76 coverExternalPadding: 10, // Padding outside of cover
77 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
86 var startIndex = undefined;
88 // Find start index and mode if set in location hash
89 var params = this.paramsFromFragment(window.location.hash);
91 if ('undefined' != typeof(params.index)) {
92 startIndex = params.index;
93 } else if ('undefined' != typeof(params.page)) {
94 startIndex = this.getPageIndex(params.page);
97 if ('undefined' == typeof(startIndex)) {
98 if ('undefined' != typeof(this.titleLeaf)) {
99 startIndex = this.leafNumToIndex(this.titleLeaf);
103 if ('undefined' == typeof(startIndex)) {
107 if ('undefined' != typeof(params.mode)) {
108 this.mode = params.mode;
111 // Set document title -- may have already been set in enclosing html for
112 // search engine visibility
113 document.title = this.shortTitle(50);
115 // Sanitize parameters
116 if ( !this.canSwitchToMode( this.mode ) ) {
117 this.mode = this.constMode1up;
120 $("#GnuBook").empty();
121 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122 $("#GnuBook").append("<div id='GBcontainer'></div>");
123 $("#GBcontainer").append("<div id='GBpageview'></div>");
125 $("#GBcontainer").bind('scroll', this, function(e) {
129 this.setupKeyListeners();
130 this.startLocationPolling();
132 $(window).bind('resize', this, function(e) {
133 //console.log('resize!');
134 if (1 == e.data.mode) {
135 //console.log('centering 1page view');
136 e.data.centerPageView();
137 $('#GBpageview').empty()
138 e.data.displayedIndices = [];
139 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
142 //console.log('drawing 2 page view');
144 // We only need to prepare again in autofit (size of spread changes)
145 if (e.data.twoPage.autofit) {
146 e.data.prepareTwoPageView();
148 // Re-center if the scrollbars have disappeared
149 var center = e.data.twoPageGetViewCenter();
150 var doRecenter = false;
151 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
152 center.percentageX = 0.5;
155 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
156 center.percentageY = 0.5;
160 e.data.twoPageCenterView(center.percentageX, center.percentageY);
166 $('.GBpagediv1up').bind('mousedown', this, function(e) {
167 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
168 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
171 if (1 == this.mode) {
172 this.resizePageView();
173 this.firstIndex = startIndex;
174 this.jumpToIndex(startIndex);
176 //this.resizePageView();
178 this.displayedIndices=[0];
179 this.firstIndex = startIndex;
180 this.displayedIndices = [this.firstIndex];
181 //console.log('titleLeaf: %d', this.titleLeaf);
182 //console.log('displayedIndices: %s', this.displayedIndices);
183 this.prepareTwoPageView();
186 // Enact other parts of initial params
187 this.updateFromParams(params);
190 GnuBook.prototype.setupKeyListeners = function() {
203 // We use document here instead of window to avoid a bug in jQuery on IE7
204 $(document).keydown(function(e) {
206 // Keyboard navigation
210 // In 1up mode page scrolling is handled by browser
211 if (2 == self.mode) {
218 if (2 == self.mode) {
232 if (self.keyboardNavigationIsDisabled(e)) {
235 if (2 == self.mode) {
241 if (self.keyboardNavigationIsDisabled(e)) {
244 if (2 == self.mode) {
254 //______________________________________________________________________________
255 GnuBook.prototype.drawLeafs = function() {
256 if (1 == this.mode) {
257 this.drawLeafsOnePage();
259 this.drawLeafsTwoPage();
264 //______________________________________________________________________________
265 GnuBook.prototype.setDragHandler = function(div) {
266 div.dragging = false;
268 $(div).unbind('mousedown').bind('mousedown', function(e) {
271 //console.log('mousedown at ' + e.pageY);
273 this.dragging = true;
274 this.prevMouseX = e.pageX;
275 this.prevMouseY = e.pageY;
277 var startX = e.pageX;
278 var startY = e.pageY;
279 var startTop = $('#GBcontainer').attr('scrollTop');
280 var startLeft = $('#GBcontainer').attr('scrollLeft');
284 $(div).unbind('mousemove').bind('mousemove', function(ee) {
287 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
289 var offsetX = ee.pageX - this.prevMouseX;
290 var offsetY = ee.pageY - this.prevMouseY;
293 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
294 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
297 this.prevMouseX = ee.pageX;
298 this.prevMouseY = ee.pageY;
302 $(div).unbind('mouseup').bind('mouseup', function(ee) {
304 //console.log('mouseup');
306 this.dragging = false;
309 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
311 //console.log('mouseleave');
313 this.dragging = false;
316 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
318 //console.log('mouseenter');
320 this.dragging = false;
324 // drawLeafsOnePage()
325 //______________________________________________________________________________
326 GnuBook.prototype.drawLeafsOnePage = function() {
327 //alert('drawing leafs!');
331 var scrollTop = $('#GBcontainer').attr('scrollTop');
332 var scrollBottom = scrollTop + $('#GBcontainer').height();
333 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
335 var indicesToDisplay = [];
340 for (i=0; i<this.numLeafs; i++) {
341 var height = parseInt(this.getPageHeight(i)/this.reduce);
343 leafBottom += height;
344 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
345 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
346 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
347 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
348 if (topInView | bottomInView | middleInView) {
349 //console.log('displayed: ' + this.displayedIndices);
350 //console.log('to display: ' + i);
351 indicesToDisplay.push(i);
353 leafTop += height +10;
357 var firstIndexToDraw = indicesToDisplay[0];
358 this.firstIndex = firstIndexToDraw;
360 // Update hash, but only if we're currently displaying a leaf
361 // Hack that fixes #365790
362 if (this.displayedIndices.length > 0) {
363 this.updateLocationHash();
366 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
368 indicesToDisplay.unshift(firstIndexToDraw);
371 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
372 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
373 indicesToDisplay.push(lastIndexToDraw+1);
378 for (i=0; i<firstIndexToDraw; i++) {
379 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
382 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
383 var viewWidth = $('#GBcontainer').attr('scrollWidth');
386 for (i=0; i<indicesToDisplay.length; i++) {
387 var index = indicesToDisplay[i];
388 var height = parseInt(this.getPageHeight(index)/this.reduce);
390 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
391 var width = parseInt(this.getPageWidth(index)/this.reduce);
392 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
393 var div = document.createElement("div");
394 div.className = 'GBpagediv1up';
395 div.id = 'pagediv'+index;
396 div.style.position = "absolute";
397 $(div).css('top', leafTop + 'px');
398 var left = (viewWidth-width)>>1;
399 if (left<0) left = 0;
400 $(div).css('left', left+'px');
401 $(div).css('width', width+'px');
402 $(div).css('height', height+'px');
403 //$(div).text('loading...');
405 this.setDragHandler(div);
407 $('#GBpageview').append(div);
409 var img = document.createElement("img");
410 img.src = this.getPageURI(index);
411 $(img).css('width', width+'px');
412 $(img).css('height', height+'px');
416 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
419 leafTop += height +10;
423 for (i=0; i<this.displayedIndices.length; i++) {
424 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
425 var index = this.displayedIndices[i];
426 //console.log('Removing leaf ' + index);
427 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
428 $('#pagediv'+index).remove();
430 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
434 this.displayedIndices = indicesToDisplay.slice();
435 this.updateSearchHilites();
437 if (null != this.getPageNum(firstIndexToDraw)) {
438 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
440 $("#GBpagenum").val('');
443 this.updateToolbarZoom(this.reduce);
447 // drawLeafsTwoPage()
448 //______________________________________________________________________________
449 GnuBook.prototype.drawLeafsTwoPage = function() {
450 var scrollTop = $('#GBtwopageview').attr('scrollTop');
451 var scrollBottom = scrollTop + $('#GBtwopageview').height();
453 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
455 var indexL = this.twoPage.currentIndexL;
456 var heightL = this.getPageHeight(indexL);
457 var widthL = this.getPageWidth(indexL);
459 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
460 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
461 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
462 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
463 //console.log(leafEdgeWidthL);
465 var middle = this.twoPage.middle; // $$$ getter instead?
466 var top = this.twoPageTop();
467 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
469 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
470 this.twoPage.gutter = this.twoPageGutter();
472 this.prefetchImg(indexL);
473 $(this.prefetchedImgs[indexL]).css({
474 position: 'absolute',
475 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
478 backgroundColor: 'rgb(234, 226, 205)',
479 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
480 width: this.twoPage.scaledWL + 'px',
481 borderRight: '1px solid black',
483 }).appendTo('#GBtwopageview');
485 var indexR = this.twoPage.currentIndexR;
486 var heightR = this.getPageHeight(indexR);
487 var widthR = this.getPageWidth(indexR);
489 // $$$ should use getwidth2up?
490 //var scaledWR = this.twoPage.height*widthR/heightR;
491 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
492 this.prefetchImg(indexR);
493 $(this.prefetchedImgs[indexR]).css({
494 position: 'absolute',
495 left: this.twoPage.gutter+'px',
498 backgroundColor: 'rgb(234, 226, 205)',
499 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
500 width: this.twoPage.scaledWR + 'px',
501 borderLeft: '1px solid black',
503 }).appendTo('#GBtwopageview');
506 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
507 this.setClickHandlers();
508 this.twoPageSetCursor();
510 this.updatePageNumBox2UP();
511 this.updateToolbarZoom(this.reduce);
513 this.twoPagePlaceFlipAreas();
517 // updatePageNumBox2UP
518 //______________________________________________________________________________
519 GnuBook.prototype.updatePageNumBox2UP = function() {
520 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
521 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
523 $("#GBpagenum").val('');
525 this.updateLocationHash();
529 //______________________________________________________________________________
530 GnuBook.prototype.loadLeafs = function() {
534 if (null == this.timer) {
535 this.timer=setTimeout(function(){self.drawLeafs()},250);
537 clearTimeout(this.timer);
538 this.timer=setTimeout(function(){self.drawLeafs()},250);
544 // Pass 1 to zoom in, anything else to zoom out
545 //______________________________________________________________________________
546 GnuBook.prototype.zoom = function(direction) {
548 case this.constMode1up:
549 return this.zoom1up(direction);
550 case this.constMode2up:
551 return this.zoom2up(direction);
556 //______________________________________________________________________________
557 GnuBook.prototype.zoom1up = function(dir) {
558 if (2 == this.mode) { //can only zoom in 1-page mode
563 // $$$ with flexible zoom we could "snap" to /2 page reductions
564 // for better scaling
566 if (this.reduce <= 0.5) return;
567 this.reduce*=0.5; //zoom in
569 if (this.reduce >= 8) return;
570 this.reduce*=2; //zoom out
573 this.resizePageView();
575 $('#GBpageview').empty()
576 this.displayedIndices = [];
579 this.updateToolbarZoom(this.reduce);
583 //______________________________________________________________________________
584 GnuBook.prototype.resizePageView = function() {
587 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
588 var viewWidth = $('#GBcontainer').attr('clientWidth');
590 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
591 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
592 var oldPageViewHeight = $('#GBpageview').height();
593 var oldPageViewWidth = $('#GBpageview').width();
595 var oldCenterY = this.centerY1up();
596 var oldCenterX = this.centerX1up();
598 if (0 != oldPageViewHeight) {
599 var scrollRatio = oldCenterY / oldPageViewHeight;
604 for (i=0; i<this.numLeafs; i++) {
605 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
606 var width = parseInt(this.getPageWidth(i)/this.reduce);
607 if (width>viewWidth) viewWidth=width;
609 $('#GBpageview').height(viewHeight);
610 $('#GBpageview').width(viewWidth);
612 var newCenterY = scrollRatio*viewHeight;
613 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
614 $('#GBcontainer').attr('scrollTop', newTop);
616 // We use clientWidth here to avoid miscalculating due to scroll bar
617 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
618 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
619 newLeft = Math.max(newLeft, 0);
620 $('#GBcontainer').attr('scrollLeft', newLeft);
621 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
623 //this.centerPageView();
629 //______________________________________________________________________________
630 // Returns the current offset of the viewport center in scaled document coordinates.
631 GnuBook.prototype.centerX1up = function() {
633 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
634 centerX = $('#GBpageview').width();
636 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
638 centerX = Math.floor(centerX);
643 //______________________________________________________________________________
644 // Returns the current offset of the viewport center in scaled document coordinates.
645 GnuBook.prototype.centerY1up = function() {
646 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
647 return Math.floor(centerY);
651 //______________________________________________________________________________
652 GnuBook.prototype.centerPageView = function() {
654 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
655 var clientWidth = $('#GBcontainer').attr('clientWidth');
656 //console.log('sW='+scrollWidth+' cW='+clientWidth);
657 if (scrollWidth > clientWidth) {
658 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
663 // zoom2up(direction)
664 //______________________________________________________________________________
665 GnuBook.prototype.zoom2up = function(direction) {
667 // Hard stop autoplay
668 this.stopFlipAnimations();
670 // Get new zoom state
671 var newZoom = this.twoPageNextReduce(this.reduce, direction);
672 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
675 this.twoPage.autofit = newZoom.autofit;
676 this.reduce = newZoom.reduce;
678 // Preserve view center position
679 var oldCenter = this.twoPageGetViewCenter();
681 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
682 // $$$ An improvement would be to use the low res image until the larger one is loaded.
683 if (1 == direction) {
684 for (var img in this.prefetchedImgs) {
685 delete this.prefetchedImgs[img];
689 // Prepare view with new center to minimize visual glitches
690 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
694 // quantizeReduce(reduce)
695 //______________________________________________________________________________
696 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
697 GnuBook.prototype.quantizeReduce = function(reduce) {
698 var quantized = this.reductionFactors[0];
699 var distance = Math.abs(reduce - quantized);
700 for (var i = 1; i < this.reductionFactors.length; i++) {
701 newDistance = Math.abs(reduce - this.reductionFactors[i]);
702 if (newDistance < distance) {
703 distance = newDistance;
704 quantized = this.reductionFactors[i];
711 // twoPageNextReduce()
712 //______________________________________________________________________________
713 // Returns the next reduction level
714 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
716 var autofitReduce = this.twoPageGetAutofitReduce();
718 if (0 == direction) { // autofit
719 result.autofit = true;
720 result.reduce = autofitReduce;
722 } else if (1 == direction) { // zoom in
723 var newReduce = this.reductionFactors[0];
725 for (var i = 1; i < this.reductionFactors.length; i++) {
726 if (this.reductionFactors[i] < reduce) {
727 newReduce = this.reductionFactors[i];
731 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
733 result.autofit = true;
734 result.reduce = autofitReduce;
736 result.autofit = false;
737 result.reduce = newReduce;
741 var lastIndex = this.reductionFactors.length - 1;
742 var newReduce = this.reductionFactors[lastIndex];
744 for (var i = lastIndex; i >= 0; i--) {
745 if (this.reductionFactors[i] > reduce) {
746 newReduce = this.reductionFactors[i];
750 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
752 result.autofit = true;
753 result.reduce = autofitReduce;
755 result.autofit = false;
756 result.reduce = newReduce;
764 //______________________________________________________________________________
765 // Attempts to jump to page. Returns true if page could be found, false otherwise.
766 GnuBook.prototype.jumpToPage = function(pageNum) {
768 var pageIndex = this.getPageIndex(pageNum);
770 if ('undefined' != typeof(pageIndex)) {
773 this.jumpToIndex(pageIndex);
774 $('#GBcontainer').attr('scrollTop', leafTop);
783 //______________________________________________________________________________
784 GnuBook.prototype.jumpToIndex = function(index) {
786 if (2 == this.mode) {
789 // By checking against min/max we do nothing if requested index
791 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
792 this.flipBackToIndex(index);
793 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
794 this.flipFwdToIndex(index);
801 for (i=0; i<index; i++) {
802 h = parseInt(this.getPageHeight(i)/this.reduce);
803 leafTop += h + this.padding;
805 //$('#GBcontainer').attr('scrollTop', leafTop);
806 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
813 //______________________________________________________________________________
814 GnuBook.prototype.switchMode = function(mode) {
816 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
818 if (mode == this.mode) return;
820 if (!this.canSwitchToMode(mode)) {
825 this.removeSearchHilites();
829 this.switchToolbarMode(mode);
831 // $$$ TODO preserve center of view when switching between mode
832 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
835 this.reduce = this.quantizeReduce(this.reduce);
836 this.prepareOnePageView();
838 this.twoPage.autofit = false; // Take zoom level from other mode
839 this.reduce = this.quantizeReduce(this.reduce);
840 this.prepareTwoPageView();
841 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
846 //prepareOnePageView()
847 //______________________________________________________________________________
848 GnuBook.prototype.prepareOnePageView = function() {
850 // var startLeaf = this.displayedIndices[0];
851 var startLeaf = this.currentIndex();
853 $('#GBcontainer').empty();
854 $('#GBcontainer').css({
859 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
861 this.resizePageView();
863 this.jumpToIndex(startLeaf);
864 this.displayedIndices = [];
866 this.drawLeafsOnePage();
868 // Bind mouse handlers
869 // Disable mouse click to avoid selected/highlighted page images - bug 354239
870 gbPageView.bind('mousedown', function(e) {
871 // $$$ check here for right-click and don't disable. Also use jQuery style
872 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
875 // Special hack for IE7
876 gbPageView[0].onselectstart = function(e) { return false; };
879 // prepareTwoPageView()
880 //______________________________________________________________________________
881 // Some decisions about two page view:
883 // Both pages will be displayed at the same height, even if they were different physical/scanned
884 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
885 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
886 // aspect ratio to determine the height.
888 // The two page view div is resized to keep the middle of the book in the middle of the div
889 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
890 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
891 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
892 $('#GBcontainer').empty();
893 $('#GBcontainer').css('overflow', 'auto');
895 // We want to display two facing pages. We may be missing
896 // one side of the spread because it is the first/last leaf,
897 // foldouts, missing pages, etc
899 //var targetLeaf = this.displayedIndices[0];
900 var targetLeaf = this.firstIndex;
902 if (targetLeaf < this.firstDisplayableIndex()) {
903 targetLeaf = this.firstDisplayableIndex();
906 if (targetLeaf > this.lastDisplayableIndex()) {
907 targetLeaf = this.lastDisplayableIndex();
910 //this.twoPage.currentIndexL = null;
911 //this.twoPage.currentIndexR = null;
912 //this.pruneUnusedImgs();
914 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
915 this.twoPage.currentIndexL = currentSpreadIndices[0];
916 this.twoPage.currentIndexR = currentSpreadIndices[1];
917 this.firstIndex = this.twoPage.currentIndexL;
919 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
921 this.pruneUnusedImgs();
922 this.prefetch(); // Preload images or reload if scaling has changed
924 //console.dir(this.twoPage);
926 // Add the two page view
927 // $$$ Can we get everything set up and then append?
928 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
930 // $$$ calculate first then set
931 $('#GBtwopageview').css( {
932 height: this.twoPage.totalHeight + 'px',
933 width: this.twoPage.totalWidth + 'px',
937 // If there will not be scrollbars (e.g. when zooming out) we center the book
938 // since otherwise the book will be stuck off-center
939 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
940 centerPercentageX = 0.5;
942 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
943 centerPercentageY = 0.5;
946 this.twoPageCenterView(centerPercentageX, centerPercentageY);
948 this.twoPage.coverDiv = document.createElement('div');
949 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
950 border: '1px solid rgb(68, 25, 17)',
951 width: this.twoPage.bookCoverDivWidth + 'px',
952 height: this.twoPage.bookCoverDivHeight+'px',
953 visibility: 'visible',
954 position: 'absolute',
955 backgroundColor: '#663929',
956 left: this.twoPage.bookCoverDivLeft + 'px',
957 top: this.twoPage.bookCoverDivTop+'px',
958 MozBorderRadiusTopleft: '7px',
959 MozBorderRadiusTopright: '7px',
960 MozBorderRadiusBottomright: '7px',
961 MozBorderRadiusBottomleft: '7px'
962 }).appendTo('#GBtwopageview');
964 this.leafEdgeR = document.createElement('div');
965 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
966 $(this.leafEdgeR).css({
967 borderStyle: 'solid solid solid none',
968 borderColor: 'rgb(51, 51, 34)',
969 borderWidth: '1px 1px 1px 0px',
970 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
971 width: this.twoPage.leafEdgeWidthR + 'px',
972 height: this.twoPage.height-1 + 'px',
974 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
975 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
977 }).appendTo('#GBtwopageview');
979 this.leafEdgeL = document.createElement('div');
980 this.leafEdgeL.className = 'leafEdgeL';
981 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
982 borderStyle: 'solid none solid solid',
983 borderColor: 'rgb(51, 51, 34)',
984 borderWidth: '1px 0px 1px 1px',
985 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
986 width: this.twoPage.leafEdgeWidthL + 'px',
987 height: this.twoPage.height-1 + 'px',
988 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
989 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
991 }).appendTo('#GBtwopageview');
993 div = document.createElement('div');
994 $(div).attr('id', 'GBbookspine').css({
995 border: '1px solid rgb(68, 25, 17)',
996 width: this.twoPage.bookSpineDivWidth+'px',
997 height: this.twoPage.bookSpineDivHeight+'px',
998 position: 'absolute',
999 backgroundColor: 'rgb(68, 25, 17)',
1000 left: this.twoPage.bookSpineDivLeft+'px',
1001 top: this.twoPage.bookSpineDivTop+'px'
1002 }).appendTo('#GBtwopageview');
1004 var self = this; // for closure
1006 this.twoPage.leftFlipArea = document.createElement('div');
1007 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1009 width: this.twoPageFlipAreaWidth() + 'px',
1010 height: this.twoPageFlipAreaHeight() + 'px',
1011 position: 'absolute',
1012 left: this.twoPageLeftFlipAreaLeft() + 'px',
1013 top: this.twoPageFlipAreaTop() + 'px',
1016 }).bind('click', function(e) {
1018 }).bind('mousedown', function(e) {
1020 }).appendTo('#GBtwopageview');
1022 this.twoPage.rightFlipArea = document.createElement('div');
1023 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1025 width: this.twoPageFlipAreaWidth() + 'px',
1026 height: this.twoPageFlipAreaHeight() + 'px',
1027 position: 'absolute',
1028 left: this.twoPageRightFlipAreaLeft() + 'px',
1029 top: this.twoPageFlipAreaTop() + 'px',
1032 }).bind('click', function(e) {
1034 }).bind('mousedown', function(e) {
1036 }).appendTo('#GBtwopageview');
1038 this.prepareTwoPagePopUp();
1040 this.displayedIndices = [];
1042 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1043 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1045 this.drawLeafsTwoPage();
1046 this.updateSearchHilites2UP();
1047 this.updateToolbarZoom(this.reduce);
1052 // prepareTwoPagePopUp()
1054 // This function prepares the "View Page n" popup that shows while the mouse is
1055 // over the left/right "stack of sheets" edges. It also binds the mouse
1056 // events for these divs.
1057 //______________________________________________________________________________
1058 GnuBook.prototype.prepareTwoPagePopUp = function() {
1060 this.twoPagePopUp = document.createElement('div');
1061 $(this.twoPagePopUp).css({
1062 border: '1px solid black',
1064 position: 'absolute',
1065 fontFamily: 'sans-serif',
1068 backgroundColor: 'rgb(255, 255, 238)',
1070 }).appendTo('#GBcontainer');
1071 $(this.twoPagePopUp).hide();
1073 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1074 $(e.data.twoPagePopUp).show();
1077 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1078 $(e.data.twoPagePopUp).hide();
1081 $(this.leafEdgeL).bind('click', this, function(e) {
1083 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1084 e.data.jumpToIndex(jumpIndex);
1087 $(this.leafEdgeR).bind('click', this, function(e) {
1089 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1090 e.data.jumpToIndex(jumpIndex);
1093 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1095 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1096 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1098 // $$$ TODO: Make sure popup is positioned so that it is in view
1099 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1100 $(e.data.twoPagePopUp).css({
1101 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1102 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1106 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1108 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1109 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1111 // $$$ TODO: Make sure popup is positioned so that it is in view
1112 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1113 $(e.data.twoPagePopUp).css({
1114 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1115 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1120 // calculateSpreadSize()
1121 //______________________________________________________________________________
1122 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1123 // this.twoPage.currentIndexR
1124 // This function sets this.twoPage.height, twoPage.width
1126 GnuBook.prototype.calculateSpreadSize = function() {
1128 var firstIndex = this.twoPage.currentIndexL;
1129 var secondIndex = this.twoPage.currentIndexR;
1130 //console.log('first page is ' + firstIndex);
1132 // Calculate page sizes and total leaf width
1134 if ( this.twoPage.autofit) {
1135 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1137 // set based on reduction factor
1138 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1141 // Both pages together
1142 this.twoPage.height = spreadSize.height;
1143 this.twoPage.width = spreadSize.width;
1146 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1147 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1150 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1151 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1152 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1156 // The width of the book cover div. The combined width of both pages, twice the width
1157 // of the book cover internal padding (2*10) and the page edges
1158 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1159 // The height of the book cover div
1160 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1163 // We calculate the total width and height for the div so that we can make the book
1165 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1166 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1167 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1168 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1169 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1170 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1172 // We want to minimize the unused space in two-up mode (maximize the amount of page
1173 // shown). We give width to the leaf edges and these widths change (though the sum
1174 // of the two remains constant) as we flip through the book. With the book
1175 // cover centered and fixed in the GBcontainer div the page images will meet
1176 // at the "gutter" which is generally offset from the center.
1177 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1178 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1180 // The left edge of the book cover moves depending on the width of the pages
1181 // $$$ change to getter
1182 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1183 // The top edge of the book cover stays a fixed distance from the top
1184 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1187 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1188 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1189 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1192 this.reduce = spreadSize.reduce; // $$$ really set this here?
1195 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1198 // We check which page is closest to a "normal" page and use that to set the height
1199 // for both pages. This means that foldouts and other odd size pages will be displayed
1200 // smaller than the nominal zoom amount.
1201 var canon5Dratio = 1.5;
1204 height: this.getPageHeight(firstIndex),
1205 width: this.getPageWidth(firstIndex)
1209 height: this.getPageHeight(secondIndex),
1210 width: this.getPageWidth(secondIndex)
1213 var firstIndexRatio = first.height / first.width;
1214 var secondIndexRatio = second.height / second.width;
1215 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1218 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1219 ratio = firstIndexRatio;
1220 //console.log('using firstIndexRatio ' + ratio);
1222 ratio = secondIndexRatio;
1223 //console.log('using secondIndexRatio ' + ratio);
1226 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1227 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1228 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1230 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1231 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1233 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1234 ideal.width -= 10; // $$$ fudge factor
1235 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1236 ideal.height -= 20; // fudge factor
1237 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1239 if (ideal.height/ratio <= ideal.width) {
1241 ideal.width = parseInt(ideal.height/ratio);
1244 ideal.height = parseInt(ideal.width*ratio);
1247 // $$$ check this logic with large spreads
1248 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1253 // getSpreadSizeFromReduce()
1254 //______________________________________________________________________________
1255 // Returns the spread size calculated from the reduction factor for the given pages
1256 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1257 var spreadSize = {};
1258 // $$$ Scale this based on reduce?
1259 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1260 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1261 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1263 // $$$ Possibly incorrect -- we should make height "dominant"
1264 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1265 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1266 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1267 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1268 spreadSize.reduce = reduce;
1273 // twoPageGetAutofitReduce()
1274 //______________________________________________________________________________
1275 // Returns the current ideal reduction factor
1276 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1277 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1278 return spreadSize.reduce;
1281 // twoPageSetCursor()
1282 //______________________________________________________________________________
1283 // Set the cursor for two page view
1284 GnuBook.prototype.twoPageSetCursor = function() {
1285 // console.log('setting cursor');
1286 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1287 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1288 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1289 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1291 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1292 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1297 //______________________________________________________________________________
1298 // Returns the currently active index.
1299 GnuBook.prototype.currentIndex = function() {
1300 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1301 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1302 return this.firstIndex;
1304 throw 'currentIndex called for unimplemented mode ' + this.mode;
1309 //______________________________________________________________________________
1310 // Flip the right page over onto the left
1311 GnuBook.prototype.right = function() {
1312 if ('rl' != this.pageProgression) {
1322 //______________________________________________________________________________
1323 // Flip to the rightmost page
1324 GnuBook.prototype.rightmost = function() {
1325 if ('rl' != this.pageProgression) {
1333 //______________________________________________________________________________
1334 // Flip the left page over onto the right.
1335 GnuBook.prototype.left = function() {
1336 if ('rl' != this.pageProgression) {
1346 //______________________________________________________________________________
1347 // Flip to the leftmost page
1348 GnuBook.prototype.leftmost = function() {
1349 if ('rl' != this.pageProgression) {
1357 //______________________________________________________________________________
1358 GnuBook.prototype.next = function() {
1359 if (2 == this.mode) {
1361 this.flipFwdToIndex(null);
1363 if (this.firstIndex < this.lastDisplayableIndex()) {
1364 this.jumpToIndex(this.firstIndex+1);
1370 //______________________________________________________________________________
1371 GnuBook.prototype.prev = function() {
1372 if (2 == this.mode) {
1374 this.flipBackToIndex(null);
1376 if (this.firstIndex >= 1) {
1377 this.jumpToIndex(this.firstIndex-1);
1382 GnuBook.prototype.first = function() {
1383 if (2 == this.mode) {
1384 this.jumpToIndex(2);
1387 this.jumpToIndex(0);
1391 GnuBook.prototype.last = function() {
1392 if (2 == this.mode) {
1393 this.jumpToIndex(this.lastDisplayableIndex());
1396 this.jumpToIndex(this.lastDisplayableIndex());
1400 // flipBackToIndex()
1401 //______________________________________________________________________________
1402 // to flip back one spread, pass index=null
1403 GnuBook.prototype.flipBackToIndex = function(index) {
1404 if (1 == this.mode) return;
1406 var leftIndex = this.twoPage.currentIndexL;
1408 // $$$ Need to change this to be able to see first spread.
1409 // See https://bugs.launchpad.net/gnubook/+bug/296788
1410 if (leftIndex <= 2) return;
1411 if (this.animating) return;
1413 if (null != this.leafEdgeTmp) {
1414 alert('error: leafEdgeTmp should be null!');
1418 if (null == index) {
1419 index = leftIndex-2;
1421 //if (index<0) return;
1423 var previousIndices = this.getSpreadIndices(index);
1425 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1429 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1431 this.animating = true;
1433 if ('rl' != this.pageProgression) {
1434 // Assume LTR and we are going backward
1435 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1436 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1438 // RTL and going backward
1439 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1440 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1444 // flipLeftToRight()
1445 //______________________________________________________________________________
1446 // Flips the page on the left towards the page on the right
1447 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1449 var leftLeaf = this.twoPage.currentIndexL;
1451 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1452 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1453 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1455 var currWidthL = this.getPageWidth2UP(leftLeaf);
1456 var newWidthL = this.getPageWidth2UP(newIndexL);
1457 var newWidthR = this.getPageWidth2UP(newIndexR);
1459 var top = this.twoPageTop();
1460 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1462 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1463 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1465 //animation strategy:
1466 // 0. remove search highlight, if any.
1467 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1468 // of the left leaf and where the user clicked in the leaf edge.
1469 // Note that if this function was triggered by left() and not a
1470 // mouse click, the width of leafEdgeTmp is very small (zero px).
1471 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1472 // leftLeaf to width=0.
1473 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1474 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1475 // its new full width.
1476 // 4. After step 3 is finished, do the following:
1477 // - remove leafEdgeTmp from the dom.
1478 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1479 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1480 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1481 // and width=newLeafEdgeWidthL.
1482 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1483 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1484 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1485 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1486 // - prefetch new adjacent leafs.
1487 // - set up click handlers for both new left and right leafs.
1488 // - redraw the search highlight.
1489 // - update the pagenum box and the url.
1492 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1494 this.leafEdgeTmp = document.createElement('div');
1495 $(this.leafEdgeTmp).css({
1496 borderStyle: 'solid none solid solid',
1497 borderColor: 'rgb(51, 51, 34)',
1498 borderWidth: '1px 0px 1px 1px',
1499 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1500 width: leafEdgeTmpW + 'px',
1501 height: this.twoPage.height-1 + 'px',
1502 left: leftEdgeTmpLeft + 'px',
1504 position: 'absolute',
1506 }).appendTo('#GBtwopageview');
1508 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1509 $(this.leafEdgeL).css({
1510 width: newLeafEdgeWidthL+'px',
1511 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1514 // Left gets the offset of the current left leaf from the document
1515 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1516 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1517 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1519 // We change the left leaf to right positioning
1520 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1521 $(this.prefetchedImgs[leftLeaf]).css({
1526 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1527 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1531 this.removeSearchHilites();
1533 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1534 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1536 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1537 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1539 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1540 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1541 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1543 $(self.leafEdgeR).css({
1544 // Moves the right leaf edge
1545 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1546 left: gutter+newWidthR+'px'
1549 $(self.leafEdgeL).css({
1550 // Moves and resizes the left leaf edge
1551 width: newLeafEdgeWidthL+'px',
1552 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1555 // Resizes the brown border div
1556 $(self.twoPage.coverDiv).css({
1557 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1558 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1561 $(self.leafEdgeTmp).remove();
1562 self.leafEdgeTmp = null;
1564 // $$$ TODO refactor with opposite direction flip
1565 self.twoPage.currentIndexL = newIndexL;
1566 self.twoPage.currentIndexR = newIndexR;
1567 self.twoPage.scaledWL = newWidthL;
1568 self.twoPage.scaledWR = newWidthR;
1569 self.firstIndex = self.twoPage.currentIndexL;
1570 self.displayedIndices = [newIndexL, newIndexR];
1571 self.setClickHandlers();
1572 self.twoPageSetCursor();
1573 self.pruneUnusedImgs();
1575 self.animating = false;
1577 self.updateSearchHilites2UP();
1578 self.updatePageNumBox2UP();
1580 self.twoPagePlaceFlipAreas();
1582 if (self.animationFinishedCallback) {
1583 self.animationFinishedCallback();
1584 self.animationFinishedCallback = null;
1592 //______________________________________________________________________________
1593 // Whether we flip left or right is dependent on the page progression
1594 // to flip forward one spread, pass index=null
1595 GnuBook.prototype.flipFwdToIndex = function(index) {
1597 if (this.animating) return;
1599 if (null != this.leafEdgeTmp) {
1600 alert('error: leafEdgeTmp should be null!');
1604 if (null == index) {
1605 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1607 if (index > this.lastDisplayableIndex()) return;
1609 this.animating = true;
1611 var nextIndices = this.getSpreadIndices(index);
1613 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1615 if ('rl' != this.pageProgression) {
1616 // We did not specify RTL
1617 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1618 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1621 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1622 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1626 // flipRightToLeft(nextL, nextR, gutter)
1627 // $$$ better not to have to pass gutter in
1628 //______________________________________________________________________________
1629 // Flip from left to right and show the nextL and nextR indices on those sides
1630 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1631 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1632 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1633 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1634 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1636 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1638 var top = this.twoPageTop();
1639 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1641 var middle = this.twoPage.middle;
1642 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1644 this.leafEdgeTmp = document.createElement('div');
1645 $(this.leafEdgeTmp).css({
1646 borderStyle: 'solid none solid solid',
1647 borderColor: 'rgb(51, 51, 34)',
1648 borderWidth: '1px 0px 1px 1px',
1649 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1650 width: leafEdgeTmpW + 'px',
1651 height: this.twoPage.height-1 + 'px',
1652 left: gutter+scaledW+'px',
1654 position: 'absolute',
1656 }).appendTo('#GBtwopageview');
1658 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1659 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1661 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1662 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1663 var newWidthL = this.getPageWidth2UP(newIndexL);
1664 var newWidthR = this.getPageWidth2UP(newIndexR);
1666 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1668 var self = this; // closure-tastic!
1670 var speed = this.flipSpeed;
1672 this.removeSearchHilites();
1674 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1675 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1676 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1677 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1678 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1680 $(self.leafEdgeL).css({
1681 width: newLeafEdgeWidthL+'px',
1682 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1685 // Resizes the book cover
1686 $(self.twoPage.coverDiv).css({
1687 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1688 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1691 $(self.leafEdgeTmp).remove();
1692 self.leafEdgeTmp = null;
1694 self.twoPage.currentIndexL = newIndexL;
1695 self.twoPage.currentIndexR = newIndexR;
1696 self.twoPage.scaledWL = newWidthL;
1697 self.twoPage.scaledWR = newWidthR;
1699 self.firstIndex = self.twoPage.currentIndexL;
1700 self.displayedIndices = [newIndexL, newIndexR];
1701 self.setClickHandlers();
1702 self.twoPageSetCursor();
1703 self.pruneUnusedImgs();
1705 self.animating = false;
1708 self.updateSearchHilites2UP();
1709 self.updatePageNumBox2UP();
1711 self.twoPagePlaceFlipAreas();
1713 if (self.animationFinishedCallback) {
1714 self.animationFinishedCallback();
1715 self.animationFinishedCallback = null;
1722 //______________________________________________________________________________
1723 GnuBook.prototype.setClickHandlers = function() {
1726 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1731 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1738 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1739 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1743 //______________________________________________________________________________
1744 GnuBook.prototype.prefetchImg = function(index) {
1745 var pageURI = this.getPageURI(index);
1747 // Load image if not loaded or URI has changed (e.g. due to scaling)
1748 var loadImage = false;
1749 if (undefined == this.prefetchedImgs[index]) {
1750 //console.log('no image for ' + index);
1752 } else if (pageURI != this.prefetchedImgs[index].uri) {
1753 //console.log('uri changed for ' + index);
1758 //console.log('prefetching ' + index);
1759 var img = document.createElement("img");
1761 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1762 this.prefetchedImgs[index] = img;
1767 // prepareFlipLeftToRight()
1769 //______________________________________________________________________________
1771 // Prepare to flip the left page towards the right. This corresponds to moving
1772 // backward when the page progression is left to right.
1773 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1775 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1777 this.prefetchImg(prevL);
1778 this.prefetchImg(prevR);
1780 var height = this.getPageHeight(prevL);
1781 var width = this.getPageWidth(prevL);
1782 var middle = this.twoPage.middle;
1783 var top = this.twoPageTop();
1784 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1786 // The gutter is the dividing line between the left and right pages.
1787 // It is offset from the middle to create the illusion of thickness to the pages
1788 var gutter = middle + this.gutterOffsetForIndex(prevL);
1790 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1791 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1792 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1794 $(this.prefetchedImgs[prevL]).css({
1795 position: 'absolute',
1796 left: gutter-scaledW+'px',
1797 right: '', // clear right property
1799 backgroundColor: 'rgb(234, 226, 205)',
1800 height: this.twoPage.height,
1801 width: scaledW+'px',
1802 borderRight: '1px solid black',
1806 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1808 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1810 $(this.prefetchedImgs[prevR]).css({
1811 position: 'absolute',
1815 backgroundColor: 'rgb(234, 226, 205)',
1816 height: this.twoPage.height,
1818 borderLeft: '1px solid black',
1822 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1826 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1827 // prepareFlipRightToLeft()
1828 //______________________________________________________________________________
1829 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1831 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1834 this.prefetchImg(nextL);
1835 this.prefetchImg(nextR);
1837 var height = this.getPageHeight(nextR);
1838 var width = this.getPageWidth(nextR);
1839 var middle = this.twoPage.middle;
1840 var top = this.twoPageTop();
1841 var scaledW = this.twoPage.height*width/height;
1843 var gutter = middle + this.gutterOffsetForIndex(nextL);
1845 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1846 $(this.prefetchedImgs[nextR]).css({
1847 position: 'absolute',
1850 backgroundColor: 'rgb(234, 226, 205)',
1851 height: this.twoPage.height,
1852 width: scaledW+'px',
1853 borderLeft: '1px solid black',
1857 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1859 height = this.getPageHeight(nextL);
1860 width = this.getPageWidth(nextL);
1861 scaledW = this.twoPage.height*width/height;
1863 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1864 $(this.prefetchedImgs[nextL]).css({
1865 position: 'absolute',
1866 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1868 backgroundColor: 'rgb(234, 226, 205)',
1869 height: this.twoPage.height,
1870 width: 0+'px', // Start at 0 width, then grow to the left
1871 borderRight: '1px solid black',
1875 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1879 // getNextLeafs() -- NOT RTL AWARE
1880 //______________________________________________________________________________
1881 // GnuBook.prototype.getNextLeafs = function(o) {
1882 // //TODO: we might have two left or two right leafs in a row (damaged book)
1883 // //For now, assume that leafs are contiguous.
1885 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1886 // o.L = this.twoPage.currentIndexL+2;
1887 // o.R = this.twoPage.currentIndexL+3;
1890 // getprevLeafs() -- NOT RTL AWARE
1891 //______________________________________________________________________________
1892 // GnuBook.prototype.getPrevLeafs = function(o) {
1893 // //TODO: we might have two left or two right leafs in a row (damaged book)
1894 // //For now, assume that leafs are contiguous.
1896 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1897 // o.L = this.twoPage.currentIndexL-2;
1898 // o.R = this.twoPage.currentIndexL-1;
1901 // pruneUnusedImgs()
1902 //______________________________________________________________________________
1903 GnuBook.prototype.pruneUnusedImgs = function() {
1904 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1905 for (var key in this.prefetchedImgs) {
1906 //console.log('key is ' + key);
1907 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1908 //console.log('removing key '+ key);
1909 $(this.prefetchedImgs[key]).remove();
1911 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1912 //console.log('deleting key '+ key);
1913 delete this.prefetchedImgs[key];
1919 //______________________________________________________________________________
1920 GnuBook.prototype.prefetch = function() {
1922 // prefetch visible pages first
1923 this.prefetchImg(this.twoPage.currentIndexL);
1924 this.prefetchImg(this.twoPage.currentIndexR);
1926 var adjacentPagesToLoad = 3;
1928 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1929 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1931 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
1932 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
1934 // Load images spreading out from current
1935 for (var i = 1; i <= adjacentPagesToLoad; i++) {
1936 var goingDown = lowCurrent - i;
1937 if (goingDown >= start) {
1938 this.prefetchImg(goingDown);
1940 var goingUp = highCurrent + i;
1941 if (goingUp <= end) {
1942 this.prefetchImg(goingUp);
1947 var lim = this.twoPage.currentIndexL-4;
1949 lim = Math.max(lim, 0);
1950 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1951 this.prefetchImg(i);
1954 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1955 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1956 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1957 this.prefetchImg(i);
1963 // getPageWidth2UP()
1964 //______________________________________________________________________________
1965 GnuBook.prototype.getPageWidth2UP = function(index) {
1966 // We return the width based on the dominant height
1967 var height = this.getPageHeight(index);
1968 var width = this.getPageWidth(index);
1969 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1973 //______________________________________________________________________________
1974 GnuBook.prototype.search = function(term) {
1975 $('#GnuBookSearchScript').remove();
1976 var script = document.createElement("script");
1977 script.setAttribute('id', 'GnuBookSearchScript');
1978 script.setAttribute("type", "text/javascript");
1979 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1980 document.getElementsByTagName('head')[0].appendChild(script);
1981 $('#GnuBookSearchResults').html('Searching...');
1984 // GBSearchCallback()
1985 //______________________________________________________________________________
1986 GnuBook.prototype.GBSearchCallback = function(txt) {
1988 if (jQuery.browser.msie) {
1989 var dom=new ActiveXObject("Microsoft.XMLDOM");
1993 var parser = new DOMParser();
1994 var dom = parser.parseFromString(txt, "text/xml");
1997 $('#GnuBookSearchResults').empty();
1998 $('#GnuBookSearchResults').append('<ul>');
2000 for (var key in this.searchResults) {
2001 if (null != this.searchResults[key].div) {
2002 $(this.searchResults[key].div).remove();
2004 delete this.searchResults[key];
2007 var pages = dom.getElementsByTagName('PAGE');
2009 if (0 == pages.length) {
2010 // $$$ it would be nice to echo the (sanitized) search result here
2011 $('#GnuBookSearchResults').append('<li>No search results found</li>');
2013 for (var i = 0; i < pages.length; i++){
2014 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2017 var re = new RegExp (/_(\d{4})/);
2018 var reMatch = re.exec(pages[i].getAttribute('file'));
2019 var index = parseInt(reMatch[1], 10);
2020 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2022 var children = pages[i].childNodes;
2024 for (var j=0; j<children.length; j++) {
2025 //console.log(j + ' - ' + children[j].nodeName);
2026 //console.log(children[j].firstChild.nodeValue);
2027 if ('CONTEXT' == children[j].nodeName) {
2028 context += children[j].firstChild.nodeValue;
2029 } else if ('WORD' == children[j].nodeName) {
2030 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2032 var index = this.leafNumToIndex(index);
2033 if (null != index) {
2034 //coordinates are [left, bottom, right, top, [baseline]]
2035 //we'll skip baseline for now...
2036 var coords = children[j].getAttribute('coords').split(',',4);
2037 if (4 == coords.length) {
2038 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
2043 var pageName = this.getPageName(index);
2044 //TODO: remove hardcoded instance name
2045 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
2048 $('#GnuBookSearchResults').append('</ul>');
2050 this.updateSearchHilites();
2053 // updateSearchHilites()
2054 //______________________________________________________________________________
2055 GnuBook.prototype.updateSearchHilites = function() {
2056 if (2 == this.mode) {
2057 this.updateSearchHilites2UP();
2059 this.updateSearchHilites1UP();
2063 // showSearchHilites1UP()
2064 //______________________________________________________________________________
2065 GnuBook.prototype.updateSearchHilites1UP = function() {
2067 for (var key in this.searchResults) {
2069 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2070 var result = this.searchResults[key];
2071 if(null == result.div) {
2072 result.div = document.createElement('div');
2073 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2074 //console.log('appending ' + key);
2077 width: (result.r-result.l)/this.reduce + 'px',
2078 height: (result.b-result.t)/this.reduce + 'px',
2079 left: (result.l)/this.reduce + 'px',
2080 top: (result.t)/this.reduce +'px'
2084 //console.log(key + ' not displayed');
2085 this.searchResults[key].div=null;
2091 //______________________________________________________________________________
2092 // Returns the position of the gutter (line between the page images)
2093 GnuBook.prototype.twoPageGutter = function() {
2094 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2098 //______________________________________________________________________________
2099 // Returns the offset for the top of the page images
2100 GnuBook.prototype.twoPageTop = function() {
2101 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2104 // twoPageCoverWidth()
2105 //______________________________________________________________________________
2106 // Returns the width of the cover div given the total page width
2107 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2108 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2111 // twoPageGetViewCenter()
2112 //______________________________________________________________________________
2113 // Returns the percentage offset into twopageview div at the center of container div
2114 // { percentageX: float, percentageY: float }
2115 GnuBook.prototype.twoPageGetViewCenter = function() {
2118 var containerOffset = $('#GBcontainer').offset();
2119 var viewOffset = $('#GBtwopageview').offset();
2120 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2121 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2126 // twoPageCenterView(percentageX, percentageY)
2127 //______________________________________________________________________________
2128 // Centers the point given by percentage from left,top of twopageview
2129 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2130 if ('undefined' == typeof(percentageX)) {
2133 if ('undefined' == typeof(percentageY)) {
2137 var viewWidth = $('#GBtwopageview').width();
2138 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2139 var intoViewX = percentageX * viewWidth;
2141 var viewHeight = $('#GBtwopageview').height();
2142 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2143 var intoViewY = percentageY * viewHeight;
2145 if (viewWidth < containerClientWidth) {
2146 // Can fit width without scrollbars - center by adjusting offset
2147 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2149 // Need to scroll to center
2150 $('#GBtwopageview').css('left', 0);
2151 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2154 if (viewHeight < containerClientHeight) {
2155 // Fits with scrollbars - add offset
2156 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2158 $('#GBtwopageview').css('top', 0);
2159 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2163 // twoPageFlipAreaHeight
2164 //______________________________________________________________________________
2165 // Returns the integer height of the click-to-flip areas at the edges of the book
2166 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2167 return parseInt(this.twoPage.height);
2170 // twoPageFlipAreaWidth
2171 //______________________________________________________________________________
2172 // Returns the integer width of the flip areas
2173 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2174 var max = 100; // $$$ TODO base on view width?
2177 var width = this.twoPage.width * 0.15;
2178 return parseInt(GnuBook.util.clamp(width, min, max));
2181 // twoPageFlipAreaTop
2182 //______________________________________________________________________________
2183 // Returns integer top offset for flip areas
2184 GnuBook.prototype.twoPageFlipAreaTop = function() {
2185 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2188 // twoPageLeftFlipAreaLeft
2189 //______________________________________________________________________________
2190 // Left offset for left flip area
2191 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2192 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2195 // twoPageRightFlipAreaLeft
2196 //______________________________________________________________________________
2197 // Left offset for right flip area
2198 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2199 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2202 // twoPagePlaceFlipAreas
2203 //______________________________________________________________________________
2204 // Readjusts position of flip areas based on current layout
2205 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2206 // We don't set top since it shouldn't change relative to view
2207 $(this.twoPage.leftFlipArea).css({
2208 left: this.twoPageLeftFlipAreaLeft() + 'px'
2210 $(this.twoPage.rightFlipArea).css({
2211 left: this.twoPageRightFlipAreaLeft() + 'px'
2215 // showSearchHilites2UP()
2216 //______________________________________________________________________________
2217 GnuBook.prototype.updateSearchHilites2UP = function() {
2219 for (var key in this.searchResults) {
2220 key = parseInt(key, 10);
2221 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2222 var result = this.searchResults[key];
2223 if(null == result.div) {
2224 result.div = document.createElement('div');
2225 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2226 //console.log('appending ' + key);
2229 // We calculate the reduction factor for the specific page because it can be different
2230 // for each page in the spread
2231 var height = this.getPageHeight(key);
2232 var width = this.getPageWidth(key)
2233 var reduce = this.twoPage.height/height;
2234 var scaledW = parseInt(width*reduce);
2236 var gutter = this.twoPageGutter();
2238 if ('L' == this.getPageSide(key)) {
2239 pageL = gutter-scaledW;
2243 var pageT = this.twoPageTop();
2246 width: (result.r-result.l)*reduce + 'px',
2247 height: (result.b-result.t)*reduce + 'px',
2248 left: pageL+(result.l)*reduce + 'px',
2249 top: pageT+(result.t)*reduce +'px'
2253 //console.log(key + ' not displayed');
2254 if (null != this.searchResults[key].div) {
2255 //console.log('removing ' + key);
2256 $(this.searchResults[key].div).remove();
2258 this.searchResults[key].div=null;
2263 // removeSearchHilites()
2264 //______________________________________________________________________________
2265 GnuBook.prototype.removeSearchHilites = function() {
2266 for (var key in this.searchResults) {
2267 if (null != this.searchResults[key].div) {
2268 $(this.searchResults[key].div).remove();
2269 this.searchResults[key].div=null;
2275 //______________________________________________________________________________
2276 GnuBook.prototype.showEmbedCode = function() {
2277 if (null != this.embedPopup) { // check if already showing
2281 this.embedPopup = document.createElement("div");
2282 $(this.embedPopup).css({
2283 position: 'absolute',
2285 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2288 border: "3px double #999999",
2290 backgroundColor: "#fff"
2291 }).appendTo('#GnuBook');
2293 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2294 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>';
2295 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2296 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2298 this.embedPopup.innerHTML = htmlStr;
2299 $(this.embedPopup).find('input').bind('click', function() {
2305 //______________________________________________________________________________
2306 GnuBook.prototype.autoToggle = function() {
2308 var bComingFrom1up = false;
2309 if (2 != this.mode) {
2310 bComingFrom1up = true;
2314 // Change to autofit if book is too large
2315 if (this.reduce < this.twoPageGetAutofitReduce()) {
2320 if (null == this.autoTimer) {
2321 this.flipSpeed = 2000;
2323 // $$$ Draw events currently cause layout problems when they occur during animation.
2324 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2325 // we workaround for now by not triggering immediate animation in that case.
2326 // See https://bugs.launchpad.net/gnubook/+bug/328327
2327 if (('rl' == this.pageProgression) && bComingFrom1up) {
2328 // don't flip immediately -- wait until timer fires
2331 this.flipFwdToIndex();
2334 $('#GBtoolbar .play').hide();
2335 $('#GBtoolbar .pause').show();
2336 this.autoTimer=setInterval(function(){
2337 if (self.animating) {return;}
2339 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2340 self.flipBackToIndex(1); // $$$ really what we want?
2342 self.flipFwdToIndex();
2351 //______________________________________________________________________________
2352 // Stop autoplay mode, allowing animations to finish
2353 GnuBook.prototype.autoStop = function() {
2354 if (null != this.autoTimer) {
2355 clearInterval(this.autoTimer);
2356 this.flipSpeed = 'fast';
2357 $('#GBtoolbar .pause').hide();
2358 $('#GBtoolbar .play').show();
2359 this.autoTimer = null;
2363 // stopFlipAnimations
2364 //______________________________________________________________________________
2365 // Immediately stop flip animations. Callbacks are triggered.
2366 GnuBook.prototype.stopFlipAnimations = function() {
2368 this.autoStop(); // Clear timers
2370 // Stop animation, clear queue, trigger callbacks
2371 if (this.leafEdgeTmp) {
2372 $(this.leafEdgeTmp).stop(false, true);
2374 jQuery.each(this.prefetchedImgs, function() {
2375 $(this).stop(false, true);
2378 // And again since animations also queued in callbacks
2379 if (this.leafEdgeTmp) {
2380 $(this.leafEdgeTmp).stop(false, true);
2382 jQuery.each(this.prefetchedImgs, function() {
2383 $(this).stop(false, true);
2388 // keyboardNavigationIsDisabled(event)
2389 // - returns true if keyboard navigation should be disabled for the event
2390 //______________________________________________________________________________
2391 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2392 if (event.target.tagName == "INPUT") {
2398 // gutterOffsetForIndex
2399 //______________________________________________________________________________
2401 // Returns the gutter offset for the spread containing the given index.
2402 // This function supports RTL
2403 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2405 // To find the offset of the gutter from the middle we calculate our percentage distance
2406 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2407 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2409 // But then again for RTL it's the opposite
2410 if ('rl' == this.pageProgression) {
2418 //______________________________________________________________________________
2419 // Returns the width of the leaf edge div for the page with index given
2420 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2421 // $$$ could there be single pixel rounding errors for L vs R?
2422 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2423 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2425 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2429 // jumpIndexForLeftEdgePageX
2430 //______________________________________________________________________________
2431 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2432 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2433 if ('rl' != this.pageProgression) {
2434 // LTR - flipping backward
2435 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2437 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2438 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2442 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2443 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2448 // jumpIndexForRightEdgePageX
2449 //______________________________________________________________________________
2450 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2451 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2452 if ('rl' != this.pageProgression) {
2454 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2455 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2458 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2459 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2464 GnuBook.prototype.initToolbar = function(mode, ui) {
2466 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2467 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2468 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2469 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2470 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2471 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2472 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2473 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2476 this.updateToolbarZoom(this.reduce); // Pretty format
2478 if (ui == "embed") {
2479 $("#GnuBook a.logo").attr("target","_blank");
2482 // $$$ turn this into a member variable
2483 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2485 // We build in mode 2
2486 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2487 + "<button class='GBicon rollover embed' />"
2488 + "<form class='GBpageform' action='javascript:' onsubmit='gb.jumpToPage(this.elements[0].value)'> <span class='label'>Page:<input id='GBpagenum' type='text' size='3' onfocus='gb.autoStop();'></input></span></form>"
2489 + "<div class='GBtoolbarmode2' style='display: none'><button class='GBicon rollover book_leftmost' /><button class='GBicon rollover book_left' /><button class='GBicon rollover book_right' /><button class='GBicon rollover book_rightmost' /></div>"
2490 + "<div class='GBtoolbarmode1' style='display: none'><button class='GBicon rollover book_top' /><button class='GBicon rollover book_up' /> <button class='GBicon rollover book_down' /><button class='GBicon rollover book_bottom' /></div>"
2491 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2493 this.bindToolbarNavHandlers(jToolbar);
2495 // Setup tooltips -- later we could load these from a file for i18n
2496 var titles = { '.logo': 'Go to Archive.org',
2497 '.zoom_in': 'Zoom in',
2498 '.zoom_out': 'Zoom out',
2499 '.one_page_mode': 'One-page view',
2500 '.two_page_mode': 'Two-page view',
2501 '.embed': 'Embed bookreader',
2502 '.book_left': 'Flip left',
2503 '.book_right': 'Flip right',
2504 '.book_up': 'Page up',
2505 '.book_down': 'Page down',
2508 '.book_top': 'First page',
2509 '.book_bottom': 'Last page'
2511 if ('rl' == this.pageProgression) {
2512 titles['.book_leftmost'] = 'Last page';
2513 titles['.book_rightmost'] = 'First page';
2515 titles['.book_leftmost'] = 'First page';
2516 titles['.book_rightmost'] = 'Last page';
2519 for (var icon in titles) {
2520 jToolbar.find(icon).attr('title', titles[icon]);
2523 // Hide mode buttons and autoplay if 2up is not available
2524 // $$$ if we end up with more than two modes we should show the applicable buttons
2525 if ( !this.canSwitchToMode(this.constMode2up) ) {
2526 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2529 // Switch to requested mode -- binds other click handlers
2530 this.switchToolbarMode(mode);
2535 // switchToolbarMode
2536 //______________________________________________________________________________
2537 // Update the toolbar for the given mode (changes navigation buttons)
2538 // $$$ we should soon split the toolbar out into its own module
2539 GnuBook.prototype.switchToolbarMode = function(mode) {
2542 $('#GBtoolbar .GBtoolbarmode2').hide();
2543 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2546 $('#GBtoolbar .GBtoolbarmode1').hide();
2547 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2551 // bindToolbarNavHandlers
2552 //______________________________________________________________________________
2553 // Binds the toolbar handlers
2554 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2556 jToolbar.find('.book_left').bind('click', function(e) {
2561 jToolbar.find('.book_right').bind('click', function(e) {
2566 jToolbar.find('.book_up').bind('click', function(e) {
2571 jToolbar.find('.book_down').bind('click', function(e) {
2576 jToolbar.find('.embed').bind('click', function(e) {
2581 jToolbar.find('.play').bind('click', function(e) {
2586 jToolbar.find('.pause').bind('click', function(e) {
2591 jToolbar.find('.book_top').bind('click', function(e) {
2596 jToolbar.find('.book_bottom').bind('click', function(e) {
2601 jToolbar.find('.book_leftmost').bind('click', function(e) {
2606 jToolbar.find('.book_rightmost').bind('click', function(e) {
2612 // updateToolbarZoom(reduce)
2613 //______________________________________________________________________________
2614 // Update the displayed zoom factor based on reduction factor
2615 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2617 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2620 value = (100 / reduce).toFixed(2);
2621 // Strip trailing zeroes and decimal if all zeroes
2622 value = value.replace(/0+$/,'');
2623 value = value.replace(/\.$/,'');
2626 $('#GBzoom').text(value);
2629 // firstDisplayableIndex
2630 //______________________________________________________________________________
2631 // Returns the index of the first visible page, dependent on the mode.
2632 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2633 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2634 GnuBook.prototype.firstDisplayableIndex = function() {
2635 if (this.mode == 0) {
2638 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2642 // lastDisplayableIndex
2643 //______________________________________________________________________________
2644 // Returns the index of the last visible page, dependent on the mode.
2645 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2646 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2647 GnuBook.prototype.lastDisplayableIndex = function() {
2648 if (this.mode == 2) {
2649 if (this.lastDisplayableIndex2up === null) {
2650 // Calculate and cache
2651 var candidate = this.numLeafs - 1;
2652 for ( ; candidate >= 0; candidate--) {
2653 var spreadIndices = this.getSpreadIndices(candidate);
2654 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2658 this.lastDisplayableIndex2up = candidate;
2660 return this.lastDisplayableIndex2up;
2662 return this.numLeafs - 1;
2666 // shortTitle(maximumCharacters)
2668 // Returns a shortened version of the title with the maximum number of characters
2669 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2670 if (this.bookTitle.length < maximumCharacters) {
2671 return this.bookTitle;
2674 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2681 // Parameter related functions
2683 // updateFromParams(params)
2685 // Update ourselves from the params object.
2687 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2688 GnuBook.prototype.updateFromParams = function(params) {
2689 if ('undefined' != typeof(params.mode)) {
2690 this.switchMode(params.mode);
2693 // $$$ process /search
2694 // $$$ process /zoom
2696 // We only respect page if index is not set
2697 if ('undefined' != typeof(params.index)) {
2698 if (params.index != this.currentIndex()) {
2699 this.jumpToIndex(params.index);
2701 } else if ('undefined' != typeof(params.page)) {
2702 // $$$ this assumes page numbers are unique
2703 if (params.page != this.getPageNum(this.currentIndex())) {
2704 this.jumpToPage(params.page);
2708 // $$$ process /region
2709 // $$$ process /highlight
2712 // paramsFromFragment(urlFragment)
2714 // Returns a object with configuration parametes from a URL fragment.
2716 // E.g paramsFromFragment(window.location.hash)
2717 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2718 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2722 // For convenience we allow an initial # character (as from window.location.hash)
2723 // but don't require it
2724 if (urlFragment.substr(0,1) == '#') {
2725 urlFragment = urlFragment.substr(1);
2728 // Simple #nn syntax
2729 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2730 if ( !isNaN(oldStyleLeafNum) ) {
2731 params.index = oldStyleLeafNum;
2733 // Done processing if using old-style syntax
2737 // Split into key-value pairs
2738 var urlArray = urlFragment.split('/');
2740 for (var i = 0; i < urlArray.length; i += 2) {
2741 urlHash[urlArray[i]] = urlArray[i+1];
2745 if ('1up' == urlHash['mode']) {
2746 params.mode = this.constMode1up;
2747 } else if ('2up' == urlHash['mode']) {
2748 params.mode = this.constMode2up;
2752 if ('undefined' != typeof(urlHash['page'])) {
2753 // page was set -- may not be int
2754 params.page = urlHash['page'];
2757 // $$$ process /region
2758 // $$$ process /search
2759 // $$$ process /highlight
2764 // paramsFromCurrent()
2766 // Create a params object from the current parameters.
2767 GnuBook.prototype.paramsFromCurrent = function() {
2771 var pageNum = this.getPageNum(this.currentIndex());
2772 if ((pageNum === 0) || pageNum) {
2773 params.page = pageNum;
2776 params.index = this.currentIndex();
2777 params.mode = this.mode;
2786 // fragmentFromParams(params)
2788 // Create a fragment string from the params object.
2789 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2790 GnuBook.prototype.fragmentFromParams = function(params) {
2791 var separator = '/';
2795 if ('undefined' != typeof(params.page)) {
2796 fragments.push('page', params.page);
2798 // Don't have page numbering -- use index instead
2799 fragments.push('page', 'n' + params.index);
2807 if ('undefined' != typeof(params.mode)) {
2808 if (params.mode == this.constMode1up) {
2809 fragments.push('mode', '1up');
2810 } else if (params.mode == this.constMode2up) {
2811 fragments.push('mode', '2up');
2813 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2817 return fragments.join(separator);
2820 // getPageIndex(pageNum)
2822 // Returns the *highest* index the given page number, or undefined
2823 GnuBook.prototype.getPageIndex = function(pageNum) {
2824 var pageIndices = this.getPageIndices(pageNum);
2826 if (pageIndices.length > 0) {
2827 return pageIndices[pageIndices.length - 1];
2833 // getPageIndices(pageNum)
2835 // Returns an array (possibly empty) of the indices with the given page number
2836 GnuBook.prototype.getPageIndices = function(pageNum) {
2839 // Check for special "nXX" page number
2840 if (pageNum.slice(0,1) == 'n') {
2842 var pageIntStr = pageNum.slice(1, pageNum.length);
2843 var pageIndex = parseInt(pageIntStr);
2844 indices.append(pageIndex);
2847 // Do nothing... will run through page names and see if one matches
2852 for (i=0; i<this.numLeafs; i++) {
2853 if (this.getPageNum(i) == pageNum) {
2861 // getPageName(index)
2863 // Returns the name of the page as it should be displayed in the user interface
2864 GnuBook.prototype.getPageName = function(index) {
2865 return 'Page ' + this.getPageNum(index);
2868 // updateLocationHash
2870 // Update the location hash from the current parameters. Call this instead of manually
2871 // using window.location.replace
2872 GnuBook.prototype.updateLocationHash = function() {
2873 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2874 window.location.replace(newHash);
2876 // This is the variable checked in the timer. Only user-generated changes
2877 // to the URL will trigger the event.
2878 this.oldLocationHash = newHash;
2881 // startLocationPolling
2883 // Starts polling of window.location to see hash fragment changes
2884 GnuBook.prototype.startLocationPolling = function() {
2885 var self = this; // remember who I am
2886 self.oldLocationHash = window.location.hash;
2888 if (this.locationPollId) {
2889 clearInterval(this.locationPollID);
2890 this.locationPollId = null;
2893 this.locationPollId = setInterval(function() {
2894 var newHash = window.location.hash;
2895 if (newHash != self.oldLocationHash) {
2896 if (newHash != self.oldUserHash) { // Only process new user hash once
2897 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2899 // Queue change if animating
2900 if (self.animating) {
2902 self.animationFinishedCallback = function() {
2903 self.updateFromParams(self.paramsFromFragment(newHash));
2905 } else { // update immediately
2906 self.updateFromParams(self.paramsFromFragment(newHash));
2908 self.oldUserHash = newHash;
2916 // Returns a URL for an embedded version of the current book
2917 GnuBook.prototype.getEmbedURL = function() {
2918 // We could generate a URL hash fragment here but for now we just leave at defaults
2919 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2924 // Returns the embed code HTML fragment suitable for copy and paste
2925 GnuBook.prototype.getEmbedCode = function() {
2926 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2931 // Returns true if we can switch to the requested mode
2932 GnuBook.prototype.canSwitchToMode = function(mode) {
2933 if (mode == this.constMode2up) {
2934 // check there are enough pages to display
2935 // $$$ this is a workaround for the mis-feature that we can't display
2936 // short books in 2up mode
2937 if (this.numLeafs < 6) {
2945 // Library functions
2947 clamp: function(value, min, max) {
2948 return Math.min(Math.max(value, min), max);