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 // Prepare view with new center to minimize visual glitches
682 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
686 // quantizeReduce(reduce)
687 //______________________________________________________________________________
688 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
689 GnuBook.prototype.quantizeReduce = function(reduce) {
690 var quantized = this.reductionFactors[0];
691 var distance = Math.abs(reduce - quantized);
692 for (var i = 1; i < this.reductionFactors.length; i++) {
693 newDistance = Math.abs(reduce - this.reductionFactors[i]);
694 if (newDistance < distance) {
695 distance = newDistance;
696 quantized = this.reductionFactors[i];
703 // twoPageNextReduce()
704 //______________________________________________________________________________
705 // Returns the next reduction level
706 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
708 var autofitReduce = this.twoPageGetAutofitReduce();
710 if (0 == direction) { // autofit
711 result.autofit = true;
712 result.reduce = autofitReduce;
714 } else if (1 == direction) { // zoom in
715 var newReduce = this.reductionFactors[0];
717 for (var i = 1; i < this.reductionFactors.length; i++) {
718 if (this.reductionFactors[i] < reduce) {
719 newReduce = this.reductionFactors[i];
723 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
725 result.autofit = true;
726 result.reduce = autofitReduce;
728 result.autofit = false;
729 result.reduce = newReduce;
733 var lastIndex = this.reductionFactors.length - 1;
734 var newReduce = this.reductionFactors[lastIndex];
736 for (var i = lastIndex; i >= 0; i--) {
737 if (this.reductionFactors[i] > reduce) {
738 newReduce = this.reductionFactors[i];
742 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
744 result.autofit = true;
745 result.reduce = autofitReduce;
747 result.autofit = false;
748 result.reduce = newReduce;
756 //______________________________________________________________________________
757 // Attempts to jump to page. Returns true if page could be found, false otherwise.
758 GnuBook.prototype.jumpToPage = function(pageNum) {
760 var pageIndex = this.getPageIndex(pageNum);
762 if ('undefined' != typeof(pageIndex)) {
765 this.jumpToIndex(pageIndex);
766 $('#GBcontainer').attr('scrollTop', leafTop);
775 //______________________________________________________________________________
776 GnuBook.prototype.jumpToIndex = function(index) {
778 if (2 == this.mode) {
781 // By checking against min/max we do nothing if requested index
783 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
784 this.flipBackToIndex(index);
785 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
786 this.flipFwdToIndex(index);
793 for (i=0; i<index; i++) {
794 h = parseInt(this.getPageHeight(i)/this.reduce);
795 leafTop += h + this.padding;
797 //$('#GBcontainer').attr('scrollTop', leafTop);
798 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
805 //______________________________________________________________________________
806 GnuBook.prototype.switchMode = function(mode) {
808 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
810 if (mode == this.mode) return;
812 if (!this.canSwitchToMode(mode)) {
817 this.removeSearchHilites();
821 this.switchToolbarMode(mode);
823 // $$$ TODO preserve center of view when switching between mode
824 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
827 this.reduce = this.quantizeReduce(this.reduce);
828 this.prepareOnePageView();
830 this.twoPage.autofit = false; // Take zoom level from other mode
831 this.reduce = this.quantizeReduce(this.reduce);
832 this.prepareTwoPageView();
833 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
838 //prepareOnePageView()
839 //______________________________________________________________________________
840 GnuBook.prototype.prepareOnePageView = function() {
842 // var startLeaf = this.displayedIndices[0];
843 var startLeaf = this.currentIndex();
845 $('#GBcontainer').empty();
846 $('#GBcontainer').css({
851 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
853 this.resizePageView();
855 this.jumpToIndex(startLeaf);
856 this.displayedIndices = [];
858 this.drawLeafsOnePage();
860 // Bind mouse handlers
861 // Disable mouse click to avoid selected/highlighted page images - bug 354239
862 gbPageView.bind('mousedown', function(e) {
863 // $$$ check here for right-click and don't disable. Also use jQuery style
864 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
867 // Special hack for IE7
868 gbPageView[0].onselectstart = function(e) { return false; };
871 // prepareTwoPageView()
872 //______________________________________________________________________________
873 // Some decisions about two page view:
875 // Both pages will be displayed at the same height, even if they were different physical/scanned
876 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
877 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
878 // aspect ratio to determine the height.
880 // The two page view div is resized to keep the middle of the book in the middle of the div
881 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
882 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
883 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
884 $('#GBcontainer').empty();
885 $('#GBcontainer').css('overflow', 'auto');
887 // We want to display two facing pages. We may be missing
888 // one side of the spread because it is the first/last leaf,
889 // foldouts, missing pages, etc
891 //var targetLeaf = this.displayedIndices[0];
892 var targetLeaf = this.firstIndex;
894 if (targetLeaf < this.firstDisplayableIndex()) {
895 targetLeaf = this.firstDisplayableIndex();
898 if (targetLeaf > this.lastDisplayableIndex()) {
899 targetLeaf = this.lastDisplayableIndex();
902 this.twoPage.currentIndexL = null;
903 this.twoPage.currentIndexR = null;
904 this.pruneUnusedImgs();
906 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
907 this.twoPage.currentIndexL = currentSpreadIndices[0];
908 this.twoPage.currentIndexR = currentSpreadIndices[1];
909 this.firstIndex = this.twoPage.currentIndexL;
911 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
913 //console.dir(this.twoPage);
915 // Add the two page view
916 // $$$ Can we get everything set up and then append?
917 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
919 // $$$ calculate first then set
920 $('#GBtwopageview').css( {
921 height: this.twoPage.totalHeight + 'px',
922 width: this.twoPage.totalWidth + 'px',
926 // If there will not be scrollbars (e.g. when zooming out) we center the book
927 // since otherwise the book will be stuck off-center
928 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
929 centerPercentageX = 0.5;
931 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
932 centerPercentageY = 0.5;
935 this.twoPageCenterView(centerPercentageX, centerPercentageY);
937 this.twoPage.coverDiv = document.createElement('div');
938 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
939 border: '1px solid rgb(68, 25, 17)',
940 width: this.twoPage.bookCoverDivWidth + 'px',
941 height: this.twoPage.bookCoverDivHeight+'px',
942 visibility: 'visible',
943 position: 'absolute',
944 backgroundColor: '#663929',
945 left: this.twoPage.bookCoverDivLeft + 'px',
946 top: this.twoPage.bookCoverDivTop+'px',
947 MozBorderRadiusTopleft: '7px',
948 MozBorderRadiusTopright: '7px',
949 MozBorderRadiusBottomright: '7px',
950 MozBorderRadiusBottomleft: '7px'
951 }).appendTo('#GBtwopageview');
953 this.leafEdgeR = document.createElement('div');
954 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
955 $(this.leafEdgeR).css({
956 borderStyle: 'solid solid solid none',
957 borderColor: 'rgb(51, 51, 34)',
958 borderWidth: '1px 1px 1px 0px',
959 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
960 width: this.twoPage.leafEdgeWidthR + 'px',
961 height: this.twoPage.height-1 + 'px',
963 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
964 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
966 }).appendTo('#GBtwopageview');
968 this.leafEdgeL = document.createElement('div');
969 this.leafEdgeL.className = 'leafEdgeL';
970 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
971 borderStyle: 'solid none solid solid',
972 borderColor: 'rgb(51, 51, 34)',
973 borderWidth: '1px 0px 1px 1px',
974 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
975 width: this.twoPage.leafEdgeWidthL + 'px',
976 height: this.twoPage.height-1 + 'px',
977 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
978 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
980 }).appendTo('#GBtwopageview');
982 div = document.createElement('div');
983 $(div).attr('id', 'GBbookspine').css({
984 border: '1px solid rgb(68, 25, 17)',
985 width: this.twoPage.bookSpineDivWidth+'px',
986 height: this.twoPage.bookSpineDivHeight+'px',
987 position: 'absolute',
988 backgroundColor: 'rgb(68, 25, 17)',
989 left: this.twoPage.bookSpineDivLeft+'px',
990 top: this.twoPage.bookSpineDivTop+'px'
991 }).appendTo('#GBtwopageview');
993 var self = this; // for closure
995 this.twoPage.leftFlipArea = document.createElement('div');
996 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
998 width: this.twoPageFlipAreaWidth() + 'px',
999 height: this.twoPageFlipAreaHeight() + 'px',
1000 position: 'absolute',
1001 left: this.twoPageLeftFlipAreaLeft() + 'px',
1002 top: this.twoPageFlipAreaTop() + 'px',
1005 }).bind('click', function(e) {
1007 }).bind('mousedown', function(e) {
1009 }).appendTo('#GBtwopageview');
1011 this.twoPage.rightFlipArea = document.createElement('div');
1012 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1014 width: this.twoPageFlipAreaWidth() + 'px',
1015 height: this.twoPageFlipAreaHeight() + 'px',
1016 position: 'absolute',
1017 left: this.twoPageRightFlipAreaLeft() + 'px',
1018 top: this.twoPageFlipAreaTop() + 'px',
1021 }).bind('click', function(e) {
1023 }).bind('mousedown', function(e) {
1025 }).appendTo('#GBtwopageview');
1027 this.prepareTwoPagePopUp();
1029 this.displayedIndices = [];
1031 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1032 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1034 this.drawLeafsTwoPage();
1035 this.updateSearchHilites2UP();
1036 this.updateToolbarZoom(this.reduce);
1041 // prepareTwoPagePopUp()
1043 // This function prepares the "View Page n" popup that shows while the mouse is
1044 // over the left/right "stack of sheets" edges. It also binds the mouse
1045 // events for these divs.
1046 //______________________________________________________________________________
1047 GnuBook.prototype.prepareTwoPagePopUp = function() {
1049 this.twoPagePopUp = document.createElement('div');
1050 $(this.twoPagePopUp).css({
1051 border: '1px solid black',
1053 position: 'absolute',
1054 fontFamily: 'sans-serif',
1057 backgroundColor: 'rgb(255, 255, 238)',
1059 }).appendTo('#GBcontainer');
1060 $(this.twoPagePopUp).hide();
1062 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1063 $(e.data.twoPagePopUp).show();
1066 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1067 $(e.data.twoPagePopUp).hide();
1070 $(this.leafEdgeL).bind('click', this, function(e) {
1072 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1073 e.data.jumpToIndex(jumpIndex);
1076 $(this.leafEdgeR).bind('click', this, function(e) {
1078 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1079 e.data.jumpToIndex(jumpIndex);
1082 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1084 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1085 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1087 // $$$ TODO: Make sure popup is positioned so that it is in view
1088 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1089 $(e.data.twoPagePopUp).css({
1090 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1091 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1095 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1097 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1098 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1100 // $$$ TODO: Make sure popup is positioned so that it is in view
1101 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1102 $(e.data.twoPagePopUp).css({
1103 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1104 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1109 // calculateSpreadSize()
1110 //______________________________________________________________________________
1111 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1112 // this.twoPage.currentIndexR
1113 // This function sets this.twoPage.height, twoPage.width
1115 GnuBook.prototype.calculateSpreadSize = function() {
1117 var firstIndex = this.twoPage.currentIndexL;
1118 var secondIndex = this.twoPage.currentIndexR;
1119 //console.log('first page is ' + firstIndex);
1121 // Calculate page sizes and total leaf width
1123 if ( this.twoPage.autofit) {
1124 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1126 // set based on reduction factor
1127 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1130 // Both pages together
1131 this.twoPage.height = spreadSize.height;
1132 this.twoPage.width = spreadSize.width;
1135 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1136 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1139 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1140 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1141 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1145 // The width of the book cover div. The combined width of both pages, twice the width
1146 // of the book cover internal padding (2*10) and the page edges
1147 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1148 // The height of the book cover div
1149 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1152 // We calculate the total width and height for the div so that we can make the book
1154 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1155 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1156 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1157 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1158 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1159 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1161 // We want to minimize the unused space in two-up mode (maximize the amount of page
1162 // shown). We give width to the leaf edges and these widths change (though the sum
1163 // of the two remains constant) as we flip through the book. With the book
1164 // cover centered and fixed in the GBcontainer div the page images will meet
1165 // at the "gutter" which is generally offset from the center.
1166 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1167 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1169 // The left edge of the book cover moves depending on the width of the pages
1170 // $$$ change to getter
1171 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1172 // The top edge of the book cover stays a fixed distance from the top
1173 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1176 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1177 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1178 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1181 this.reduce = spreadSize.reduce; // $$$ really set this here?
1184 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1187 // We check which page is closest to a "normal" page and use that to set the height
1188 // for both pages. This means that foldouts and other odd size pages will be displayed
1189 // smaller than the nominal zoom amount.
1190 var canon5Dratio = 1.5;
1193 height: this.getPageHeight(firstIndex),
1194 width: this.getPageWidth(firstIndex)
1198 height: this.getPageHeight(secondIndex),
1199 width: this.getPageWidth(secondIndex)
1202 var firstIndexRatio = first.height / first.width;
1203 var secondIndexRatio = second.height / second.width;
1204 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1207 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1208 ratio = firstIndexRatio;
1209 //console.log('using firstIndexRatio ' + ratio);
1211 ratio = secondIndexRatio;
1212 //console.log('using secondIndexRatio ' + ratio);
1215 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1216 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1217 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1219 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1220 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1222 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1223 ideal.width -= 10; // $$$ fudge factor
1224 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1225 ideal.height -= 20; // fudge factor
1226 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1228 if (ideal.height/ratio <= ideal.width) {
1230 ideal.width = parseInt(ideal.height/ratio);
1233 ideal.height = parseInt(ideal.width*ratio);
1236 // $$$ check this logic with large spreads
1237 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1242 // getSpreadSizeFromReduce()
1243 //______________________________________________________________________________
1244 // Returns the spread size calculated from the reduction factor for the given pages
1245 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1246 var spreadSize = {};
1247 // $$$ Scale this based on reduce?
1248 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1249 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1250 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1252 // $$$ Possibly incorrect -- we should make height "dominant"
1253 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1254 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1255 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1256 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1257 spreadSize.reduce = reduce;
1262 // twoPageGetAutofitReduce()
1263 //______________________________________________________________________________
1264 // Returns the current ideal reduction factor
1265 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1266 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1267 return spreadSize.reduce;
1270 // twoPageSetCursor()
1271 //______________________________________________________________________________
1272 // Set the cursor for two page view
1273 GnuBook.prototype.twoPageSetCursor = function() {
1274 // console.log('setting cursor');
1275 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1276 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1277 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1278 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1280 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1281 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1286 //______________________________________________________________________________
1287 // Returns the currently active index.
1288 GnuBook.prototype.currentIndex = function() {
1289 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1290 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1291 return this.firstIndex;
1293 throw 'currentIndex called for unimplemented mode ' + this.mode;
1298 //______________________________________________________________________________
1299 // Flip the right page over onto the left
1300 GnuBook.prototype.right = function() {
1301 if ('rl' != this.pageProgression) {
1311 //______________________________________________________________________________
1312 // Flip to the rightmost page
1313 GnuBook.prototype.rightmost = function() {
1314 if ('rl' != this.pageProgression) {
1322 //______________________________________________________________________________
1323 // Flip the left page over onto the right.
1324 GnuBook.prototype.left = function() {
1325 if ('rl' != this.pageProgression) {
1335 //______________________________________________________________________________
1336 // Flip to the leftmost page
1337 GnuBook.prototype.leftmost = function() {
1338 if ('rl' != this.pageProgression) {
1346 //______________________________________________________________________________
1347 GnuBook.prototype.next = function() {
1348 if (2 == this.mode) {
1350 this.flipFwdToIndex(null);
1352 if (this.firstIndex < this.lastDisplayableIndex()) {
1353 this.jumpToIndex(this.firstIndex+1);
1359 //______________________________________________________________________________
1360 GnuBook.prototype.prev = function() {
1361 if (2 == this.mode) {
1363 this.flipBackToIndex(null);
1365 if (this.firstIndex >= 1) {
1366 this.jumpToIndex(this.firstIndex-1);
1371 GnuBook.prototype.first = function() {
1372 if (2 == this.mode) {
1373 this.jumpToIndex(2);
1376 this.jumpToIndex(0);
1380 GnuBook.prototype.last = function() {
1381 if (2 == this.mode) {
1382 this.jumpToIndex(this.lastDisplayableIndex());
1385 this.jumpToIndex(this.lastDisplayableIndex());
1389 // flipBackToIndex()
1390 //______________________________________________________________________________
1391 // to flip back one spread, pass index=null
1392 GnuBook.prototype.flipBackToIndex = function(index) {
1393 if (1 == this.mode) return;
1395 var leftIndex = this.twoPage.currentIndexL;
1397 // $$$ Need to change this to be able to see first spread.
1398 // See https://bugs.launchpad.net/gnubook/+bug/296788
1399 if (leftIndex <= 2) return;
1400 if (this.animating) return;
1402 if (null != this.leafEdgeTmp) {
1403 alert('error: leafEdgeTmp should be null!');
1407 if (null == index) {
1408 index = leftIndex-2;
1410 //if (index<0) return;
1412 var previousIndices = this.getSpreadIndices(index);
1414 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1418 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1420 this.animating = true;
1422 if ('rl' != this.pageProgression) {
1423 // Assume LTR and we are going backward
1424 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1425 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1427 // RTL and going backward
1428 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1429 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1433 // flipLeftToRight()
1434 //______________________________________________________________________________
1435 // Flips the page on the left towards the page on the right
1436 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1438 var leftLeaf = this.twoPage.currentIndexL;
1440 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1441 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1442 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1444 var currWidthL = this.getPageWidth2UP(leftLeaf);
1445 var newWidthL = this.getPageWidth2UP(newIndexL);
1446 var newWidthR = this.getPageWidth2UP(newIndexR);
1448 var top = this.twoPageTop();
1449 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1451 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1452 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1454 //animation strategy:
1455 // 0. remove search highlight, if any.
1456 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1457 // of the left leaf and where the user clicked in the leaf edge.
1458 // Note that if this function was triggered by left() and not a
1459 // mouse click, the width of leafEdgeTmp is very small (zero px).
1460 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1461 // leftLeaf to width=0.
1462 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1463 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1464 // its new full width.
1465 // 4. After step 3 is finished, do the following:
1466 // - remove leafEdgeTmp from the dom.
1467 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1468 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1469 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1470 // and width=newLeafEdgeWidthL.
1471 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1472 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1473 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1474 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1475 // - prefetch new adjacent leafs.
1476 // - set up click handlers for both new left and right leafs.
1477 // - redraw the search highlight.
1478 // - update the pagenum box and the url.
1481 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1483 this.leafEdgeTmp = document.createElement('div');
1484 $(this.leafEdgeTmp).css({
1485 borderStyle: 'solid none solid solid',
1486 borderColor: 'rgb(51, 51, 34)',
1487 borderWidth: '1px 0px 1px 1px',
1488 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1489 width: leafEdgeTmpW + 'px',
1490 height: this.twoPage.height-1 + 'px',
1491 left: leftEdgeTmpLeft + 'px',
1493 position: 'absolute',
1495 }).appendTo('#GBtwopageview');
1497 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1498 $(this.leafEdgeL).css({
1499 width: newLeafEdgeWidthL+'px',
1500 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1503 // Left gets the offset of the current left leaf from the document
1504 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1505 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1506 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1508 // We change the left leaf to right positioning
1509 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1510 $(this.prefetchedImgs[leftLeaf]).css({
1515 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1516 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1520 this.removeSearchHilites();
1522 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1523 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1525 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1526 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1528 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1529 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1530 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1532 $(self.leafEdgeR).css({
1533 // Moves the right leaf edge
1534 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1535 left: gutter+newWidthR+'px'
1538 $(self.leafEdgeL).css({
1539 // Moves and resizes the left leaf edge
1540 width: newLeafEdgeWidthL+'px',
1541 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1544 // Resizes the brown border div
1545 $(self.twoPage.coverDiv).css({
1546 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1547 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1550 $(self.leafEdgeTmp).remove();
1551 self.leafEdgeTmp = null;
1553 // $$$ TODO refactor with opposite direction flip
1554 self.twoPage.currentIndexL = newIndexL;
1555 self.twoPage.currentIndexR = newIndexR;
1556 self.twoPage.scaledWL = newWidthL;
1557 self.twoPage.scaledWR = newWidthR;
1558 self.firstIndex = self.twoPage.currentIndexL;
1559 self.displayedIndices = [newIndexL, newIndexR];
1560 self.setClickHandlers();
1561 self.twoPageSetCursor();
1562 self.pruneUnusedImgs();
1564 self.animating = false;
1566 self.updateSearchHilites2UP();
1567 self.updatePageNumBox2UP();
1569 self.twoPagePlaceFlipAreas();
1571 if (self.animationFinishedCallback) {
1572 self.animationFinishedCallback();
1573 self.animationFinishedCallback = null;
1581 //______________________________________________________________________________
1582 // Whether we flip left or right is dependent on the page progression
1583 // to flip forward one spread, pass index=null
1584 GnuBook.prototype.flipFwdToIndex = function(index) {
1586 if (this.animating) return;
1588 if (null != this.leafEdgeTmp) {
1589 alert('error: leafEdgeTmp should be null!');
1593 if (null == index) {
1594 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1596 if (index > this.lastDisplayableIndex()) return;
1598 this.animating = true;
1600 var nextIndices = this.getSpreadIndices(index);
1602 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1604 if ('rl' != this.pageProgression) {
1605 // We did not specify RTL
1606 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1607 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1610 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1611 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1615 // flipRightToLeft(nextL, nextR, gutter)
1616 // $$$ better not to have to pass gutter in
1617 //______________________________________________________________________________
1618 // Flip from left to right and show the nextL and nextR indices on those sides
1619 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1620 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1621 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1622 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1623 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1625 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1627 var top = this.twoPageTop();
1628 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1630 var middle = this.twoPage.middle;
1631 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1633 this.leafEdgeTmp = document.createElement('div');
1634 $(this.leafEdgeTmp).css({
1635 borderStyle: 'solid none solid solid',
1636 borderColor: 'rgb(51, 51, 34)',
1637 borderWidth: '1px 0px 1px 1px',
1638 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1639 width: leafEdgeTmpW + 'px',
1640 height: this.twoPage.height-1 + 'px',
1641 left: gutter+scaledW+'px',
1643 position: 'absolute',
1645 }).appendTo('#GBtwopageview');
1647 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1648 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1650 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1651 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1652 var newWidthL = this.getPageWidth2UP(newIndexL);
1653 var newWidthR = this.getPageWidth2UP(newIndexR);
1655 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1657 var self = this; // closure-tastic!
1659 var speed = this.flipSpeed;
1661 this.removeSearchHilites();
1663 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1664 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1665 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1666 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1667 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1669 $(self.leafEdgeL).css({
1670 width: newLeafEdgeWidthL+'px',
1671 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1674 // Resizes the book cover
1675 $(self.twoPage.coverDiv).css({
1676 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1677 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1680 $(self.leafEdgeTmp).remove();
1681 self.leafEdgeTmp = null;
1683 self.twoPage.currentIndexL = newIndexL;
1684 self.twoPage.currentIndexR = newIndexR;
1685 self.twoPage.scaledWL = newWidthL;
1686 self.twoPage.scaledWR = newWidthR;
1688 self.firstIndex = self.twoPage.currentIndexL;
1689 self.displayedIndices = [newIndexL, newIndexR];
1690 self.setClickHandlers();
1691 self.twoPageSetCursor();
1692 self.pruneUnusedImgs();
1694 self.animating = false;
1697 self.updateSearchHilites2UP();
1698 self.updatePageNumBox2UP();
1700 self.twoPagePlaceFlipAreas();
1702 if (self.animationFinishedCallback) {
1703 self.animationFinishedCallback();
1704 self.animationFinishedCallback = null;
1711 //______________________________________________________________________________
1712 GnuBook.prototype.setClickHandlers = function() {
1715 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1720 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1727 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1728 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1732 //______________________________________________________________________________
1733 GnuBook.prototype.prefetchImg = function(index) {
1734 if (undefined == this.prefetchedImgs[index]) {
1735 //console.log('prefetching ' + index);
1736 var img = document.createElement("img");
1737 img.src = this.getPageURI(index);
1738 this.prefetchedImgs[index] = img;
1743 // prepareFlipLeftToRight()
1745 //______________________________________________________________________________
1747 // Prepare to flip the left page towards the right. This corresponds to moving
1748 // backward when the page progression is left to right.
1749 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1751 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1753 this.prefetchImg(prevL);
1754 this.prefetchImg(prevR);
1756 var height = this.getPageHeight(prevL);
1757 var width = this.getPageWidth(prevL);
1758 var middle = this.twoPage.middle;
1759 var top = this.twoPageTop();
1760 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1762 // The gutter is the dividing line between the left and right pages.
1763 // It is offset from the middle to create the illusion of thickness to the pages
1764 var gutter = middle + this.gutterOffsetForIndex(prevL);
1766 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1767 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1768 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1770 $(this.prefetchedImgs[prevL]).css({
1771 position: 'absolute',
1772 left: gutter-scaledW+'px',
1773 right: '', // clear right property
1775 backgroundColor: 'rgb(234, 226, 205)',
1776 height: this.twoPage.height,
1777 width: scaledW+'px',
1778 borderRight: '1px solid black',
1782 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1784 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1786 $(this.prefetchedImgs[prevR]).css({
1787 position: 'absolute',
1791 backgroundColor: 'rgb(234, 226, 205)',
1792 height: this.twoPage.height,
1794 borderLeft: '1px solid black',
1798 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1802 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1803 // prepareFlipRightToLeft()
1804 //______________________________________________________________________________
1805 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1807 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1810 this.prefetchImg(nextL);
1811 this.prefetchImg(nextR);
1813 var height = this.getPageHeight(nextR);
1814 var width = this.getPageWidth(nextR);
1815 var middle = this.twoPage.middle;
1816 var top = this.twoPageTop();
1817 var scaledW = this.twoPage.height*width/height;
1819 var gutter = middle + this.gutterOffsetForIndex(nextL);
1821 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1822 $(this.prefetchedImgs[nextR]).css({
1823 position: 'absolute',
1826 backgroundColor: 'rgb(234, 226, 205)',
1827 height: this.twoPage.height,
1828 width: scaledW+'px',
1829 borderLeft: '1px solid black',
1833 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1835 height = this.getPageHeight(nextL);
1836 width = this.getPageWidth(nextL);
1837 scaledW = this.twoPage.height*width/height;
1839 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1840 $(this.prefetchedImgs[nextL]).css({
1841 position: 'absolute',
1842 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1844 backgroundColor: 'rgb(234, 226, 205)',
1845 height: this.twoPage.height,
1846 width: 0+'px', // Start at 0 width, then grow to the left
1847 borderRight: '1px solid black',
1851 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1855 // getNextLeafs() -- NOT RTL AWARE
1856 //______________________________________________________________________________
1857 // GnuBook.prototype.getNextLeafs = function(o) {
1858 // //TODO: we might have two left or two right leafs in a row (damaged book)
1859 // //For now, assume that leafs are contiguous.
1861 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1862 // o.L = this.twoPage.currentIndexL+2;
1863 // o.R = this.twoPage.currentIndexL+3;
1866 // getprevLeafs() -- NOT RTL AWARE
1867 //______________________________________________________________________________
1868 // GnuBook.prototype.getPrevLeafs = function(o) {
1869 // //TODO: we might have two left or two right leafs in a row (damaged book)
1870 // //For now, assume that leafs are contiguous.
1872 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1873 // o.L = this.twoPage.currentIndexL-2;
1874 // o.R = this.twoPage.currentIndexL-1;
1877 // pruneUnusedImgs()
1878 //______________________________________________________________________________
1879 GnuBook.prototype.pruneUnusedImgs = function() {
1880 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1881 for (var key in this.prefetchedImgs) {
1882 //console.log('key is ' + key);
1883 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1884 //console.log('removing key '+ key);
1885 $(this.prefetchedImgs[key]).remove();
1887 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1888 //console.log('deleting key '+ key);
1889 delete this.prefetchedImgs[key];
1895 //______________________________________________________________________________
1896 GnuBook.prototype.prefetch = function() {
1898 var lim = this.twoPage.currentIndexL-4;
1900 lim = Math.max(lim, 0);
1901 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1902 this.prefetchImg(i);
1905 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1906 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1907 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1908 this.prefetchImg(i);
1913 // getPageWidth2UP()
1914 //______________________________________________________________________________
1915 GnuBook.prototype.getPageWidth2UP = function(index) {
1916 // We return the width based on the dominant height
1917 var height = this.getPageHeight(index);
1918 var width = this.getPageWidth(index);
1919 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1923 //______________________________________________________________________________
1924 GnuBook.prototype.search = function(term) {
1925 $('#GnuBookSearchScript').remove();
1926 var script = document.createElement("script");
1927 script.setAttribute('id', 'GnuBookSearchScript');
1928 script.setAttribute("type", "text/javascript");
1929 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1930 document.getElementsByTagName('head')[0].appendChild(script);
1931 $('#GnuBookSearchResults').html('Searching...');
1934 // GBSearchCallback()
1935 //______________________________________________________________________________
1936 GnuBook.prototype.GBSearchCallback = function(txt) {
1938 if (jQuery.browser.msie) {
1939 var dom=new ActiveXObject("Microsoft.XMLDOM");
1943 var parser = new DOMParser();
1944 var dom = parser.parseFromString(txt, "text/xml");
1947 $('#GnuBookSearchResults').empty();
1948 $('#GnuBookSearchResults').append('<ul>');
1950 for (var key in this.searchResults) {
1951 if (null != this.searchResults[key].div) {
1952 $(this.searchResults[key].div).remove();
1954 delete this.searchResults[key];
1957 var pages = dom.getElementsByTagName('PAGE');
1959 if (0 == pages.length) {
1960 // $$$ it would be nice to echo the (sanitized) search result here
1961 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1963 for (var i = 0; i < pages.length; i++){
1964 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1967 var re = new RegExp (/_(\d{4})/);
1968 var reMatch = re.exec(pages[i].getAttribute('file'));
1969 var index = parseInt(reMatch[1], 10);
1970 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1972 var children = pages[i].childNodes;
1974 for (var j=0; j<children.length; j++) {
1975 //console.log(j + ' - ' + children[j].nodeName);
1976 //console.log(children[j].firstChild.nodeValue);
1977 if ('CONTEXT' == children[j].nodeName) {
1978 context += children[j].firstChild.nodeValue;
1979 } else if ('WORD' == children[j].nodeName) {
1980 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1982 var index = this.leafNumToIndex(index);
1983 if (null != index) {
1984 //coordinates are [left, bottom, right, top, [baseline]]
1985 //we'll skip baseline for now...
1986 var coords = children[j].getAttribute('coords').split(',',4);
1987 if (4 == coords.length) {
1988 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1993 var pageName = this.getPageName(index);
1994 //TODO: remove hardcoded instance name
1995 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1998 $('#GnuBookSearchResults').append('</ul>');
2000 this.updateSearchHilites();
2003 // updateSearchHilites()
2004 //______________________________________________________________________________
2005 GnuBook.prototype.updateSearchHilites = function() {
2006 if (2 == this.mode) {
2007 this.updateSearchHilites2UP();
2009 this.updateSearchHilites1UP();
2013 // showSearchHilites1UP()
2014 //______________________________________________________________________________
2015 GnuBook.prototype.updateSearchHilites1UP = function() {
2017 for (var key in this.searchResults) {
2019 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2020 var result = this.searchResults[key];
2021 if(null == result.div) {
2022 result.div = document.createElement('div');
2023 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2024 //console.log('appending ' + key);
2027 width: (result.r-result.l)/this.reduce + 'px',
2028 height: (result.b-result.t)/this.reduce + 'px',
2029 left: (result.l)/this.reduce + 'px',
2030 top: (result.t)/this.reduce +'px'
2034 //console.log(key + ' not displayed');
2035 this.searchResults[key].div=null;
2041 //______________________________________________________________________________
2042 // Returns the position of the gutter (line between the page images)
2043 GnuBook.prototype.twoPageGutter = function() {
2044 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2048 //______________________________________________________________________________
2049 // Returns the offset for the top of the page images
2050 GnuBook.prototype.twoPageTop = function() {
2051 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2054 // twoPageCoverWidth()
2055 //______________________________________________________________________________
2056 // Returns the width of the cover div given the total page width
2057 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2058 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2061 // twoPageGetViewCenter()
2062 //______________________________________________________________________________
2063 // Returns the percentage offset into twopageview div at the center of container div
2064 // { percentageX: float, percentageY: float }
2065 GnuBook.prototype.twoPageGetViewCenter = function() {
2068 var containerOffset = $('#GBcontainer').offset();
2069 var viewOffset = $('#GBtwopageview').offset();
2070 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2071 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2076 // twoPageCenterView(percentageX, percentageY)
2077 //______________________________________________________________________________
2078 // Centers the point given by percentage from left,top of twopageview
2079 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2080 if ('undefined' == typeof(percentageX)) {
2083 if ('undefined' == typeof(percentageY)) {
2087 var viewWidth = $('#GBtwopageview').width();
2088 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2089 var intoViewX = percentageX * viewWidth;
2091 var viewHeight = $('#GBtwopageview').height();
2092 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2093 var intoViewY = percentageY * viewHeight;
2095 if (viewWidth < containerClientWidth) {
2096 // Can fit width without scrollbars - center by adjusting offset
2097 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2099 // Need to scroll to center
2100 $('#GBtwopageview').css('left', 0);
2101 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2104 if (viewHeight < containerClientHeight) {
2105 // Fits with scrollbars - add offset
2106 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2108 $('#GBtwopageview').css('top', 0);
2109 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2113 // twoPageFlipAreaHeight
2114 //______________________________________________________________________________
2115 // Returns the integer height of the click-to-flip areas at the edges of the book
2116 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2117 return parseInt(this.twoPage.height);
2120 // twoPageFlipAreaWidth
2121 //______________________________________________________________________________
2122 // Returns the integer width of the flip areas
2123 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2124 var max = 100; // $$$ TODO base on view width?
2127 var width = this.twoPage.width * 0.15;
2128 return parseInt(GnuBook.util.clamp(width, min, max));
2131 // twoPageFlipAreaTop
2132 //______________________________________________________________________________
2133 // Returns integer top offset for flip areas
2134 GnuBook.prototype.twoPageFlipAreaTop = function() {
2135 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2138 // twoPageLeftFlipAreaLeft
2139 //______________________________________________________________________________
2140 // Left offset for left flip area
2141 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2142 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2145 // twoPageRightFlipAreaLeft
2146 //______________________________________________________________________________
2147 // Left offset for right flip area
2148 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2149 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2152 // twoPagePlaceFlipAreas
2153 //______________________________________________________________________________
2154 // Readjusts position of flip areas based on current layout
2155 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2156 // We don't set top since it shouldn't change relative to view
2157 $(this.twoPage.leftFlipArea).css({
2158 left: this.twoPageLeftFlipAreaLeft() + 'px'
2160 $(this.twoPage.rightFlipArea).css({
2161 left: this.twoPageRightFlipAreaLeft() + 'px'
2165 // showSearchHilites2UP()
2166 //______________________________________________________________________________
2167 GnuBook.prototype.updateSearchHilites2UP = function() {
2169 for (var key in this.searchResults) {
2170 key = parseInt(key, 10);
2171 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2172 var result = this.searchResults[key];
2173 if(null == result.div) {
2174 result.div = document.createElement('div');
2175 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2176 //console.log('appending ' + key);
2179 // We calculate the reduction factor for the specific page because it can be different
2180 // for each page in the spread
2181 var height = this.getPageHeight(key);
2182 var width = this.getPageWidth(key)
2183 var reduce = this.twoPage.height/height;
2184 var scaledW = parseInt(width*reduce);
2186 var gutter = this.twoPageGutter();
2188 if ('L' == this.getPageSide(key)) {
2189 pageL = gutter-scaledW;
2193 var pageT = this.twoPageTop();
2196 width: (result.r-result.l)*reduce + 'px',
2197 height: (result.b-result.t)*reduce + 'px',
2198 left: pageL+(result.l)*reduce + 'px',
2199 top: pageT+(result.t)*reduce +'px'
2203 //console.log(key + ' not displayed');
2204 if (null != this.searchResults[key].div) {
2205 //console.log('removing ' + key);
2206 $(this.searchResults[key].div).remove();
2208 this.searchResults[key].div=null;
2213 // removeSearchHilites()
2214 //______________________________________________________________________________
2215 GnuBook.prototype.removeSearchHilites = function() {
2216 for (var key in this.searchResults) {
2217 if (null != this.searchResults[key].div) {
2218 $(this.searchResults[key].div).remove();
2219 this.searchResults[key].div=null;
2225 //______________________________________________________________________________
2226 GnuBook.prototype.showEmbedCode = function() {
2227 if (null != this.embedPopup) { // check if already showing
2231 this.embedPopup = document.createElement("div");
2232 $(this.embedPopup).css({
2233 position: 'absolute',
2235 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2238 border: "3px double #999999",
2240 backgroundColor: "#fff"
2241 }).appendTo('#GnuBook');
2243 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2244 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>';
2245 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2246 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2248 this.embedPopup.innerHTML = htmlStr;
2249 $(this.embedPopup).find('input').bind('click', function() {
2255 //______________________________________________________________________________
2256 GnuBook.prototype.autoToggle = function() {
2258 var bComingFrom1up = false;
2259 if (2 != this.mode) {
2260 bComingFrom1up = true;
2264 // Change to autofit if book is too large
2265 if (this.reduce < this.twoPageGetAutofitReduce()) {
2270 if (null == this.autoTimer) {
2271 this.flipSpeed = 2000;
2273 // $$$ Draw events currently cause layout problems when they occur during animation.
2274 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2275 // we workaround for now by not triggering immediate animation in that case.
2276 // See https://bugs.launchpad.net/gnubook/+bug/328327
2277 if (('rl' == this.pageProgression) && bComingFrom1up) {
2278 // don't flip immediately -- wait until timer fires
2281 this.flipFwdToIndex();
2284 $('#GBtoolbar .play').hide();
2285 $('#GBtoolbar .pause').show();
2286 this.autoTimer=setInterval(function(){
2287 if (self.animating) {return;}
2289 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2290 self.flipBackToIndex(1); // $$$ really what we want?
2292 self.flipFwdToIndex();
2301 //______________________________________________________________________________
2302 // Stop autoplay mode, allowing animations to finish
2303 GnuBook.prototype.autoStop = function() {
2304 if (null != this.autoTimer) {
2305 clearInterval(this.autoTimer);
2306 this.flipSpeed = 'fast';
2307 $('#GBtoolbar .pause').hide();
2308 $('#GBtoolbar .play').show();
2309 this.autoTimer = null;
2313 // stopFlipAnimations
2314 //______________________________________________________________________________
2315 // Immediately stop flip animations. Callbacks are triggered.
2316 GnuBook.prototype.stopFlipAnimations = function() {
2318 this.autoStop(); // Clear timers
2320 // Stop animation, clear queue, trigger callbacks
2321 if (this.leafEdgeTmp) {
2322 $(this.leafEdgeTmp).stop(false, true);
2324 jQuery.each(this.prefetchedImgs, function() {
2325 $(this).stop(false, true);
2328 // And again since animations also queued in callbacks
2329 if (this.leafEdgeTmp) {
2330 $(this.leafEdgeTmp).stop(false, true);
2332 jQuery.each(this.prefetchedImgs, function() {
2333 $(this).stop(false, true);
2338 // keyboardNavigationIsDisabled(event)
2339 // - returns true if keyboard navigation should be disabled for the event
2340 //______________________________________________________________________________
2341 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2342 if (event.target.tagName == "INPUT") {
2348 // gutterOffsetForIndex
2349 //______________________________________________________________________________
2351 // Returns the gutter offset for the spread containing the given index.
2352 // This function supports RTL
2353 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2355 // To find the offset of the gutter from the middle we calculate our percentage distance
2356 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2357 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2359 // But then again for RTL it's the opposite
2360 if ('rl' == this.pageProgression) {
2368 //______________________________________________________________________________
2369 // Returns the width of the leaf edge div for the page with index given
2370 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2371 // $$$ could there be single pixel rounding errors for L vs R?
2372 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2373 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2375 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2379 // jumpIndexForLeftEdgePageX
2380 //______________________________________________________________________________
2381 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2382 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2383 if ('rl' != this.pageProgression) {
2384 // LTR - flipping backward
2385 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2387 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2388 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2392 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2393 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2398 // jumpIndexForRightEdgePageX
2399 //______________________________________________________________________________
2400 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2401 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2402 if ('rl' != this.pageProgression) {
2404 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2405 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2408 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2409 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2414 GnuBook.prototype.initToolbar = function(mode, ui) {
2416 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2417 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2418 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2419 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2420 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2421 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2422 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2423 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2426 this.updateToolbarZoom(this.reduce); // Pretty format
2428 if (ui == "embed") {
2429 $("#GnuBook a.logo").attr("target","_blank");
2432 // $$$ turn this into a member variable
2433 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2435 // We build in mode 2
2436 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2437 + "<button class='GBicon rollover embed' />"
2438 + "<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>"
2439 + "<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>"
2440 + "<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>"
2441 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2443 this.bindToolbarNavHandlers(jToolbar);
2445 // Setup tooltips -- later we could load these from a file for i18n
2446 var titles = { '.logo': 'Go to Archive.org',
2447 '.zoom_in': 'Zoom in',
2448 '.zoom_out': 'Zoom out',
2449 '.one_page_mode': 'One-page view',
2450 '.two_page_mode': 'Two-page view',
2451 '.embed': 'Embed bookreader',
2452 '.book_left': 'Flip left',
2453 '.book_right': 'Flip right',
2454 '.book_up': 'Page up',
2455 '.book_down': 'Page down',
2458 '.book_top': 'First page',
2459 '.book_bottom': 'Last page'
2461 if ('rl' == this.pageProgression) {
2462 titles['.book_leftmost'] = 'Last page';
2463 titles['.book_rightmost'] = 'First page';
2465 titles['.book_leftmost'] = 'First page';
2466 titles['.book_rightmost'] = 'Last page';
2469 for (var icon in titles) {
2470 jToolbar.find(icon).attr('title', titles[icon]);
2473 // Hide mode buttons and autoplay if 2up is not available
2474 // $$$ if we end up with more than two modes we should show the applicable buttons
2475 if ( !this.canSwitchToMode(this.constMode2up) ) {
2476 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2479 // Switch to requested mode -- binds other click handlers
2480 this.switchToolbarMode(mode);
2485 // switchToolbarMode
2486 //______________________________________________________________________________
2487 // Update the toolbar for the given mode (changes navigation buttons)
2488 // $$$ we should soon split the toolbar out into its own module
2489 GnuBook.prototype.switchToolbarMode = function(mode) {
2492 $('#GBtoolbar .GBtoolbarmode2').hide();
2493 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2496 $('#GBtoolbar .GBtoolbarmode1').hide();
2497 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2501 // bindToolbarNavHandlers
2502 //______________________________________________________________________________
2503 // Binds the toolbar handlers
2504 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2506 jToolbar.find('.book_left').bind('click', function(e) {
2511 jToolbar.find('.book_right').bind('click', function(e) {
2516 jToolbar.find('.book_up').bind('click', function(e) {
2521 jToolbar.find('.book_down').bind('click', function(e) {
2526 jToolbar.find('.embed').bind('click', function(e) {
2531 jToolbar.find('.play').bind('click', function(e) {
2536 jToolbar.find('.pause').bind('click', function(e) {
2541 jToolbar.find('.book_top').bind('click', function(e) {
2546 jToolbar.find('.book_bottom').bind('click', function(e) {
2551 jToolbar.find('.book_leftmost').bind('click', function(e) {
2556 jToolbar.find('.book_rightmost').bind('click', function(e) {
2562 // updateToolbarZoom(reduce)
2563 //______________________________________________________________________________
2564 // Update the displayed zoom factor based on reduction factor
2565 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2567 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2570 value = (100 / reduce).toFixed(2);
2571 // Strip trailing zeroes and decimal if all zeroes
2572 value = value.replace(/0+$/,'');
2573 value = value.replace(/\.$/,'');
2576 $('#GBzoom').text(value);
2579 // firstDisplayableIndex
2580 //______________________________________________________________________________
2581 // Returns the index of the first visible page, dependent on the mode.
2582 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2583 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2584 GnuBook.prototype.firstDisplayableIndex = function() {
2585 if (this.mode == 0) {
2588 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2592 // lastDisplayableIndex
2593 //______________________________________________________________________________
2594 // Returns the index of the last visible page, dependent on the mode.
2595 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2596 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2597 GnuBook.prototype.lastDisplayableIndex = function() {
2598 if (this.mode == 2) {
2599 if (this.lastDisplayableIndex2up === null) {
2600 // Calculate and cache
2601 var candidate = this.numLeafs - 1;
2602 for ( ; candidate >= 0; candidate--) {
2603 var spreadIndices = this.getSpreadIndices(candidate);
2604 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2608 this.lastDisplayableIndex2up = candidate;
2610 return this.lastDisplayableIndex2up;
2612 return this.numLeafs - 1;
2616 // shortTitle(maximumCharacters)
2618 // Returns a shortened version of the title with the maximum number of characters
2619 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2620 if (this.bookTitle.length < maximumCharacters) {
2621 return this.bookTitle;
2624 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2631 // Parameter related functions
2633 // updateFromParams(params)
2635 // Update ourselves from the params object.
2637 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2638 GnuBook.prototype.updateFromParams = function(params) {
2639 if ('undefined' != typeof(params.mode)) {
2640 this.switchMode(params.mode);
2643 // $$$ process /search
2644 // $$$ process /zoom
2646 // We only respect page if index is not set
2647 if ('undefined' != typeof(params.index)) {
2648 if (params.index != this.currentIndex()) {
2649 this.jumpToIndex(params.index);
2651 } else if ('undefined' != typeof(params.page)) {
2652 // $$$ this assumes page numbers are unique
2653 if (params.page != this.getPageNum(this.currentIndex())) {
2654 this.jumpToPage(params.page);
2658 // $$$ process /region
2659 // $$$ process /highlight
2662 // paramsFromFragment(urlFragment)
2664 // Returns a object with configuration parametes from a URL fragment.
2666 // E.g paramsFromFragment(window.location.hash)
2667 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2668 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2672 // For convenience we allow an initial # character (as from window.location.hash)
2673 // but don't require it
2674 if (urlFragment.substr(0,1) == '#') {
2675 urlFragment = urlFragment.substr(1);
2678 // Simple #nn syntax
2679 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2680 if ( !isNaN(oldStyleLeafNum) ) {
2681 params.index = oldStyleLeafNum;
2683 // Done processing if using old-style syntax
2687 // Split into key-value pairs
2688 var urlArray = urlFragment.split('/');
2690 for (var i = 0; i < urlArray.length; i += 2) {
2691 urlHash[urlArray[i]] = urlArray[i+1];
2695 if ('1up' == urlHash['mode']) {
2696 params.mode = this.constMode1up;
2697 } else if ('2up' == urlHash['mode']) {
2698 params.mode = this.constMode2up;
2702 if ('undefined' != typeof(urlHash['page'])) {
2703 // page was set -- may not be int
2704 params.page = urlHash['page'];
2707 // $$$ process /region
2708 // $$$ process /search
2709 // $$$ process /highlight
2714 // paramsFromCurrent()
2716 // Create a params object from the current parameters.
2717 GnuBook.prototype.paramsFromCurrent = function() {
2721 var pageNum = this.getPageNum(this.currentIndex());
2722 if ((pageNum === 0) || pageNum) {
2723 params.page = pageNum;
2726 params.index = this.currentIndex();
2727 params.mode = this.mode;
2736 // fragmentFromParams(params)
2738 // Create a fragment string from the params object.
2739 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2740 GnuBook.prototype.fragmentFromParams = function(params) {
2741 var separator = '/';
2745 if ('undefined' != typeof(params.page)) {
2746 fragments.push('page', params.page);
2748 // Don't have page numbering -- use index instead
2749 fragments.push('page', 'n' + params.index);
2757 if ('undefined' != typeof(params.mode)) {
2758 if (params.mode == this.constMode1up) {
2759 fragments.push('mode', '1up');
2760 } else if (params.mode == this.constMode2up) {
2761 fragments.push('mode', '2up');
2763 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2767 return fragments.join(separator);
2770 // getPageIndex(pageNum)
2772 // Returns the *highest* index the given page number, or undefined
2773 GnuBook.prototype.getPageIndex = function(pageNum) {
2774 var pageIndices = this.getPageIndices(pageNum);
2776 if (pageIndices.length > 0) {
2777 return pageIndices[pageIndices.length - 1];
2783 // getPageIndices(pageNum)
2785 // Returns an array (possibly empty) of the indices with the given page number
2786 GnuBook.prototype.getPageIndices = function(pageNum) {
2789 // Check for special "nXX" page number
2790 if (pageNum.slice(0,1) == 'n') {
2792 var pageIntStr = pageNum.slice(1, pageNum.length);
2793 var pageIndex = parseInt(pageIntStr);
2794 indices.append(pageIndex);
2797 // Do nothing... will run through page names and see if one matches
2802 for (i=0; i<this.numLeafs; i++) {
2803 if (this.getPageNum(i) == pageNum) {
2811 // getPageName(index)
2813 // Returns the name of the page as it should be displayed in the user interface
2814 GnuBook.prototype.getPageName = function(index) {
2815 return 'Page ' + this.getPageNum(index);
2818 // updateLocationHash
2820 // Update the location hash from the current parameters. Call this instead of manually
2821 // using window.location.replace
2822 GnuBook.prototype.updateLocationHash = function() {
2823 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2824 window.location.replace(newHash);
2826 // This is the variable checked in the timer. Only user-generated changes
2827 // to the URL will trigger the event.
2828 this.oldLocationHash = newHash;
2831 // startLocationPolling
2833 // Starts polling of window.location to see hash fragment changes
2834 GnuBook.prototype.startLocationPolling = function() {
2835 var self = this; // remember who I am
2836 self.oldLocationHash = window.location.hash;
2838 if (this.locationPollId) {
2839 clearInterval(this.locationPollID);
2840 this.locationPollId = null;
2843 this.locationPollId = setInterval(function() {
2844 var newHash = window.location.hash;
2845 if (newHash != self.oldLocationHash) {
2846 if (newHash != self.oldUserHash) { // Only process new user hash once
2847 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2849 // Queue change if animating
2850 if (self.animating) {
2852 self.animationFinishedCallback = function() {
2853 self.updateFromParams(self.paramsFromFragment(newHash));
2855 } else { // update immediately
2856 self.updateFromParams(self.paramsFromFragment(newHash));
2858 self.oldUserHash = newHash;
2866 // Returns a URL for an embedded version of the current book
2867 GnuBook.prototype.getEmbedURL = function() {
2868 // We could generate a URL hash fragment here but for now we just leave at defaults
2869 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2874 // Returns the embed code HTML fragment suitable for copy and paste
2875 GnuBook.prototype.getEmbedCode = function() {
2876 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2881 // Returns true if we can switch to the requested mode
2882 GnuBook.prototype.canSwitchToMode = function(mode) {
2883 if (mode == this.constMode2up) {
2884 // check there are enough pages to display
2885 // $$$ this is a workaround for the mis-feature that we can't display
2886 // short books in 2up mode
2887 if (this.numLeafs < 6) {
2895 // Library functions
2897 clamp: function(value, min, max) {
2898 return Math.min(Math.max(value, min), max);