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) {
217 if (2 == self.mode) {
228 if (self.keyboardNavigationIsDisabled(e)) {
231 if (2 == self.mode) {
236 if (self.keyboardNavigationIsDisabled(e)) {
239 if (2 == self.mode) {
248 //______________________________________________________________________________
249 GnuBook.prototype.drawLeafs = function() {
250 if (1 == this.mode) {
251 this.drawLeafsOnePage();
253 this.drawLeafsTwoPage();
258 //______________________________________________________________________________
259 GnuBook.prototype.setDragHandler = function(div) {
260 div.dragging = false;
262 $(div).unbind('mousedown').bind('mousedown', function(e) {
265 //console.log('mousedown at ' + e.pageY);
267 this.dragging = true;
268 this.prevMouseX = e.pageX;
269 this.prevMouseY = e.pageY;
271 var startX = e.pageX;
272 var startY = e.pageY;
273 var startTop = $('#GBcontainer').attr('scrollTop');
274 var startLeft = $('#GBcontainer').attr('scrollLeft');
278 $(div).unbind('mousemove').bind('mousemove', function(ee) {
281 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
283 var offsetX = ee.pageX - this.prevMouseX;
284 var offsetY = ee.pageY - this.prevMouseY;
287 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
288 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
291 this.prevMouseX = ee.pageX;
292 this.prevMouseY = ee.pageY;
296 $(div).unbind('mouseup').bind('mouseup', function(ee) {
298 //console.log('mouseup');
300 this.dragging = false;
303 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
305 //console.log('mouseleave');
307 this.dragging = false;
310 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
312 //console.log('mouseenter');
314 this.dragging = false;
318 // drawLeafsOnePage()
319 //______________________________________________________________________________
320 GnuBook.prototype.drawLeafsOnePage = function() {
321 //alert('drawing leafs!');
325 var scrollTop = $('#GBcontainer').attr('scrollTop');
326 var scrollBottom = scrollTop + $('#GBcontainer').height();
327 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
329 var indicesToDisplay = [];
334 for (i=0; i<this.numLeafs; i++) {
335 var height = parseInt(this.getPageHeight(i)/this.reduce);
337 leafBottom += height;
338 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
339 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
340 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
341 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
342 if (topInView | bottomInView | middleInView) {
343 //console.log('displayed: ' + this.displayedIndices);
344 //console.log('to display: ' + i);
345 indicesToDisplay.push(i);
347 leafTop += height +10;
351 var firstIndexToDraw = indicesToDisplay[0];
352 this.firstIndex = firstIndexToDraw;
354 // Update hash, but only if we're currently displaying a leaf
355 // Hack that fixes #365790
356 if (this.displayedIndices.length > 0) {
357 this.updateLocationHash();
360 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
362 indicesToDisplay.unshift(firstIndexToDraw);
365 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
366 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
367 indicesToDisplay.push(lastIndexToDraw+1);
372 for (i=0; i<firstIndexToDraw; i++) {
373 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
376 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
377 var viewWidth = $('#GBcontainer').attr('scrollWidth');
380 for (i=0; i<indicesToDisplay.length; i++) {
381 var index = indicesToDisplay[i];
382 var height = parseInt(this.getPageHeight(index)/this.reduce);
384 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
385 var width = parseInt(this.getPageWidth(index)/this.reduce);
386 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
387 var div = document.createElement("div");
388 div.className = 'GBpagediv1up';
389 div.id = 'pagediv'+index;
390 div.style.position = "absolute";
391 $(div).css('top', leafTop + 'px');
392 var left = (viewWidth-width)>>1;
393 if (left<0) left = 0;
394 $(div).css('left', left+'px');
395 $(div).css('width', width+'px');
396 $(div).css('height', height+'px');
397 //$(div).text('loading...');
399 this.setDragHandler(div);
401 $('#GBpageview').append(div);
403 var img = document.createElement("img");
404 img.src = this.getPageURI(index);
405 $(img).css('width', width+'px');
406 $(img).css('height', height+'px');
410 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
413 leafTop += height +10;
417 for (i=0; i<this.displayedIndices.length; i++) {
418 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
419 var index = this.displayedIndices[i];
420 //console.log('Removing leaf ' + index);
421 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
422 $('#pagediv'+index).remove();
424 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
428 this.displayedIndices = indicesToDisplay.slice();
429 this.updateSearchHilites();
431 if (null != this.getPageNum(firstIndexToDraw)) {
432 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
434 $("#GBpagenum").val('');
437 this.updateToolbarZoom(this.reduce);
441 // drawLeafsTwoPage()
442 //______________________________________________________________________________
443 GnuBook.prototype.drawLeafsTwoPage = function() {
444 var scrollTop = $('#GBtwopageview').attr('scrollTop');
445 var scrollBottom = scrollTop + $('#GBtwopageview').height();
447 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
449 var indexL = this.twoPage.currentIndexL;
450 var heightL = this.getPageHeight(indexL);
451 var widthL = this.getPageWidth(indexL);
453 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
454 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
455 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
456 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
457 //console.log(leafEdgeWidthL);
459 var middle = this.twoPage.middle; // $$$ getter instead?
460 var top = this.twoPageTop();
461 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
463 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
464 this.twoPage.gutter = this.twoPageGutter();
466 this.prefetchImg(indexL);
467 $(this.prefetchedImgs[indexL]).css({
468 position: 'absolute',
469 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
472 backgroundColor: 'rgb(234, 226, 205)',
473 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
474 width: this.twoPage.scaledWL + 'px',
475 borderRight: '1px solid black',
477 }).appendTo('#GBtwopageview');
479 var indexR = this.twoPage.currentIndexR;
480 var heightR = this.getPageHeight(indexR);
481 var widthR = this.getPageWidth(indexR);
483 // $$$ should use getwidth2up?
484 //var scaledWR = this.twoPage.height*widthR/heightR;
485 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
486 this.prefetchImg(indexR);
487 $(this.prefetchedImgs[indexR]).css({
488 position: 'absolute',
489 left: this.twoPage.gutter+'px',
492 backgroundColor: 'rgb(234, 226, 205)',
493 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
494 width: this.twoPage.scaledWR + 'px',
495 borderLeft: '1px solid black',
497 }).appendTo('#GBtwopageview');
500 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
501 this.setClickHandlers();
502 this.twoPageSetCursor();
504 this.updatePageNumBox2UP();
505 this.updateToolbarZoom(this.reduce);
507 this.twoPagePlaceFlipAreas();
511 // updatePageNumBox2UP
512 //______________________________________________________________________________
513 GnuBook.prototype.updatePageNumBox2UP = function() {
514 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
515 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
517 $("#GBpagenum").val('');
519 this.updateLocationHash();
523 //______________________________________________________________________________
524 GnuBook.prototype.loadLeafs = function() {
528 if (null == this.timer) {
529 this.timer=setTimeout(function(){self.drawLeafs()},250);
531 clearTimeout(this.timer);
532 this.timer=setTimeout(function(){self.drawLeafs()},250);
538 // Pass 1 to zoom in, anything else to zoom out
539 //______________________________________________________________________________
540 GnuBook.prototype.zoom = function(direction) {
542 case this.constMode1up:
543 return this.zoom1up(direction);
544 case this.constMode2up:
545 return this.zoom2up(direction);
550 //______________________________________________________________________________
551 GnuBook.prototype.zoom1up = function(dir) {
552 if (2 == this.mode) { //can only zoom in 1-page mode
557 // $$$ with flexible zoom we could "snap" to /2 page reductions
558 // for better scaling
560 if (this.reduce <= 0.5) return;
561 this.reduce*=0.5; //zoom in
563 if (this.reduce >= 8) return;
564 this.reduce*=2; //zoom out
567 this.resizePageView();
569 $('#GBpageview').empty()
570 this.displayedIndices = [];
573 this.updateToolbarZoom(this.reduce);
577 //______________________________________________________________________________
578 GnuBook.prototype.resizePageView = function() {
581 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
582 var viewWidth = $('#GBcontainer').attr('clientWidth');
584 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
585 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
586 var oldPageViewHeight = $('#GBpageview').height();
587 var oldPageViewWidth = $('#GBpageview').width();
589 var oldCenterY = this.centerY1up();
590 var oldCenterX = this.centerX1up();
592 if (0 != oldPageViewHeight) {
593 var scrollRatio = oldCenterY / oldPageViewHeight;
598 for (i=0; i<this.numLeafs; i++) {
599 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
600 var width = parseInt(this.getPageWidth(i)/this.reduce);
601 if (width>viewWidth) viewWidth=width;
603 $('#GBpageview').height(viewHeight);
604 $('#GBpageview').width(viewWidth);
606 var newCenterY = scrollRatio*viewHeight;
607 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
608 $('#GBcontainer').attr('scrollTop', newTop);
610 // We use clientWidth here to avoid miscalculating due to scroll bar
611 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
612 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
613 newLeft = Math.max(newLeft, 0);
614 $('#GBcontainer').attr('scrollLeft', newLeft);
615 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
617 //this.centerPageView();
623 //______________________________________________________________________________
624 // Returns the current offset of the viewport center in scaled document coordinates.
625 GnuBook.prototype.centerX1up = function() {
627 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
628 centerX = $('#GBpageview').width();
630 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
632 centerX = Math.floor(centerX);
637 //______________________________________________________________________________
638 // Returns the current offset of the viewport center in scaled document coordinates.
639 GnuBook.prototype.centerY1up = function() {
640 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
641 return Math.floor(centerY);
645 //______________________________________________________________________________
646 GnuBook.prototype.centerPageView = function() {
648 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
649 var clientWidth = $('#GBcontainer').attr('clientWidth');
650 //console.log('sW='+scrollWidth+' cW='+clientWidth);
651 if (scrollWidth > clientWidth) {
652 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
657 // zoom2up(direction)
658 //______________________________________________________________________________
659 GnuBook.prototype.zoom2up = function(direction) {
661 // Hard stop autoplay
662 this.stopFlipAnimations();
664 // Get new zoom state
665 var newZoom = this.twoPageNextReduce(this.reduce, direction);
666 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
669 this.twoPage.autofit = newZoom.autofit;
670 this.reduce = newZoom.reduce;
672 // Preserve view center position
673 var oldCenter = this.twoPageGetViewCenter();
675 // Prepare view with new center to minimize visual glitches
676 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
680 // quantizeReduce(reduce)
681 //______________________________________________________________________________
682 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
683 GnuBook.prototype.quantizeReduce = function(reduce) {
684 var quantized = this.reductionFactors[0];
685 var distance = Math.abs(reduce - quantized);
686 for (var i = 1; i < this.reductionFactors.length; i++) {
687 newDistance = Math.abs(reduce - this.reductionFactors[i]);
688 if (newDistance < distance) {
689 distance = newDistance;
690 quantized = this.reductionFactors[i];
697 // twoPageNextReduce()
698 //______________________________________________________________________________
699 // Returns the next reduction level
700 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
702 var autofitReduce = this.twoPageGetAutofitReduce();
704 if (0 == direction) { // autofit
705 result.autofit = true;
706 result.reduce = autofitReduce;
708 } else if (1 == direction) { // zoom in
709 var newReduce = this.reductionFactors[0];
711 for (var i = 1; i < this.reductionFactors.length; i++) {
712 if (this.reductionFactors[i] < reduce) {
713 newReduce = this.reductionFactors[i];
717 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
719 result.autofit = true;
720 result.reduce = autofitReduce;
722 result.autofit = false;
723 result.reduce = newReduce;
727 var lastIndex = this.reductionFactors.length - 1;
728 var newReduce = this.reductionFactors[lastIndex];
730 for (var i = lastIndex; i >= 0; i--) {
731 if (this.reductionFactors[i] > reduce) {
732 newReduce = this.reductionFactors[i];
736 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
738 result.autofit = true;
739 result.reduce = autofitReduce;
741 result.autofit = false;
742 result.reduce = newReduce;
750 //______________________________________________________________________________
751 // Attempts to jump to page. Returns true if page could be found, false otherwise.
752 GnuBook.prototype.jumpToPage = function(pageNum) {
754 var pageIndex = this.getPageIndex(pageNum);
756 if ('undefined' != typeof(pageIndex)) {
759 this.jumpToIndex(pageIndex);
760 $('#GBcontainer').attr('scrollTop', leafTop);
769 //______________________________________________________________________________
770 GnuBook.prototype.jumpToIndex = function(index) {
772 if (2 == this.mode) {
775 // By checking against min/max we do nothing if requested index
777 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
778 this.flipBackToIndex(index);
779 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
780 this.flipFwdToIndex(index);
787 for (i=0; i<index; i++) {
788 h = parseInt(this.getPageHeight(i)/this.reduce);
789 leafTop += h + this.padding;
791 //$('#GBcontainer').attr('scrollTop', leafTop);
792 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
799 //______________________________________________________________________________
800 GnuBook.prototype.switchMode = function(mode) {
802 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
804 if (mode == this.mode) return;
806 if (!this.canSwitchToMode(mode)) {
811 this.removeSearchHilites();
815 this.switchToolbarMode(mode);
817 // $$$ TODO preserve center of view when switching between mode
818 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
821 this.reduce = this.quantizeReduce(this.reduce);
822 this.prepareOnePageView();
824 this.twoPage.autofit = false; // Take zoom level from other mode
825 this.reduce = this.quantizeReduce(this.reduce);
826 this.prepareTwoPageView();
827 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
832 //prepareOnePageView()
833 //______________________________________________________________________________
834 GnuBook.prototype.prepareOnePageView = function() {
836 // var startLeaf = this.displayedIndices[0];
837 var startLeaf = this.currentIndex();
839 $('#GBcontainer').empty();
840 $('#GBcontainer').css({
845 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
847 this.resizePageView();
849 this.jumpToIndex(startLeaf);
850 this.displayedIndices = [];
852 this.drawLeafsOnePage();
854 // Bind mouse handlers
855 // Disable mouse click to avoid selected/highlighted page images - bug 354239
856 gbPageView.bind('mousedown', function(e) {
857 // $$$ check here for right-click and don't disable. Also use jQuery style
858 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
861 // Special hack for IE7
862 gbPageView[0].onselectstart = function(e) { return false; };
865 // prepareTwoPageView()
866 //______________________________________________________________________________
867 // Some decisions about two page view:
869 // Both pages will be displayed at the same height, even if they were different physical/scanned
870 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
871 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
872 // aspect ratio to determine the height.
874 // The two page view div is resized to keep the middle of the book in the middle of the div
875 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
876 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
877 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
878 $('#GBcontainer').empty();
879 $('#GBcontainer').css('overflow', 'auto');
881 // We want to display two facing pages. We may be missing
882 // one side of the spread because it is the first/last leaf,
883 // foldouts, missing pages, etc
885 //var targetLeaf = this.displayedIndices[0];
886 var targetLeaf = this.firstIndex;
888 if (targetLeaf < this.firstDisplayableIndex()) {
889 targetLeaf = this.firstDisplayableIndex();
892 if (targetLeaf > this.lastDisplayableIndex()) {
893 targetLeaf = this.lastDisplayableIndex();
896 this.twoPage.currentIndexL = null;
897 this.twoPage.currentIndexR = null;
898 this.pruneUnusedImgs();
900 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
901 this.twoPage.currentIndexL = currentSpreadIndices[0];
902 this.twoPage.currentIndexR = currentSpreadIndices[1];
903 this.firstIndex = this.twoPage.currentIndexL;
905 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
907 //console.dir(this.twoPage);
909 // Add the two page view
910 // $$$ Can we get everything set up and then append?
911 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
913 // $$$ calculate first then set
914 $('#GBtwopageview').css( {
915 height: this.twoPage.totalHeight + 'px',
916 width: this.twoPage.totalWidth + 'px',
920 // If there will not be scrollbars (e.g. when zooming out) we center the book
921 // since otherwise the book will be stuck off-center
922 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
923 centerPercentageX = 0.5;
925 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
926 centerPercentageY = 0.5;
929 this.twoPageCenterView(centerPercentageX, centerPercentageY);
931 this.twoPage.coverDiv = document.createElement('div');
932 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
933 border: '1px solid rgb(68, 25, 17)',
934 width: this.twoPage.bookCoverDivWidth + 'px',
935 height: this.twoPage.bookCoverDivHeight+'px',
936 visibility: 'visible',
937 position: 'absolute',
938 backgroundColor: '#663929',
939 left: this.twoPage.bookCoverDivLeft + 'px',
940 top: this.twoPage.bookCoverDivTop+'px',
941 MozBorderRadiusTopleft: '7px',
942 MozBorderRadiusTopright: '7px',
943 MozBorderRadiusBottomright: '7px',
944 MozBorderRadiusBottomleft: '7px'
945 }).appendTo('#GBtwopageview');
947 this.leafEdgeR = document.createElement('div');
948 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
949 $(this.leafEdgeR).css({
950 borderStyle: 'solid solid solid none',
951 borderColor: 'rgb(51, 51, 34)',
952 borderWidth: '1px 1px 1px 0px',
953 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
954 width: this.twoPage.leafEdgeWidthR + 'px',
955 height: this.twoPage.height-1 + 'px',
957 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
958 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
960 }).appendTo('#GBtwopageview');
962 this.leafEdgeL = document.createElement('div');
963 this.leafEdgeL.className = 'leafEdgeL';
964 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
965 borderStyle: 'solid none solid solid',
966 borderColor: 'rgb(51, 51, 34)',
967 borderWidth: '1px 0px 1px 1px',
968 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
969 width: this.twoPage.leafEdgeWidthL + 'px',
970 height: this.twoPage.height-1 + 'px',
971 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
972 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
974 }).appendTo('#GBtwopageview');
976 div = document.createElement('div');
977 $(div).attr('id', 'GBbookspine').css({
978 border: '1px solid rgb(68, 25, 17)',
979 width: this.twoPage.bookSpineDivWidth+'px',
980 height: this.twoPage.bookSpineDivHeight+'px',
981 position: 'absolute',
982 backgroundColor: 'rgb(68, 25, 17)',
983 left: this.twoPage.bookSpineDivLeft+'px',
984 top: this.twoPage.bookSpineDivTop+'px'
985 }).appendTo('#GBtwopageview');
987 var self = this; // for closure
989 this.twoPage.leftFlipArea = document.createElement('div');
990 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
992 width: this.twoPageFlipAreaWidth() + 'px',
993 height: this.twoPageFlipAreaHeight() + 'px',
994 position: 'absolute',
995 left: this.twoPageLeftFlipAreaLeft() + 'px',
996 top: this.twoPageFlipAreaTop() + 'px',
999 }).bind('click', function(e) {
1001 }).bind('mousedown', function(e) {
1003 }).appendTo('#GBtwopageview');
1005 this.twoPage.rightFlipArea = document.createElement('div');
1006 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1008 width: this.twoPageFlipAreaWidth() + 'px',
1009 height: this.twoPageFlipAreaHeight() + 'px',
1010 position: 'absolute',
1011 left: this.twoPageRightFlipAreaLeft() + 'px',
1012 top: this.twoPageFlipAreaTop() + 'px',
1015 }).bind('click', function(e) {
1017 }).bind('mousedown', function(e) {
1019 }).appendTo('#GBtwopageview');
1021 this.prepareTwoPagePopUp();
1023 this.displayedIndices = [];
1025 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1026 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1028 this.drawLeafsTwoPage();
1029 this.updateSearchHilites2UP();
1030 this.updateToolbarZoom(this.reduce);
1035 // prepareTwoPagePopUp()
1037 // This function prepares the "View Page n" popup that shows while the mouse is
1038 // over the left/right "stack of sheets" edges. It also binds the mouse
1039 // events for these divs.
1040 //______________________________________________________________________________
1041 GnuBook.prototype.prepareTwoPagePopUp = function() {
1043 this.twoPagePopUp = document.createElement('div');
1044 $(this.twoPagePopUp).css({
1045 border: '1px solid black',
1047 position: 'absolute',
1048 fontFamily: 'sans-serif',
1051 backgroundColor: 'rgb(255, 255, 238)',
1053 }).appendTo('#GBcontainer');
1054 $(this.twoPagePopUp).hide();
1056 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1057 $(e.data.twoPagePopUp).show();
1060 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1061 $(e.data.twoPagePopUp).hide();
1064 $(this.leafEdgeL).bind('click', this, function(e) {
1066 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1067 e.data.jumpToIndex(jumpIndex);
1070 $(this.leafEdgeR).bind('click', this, function(e) {
1072 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1073 e.data.jumpToIndex(jumpIndex);
1076 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1078 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1079 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1081 // $$$ TODO: Make sure popup is positioned so that it is in view
1082 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1083 $(e.data.twoPagePopUp).css({
1084 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1085 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1089 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1091 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1092 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1094 // $$$ TODO: Make sure popup is positioned so that it is in view
1095 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1096 $(e.data.twoPagePopUp).css({
1097 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1098 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1103 // calculateSpreadSize()
1104 //______________________________________________________________________________
1105 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1106 // this.twoPage.currentIndexR
1107 // This function sets this.twoPage.height, twoPage.width
1109 GnuBook.prototype.calculateSpreadSize = function() {
1111 var firstIndex = this.twoPage.currentIndexL;
1112 var secondIndex = this.twoPage.currentIndexR;
1113 //console.log('first page is ' + firstIndex);
1115 // Calculate page sizes and total leaf width
1117 if ( this.twoPage.autofit) {
1118 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1120 // set based on reduction factor
1121 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1124 // Both pages together
1125 this.twoPage.height = spreadSize.height;
1126 this.twoPage.width = spreadSize.width;
1129 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1130 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1133 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1134 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1135 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1139 // The width of the book cover div. The combined width of both pages, twice the width
1140 // of the book cover internal padding (2*10) and the page edges
1141 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1142 // The height of the book cover div
1143 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1146 // We calculate the total width and height for the div so that we can make the book
1148 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1149 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1150 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1151 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1152 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1153 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1155 // We want to minimize the unused space in two-up mode (maximize the amount of page
1156 // shown). We give width to the leaf edges and these widths change (though the sum
1157 // of the two remains constant) as we flip through the book. With the book
1158 // cover centered and fixed in the GBcontainer div the page images will meet
1159 // at the "gutter" which is generally offset from the center.
1160 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1161 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1163 // The left edge of the book cover moves depending on the width of the pages
1164 // $$$ change to getter
1165 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1166 // The top edge of the book cover stays a fixed distance from the top
1167 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1170 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1171 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1172 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1175 this.reduce = spreadSize.reduce; // $$$ really set this here?
1178 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1181 // We check which page is closest to a "normal" page and use that to set the height
1182 // for both pages. This means that foldouts and other odd size pages will be displayed
1183 // smaller than the nominal zoom amount.
1184 var canon5Dratio = 1.5;
1187 height: this.getPageHeight(firstIndex),
1188 width: this.getPageWidth(firstIndex)
1192 height: this.getPageHeight(secondIndex),
1193 width: this.getPageWidth(secondIndex)
1196 var firstIndexRatio = first.height / first.width;
1197 var secondIndexRatio = second.height / second.width;
1198 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1201 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1202 ratio = firstIndexRatio;
1203 //console.log('using firstIndexRatio ' + ratio);
1205 ratio = secondIndexRatio;
1206 //console.log('using secondIndexRatio ' + ratio);
1209 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1210 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1211 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1213 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1214 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1216 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1217 ideal.width -= 10; // $$$ fudge factor
1218 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1219 ideal.height -= 20; // fudge factor
1220 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1222 if (ideal.height/ratio <= ideal.width) {
1224 ideal.width = parseInt(ideal.height/ratio);
1227 ideal.height = parseInt(ideal.width*ratio);
1230 // $$$ check this logic with large spreads
1231 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1236 // getSpreadSizeFromReduce()
1237 //______________________________________________________________________________
1238 // Returns the spread size calculated from the reduction factor for the given pages
1239 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1240 var spreadSize = {};
1241 // $$$ Scale this based on reduce?
1242 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1243 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1244 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1246 // $$$ Possibly incorrect -- we should make height "dominant"
1247 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1248 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1249 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1250 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1251 spreadSize.reduce = reduce;
1256 // twoPageGetAutofitReduce()
1257 //______________________________________________________________________________
1258 // Returns the current ideal reduction factor
1259 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1260 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1261 return spreadSize.reduce;
1264 // twoPageSetCursor()
1265 //______________________________________________________________________________
1266 // Set the cursor for two page view
1267 GnuBook.prototype.twoPageSetCursor = function() {
1268 // console.log('setting cursor');
1269 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1270 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1271 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1272 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1274 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1275 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1280 //______________________________________________________________________________
1281 // Returns the currently active index.
1282 GnuBook.prototype.currentIndex = function() {
1283 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1284 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1285 return this.firstIndex;
1287 throw 'currentIndex called for unimplemented mode ' + this.mode;
1292 //______________________________________________________________________________
1293 // Flip the right page over onto the left
1294 GnuBook.prototype.right = function() {
1295 if ('rl' != this.pageProgression) {
1305 //______________________________________________________________________________
1306 // Flip to the rightmost page
1307 GnuBook.prototype.rightmost = function() {
1308 if ('rl' != this.pageProgression) {
1316 //______________________________________________________________________________
1317 // Flip the left page over onto the right.
1318 GnuBook.prototype.left = function() {
1319 if ('rl' != this.pageProgression) {
1329 //______________________________________________________________________________
1330 // Flip to the leftmost page
1331 GnuBook.prototype.leftmost = function() {
1332 if ('rl' != this.pageProgression) {
1340 //______________________________________________________________________________
1341 GnuBook.prototype.next = function() {
1342 if (2 == this.mode) {
1344 this.flipFwdToIndex(null);
1346 if (this.firstIndex < this.lastDisplayableIndex()) {
1347 this.jumpToIndex(this.firstIndex+1);
1353 //______________________________________________________________________________
1354 GnuBook.prototype.prev = function() {
1355 if (2 == this.mode) {
1357 this.flipBackToIndex(null);
1359 if (this.firstIndex >= 1) {
1360 this.jumpToIndex(this.firstIndex-1);
1365 GnuBook.prototype.first = function() {
1366 if (2 == this.mode) {
1367 this.jumpToIndex(2);
1370 this.jumpToIndex(0);
1374 GnuBook.prototype.last = function() {
1375 if (2 == this.mode) {
1376 this.jumpToIndex(this.lastDisplayableIndex());
1379 this.jumpToIndex(this.lastDisplayableIndex());
1383 // flipBackToIndex()
1384 //______________________________________________________________________________
1385 // to flip back one spread, pass index=null
1386 GnuBook.prototype.flipBackToIndex = function(index) {
1387 if (1 == this.mode) return;
1389 var leftIndex = this.twoPage.currentIndexL;
1391 // $$$ Need to change this to be able to see first spread.
1392 // See https://bugs.launchpad.net/gnubook/+bug/296788
1393 if (leftIndex <= 2) return;
1394 if (this.animating) return;
1396 if (null != this.leafEdgeTmp) {
1397 alert('error: leafEdgeTmp should be null!');
1401 if (null == index) {
1402 index = leftIndex-2;
1404 //if (index<0) return;
1406 var previousIndices = this.getSpreadIndices(index);
1408 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1412 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1414 this.animating = true;
1416 if ('rl' != this.pageProgression) {
1417 // Assume LTR and we are going backward
1418 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1419 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1421 // RTL and going backward
1422 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1423 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1427 // flipLeftToRight()
1428 //______________________________________________________________________________
1429 // Flips the page on the left towards the page on the right
1430 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1432 var leftLeaf = this.twoPage.currentIndexL;
1434 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1435 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1436 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1438 var currWidthL = this.getPageWidth2UP(leftLeaf);
1439 var newWidthL = this.getPageWidth2UP(newIndexL);
1440 var newWidthR = this.getPageWidth2UP(newIndexR);
1442 var top = this.twoPageTop();
1443 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1445 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1446 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1448 //animation strategy:
1449 // 0. remove search highlight, if any.
1450 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1451 // of the left leaf and where the user clicked in the leaf edge.
1452 // Note that if this function was triggered by left() and not a
1453 // mouse click, the width of leafEdgeTmp is very small (zero px).
1454 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1455 // leftLeaf to width=0.
1456 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1457 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1458 // its new full width.
1459 // 4. After step 3 is finished, do the following:
1460 // - remove leafEdgeTmp from the dom.
1461 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1462 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1463 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1464 // and width=newLeafEdgeWidthL.
1465 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1466 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1467 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1468 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1469 // - prefetch new adjacent leafs.
1470 // - set up click handlers for both new left and right leafs.
1471 // - redraw the search highlight.
1472 // - update the pagenum box and the url.
1475 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1477 this.leafEdgeTmp = document.createElement('div');
1478 $(this.leafEdgeTmp).css({
1479 borderStyle: 'solid none solid solid',
1480 borderColor: 'rgb(51, 51, 34)',
1481 borderWidth: '1px 0px 1px 1px',
1482 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1483 width: leafEdgeTmpW + 'px',
1484 height: this.twoPage.height-1 + 'px',
1485 left: leftEdgeTmpLeft + 'px',
1487 position: 'absolute',
1489 }).appendTo('#GBtwopageview');
1491 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1492 $(this.leafEdgeL).css({
1493 width: newLeafEdgeWidthL+'px',
1494 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1497 // Left gets the offset of the current left leaf from the document
1498 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1499 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1500 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1502 // We change the left leaf to right positioning
1503 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1504 $(this.prefetchedImgs[leftLeaf]).css({
1509 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1510 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1514 this.removeSearchHilites();
1516 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1517 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1519 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1520 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1522 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1523 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1524 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1526 $(self.leafEdgeR).css({
1527 // Moves the right leaf edge
1528 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1529 left: gutter+newWidthR+'px'
1532 $(self.leafEdgeL).css({
1533 // Moves and resizes the left leaf edge
1534 width: newLeafEdgeWidthL+'px',
1535 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1538 // Resizes the brown border div
1539 $(self.twoPage.coverDiv).css({
1540 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1541 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1544 $(self.leafEdgeTmp).remove();
1545 self.leafEdgeTmp = null;
1547 // $$$ TODO refactor with opposite direction flip
1548 self.twoPage.currentIndexL = newIndexL;
1549 self.twoPage.currentIndexR = newIndexR;
1550 self.twoPage.scaledWL = newWidthL;
1551 self.twoPage.scaledWR = newWidthR;
1552 self.firstIndex = self.twoPage.currentIndexL;
1553 self.displayedIndices = [newIndexL, newIndexR];
1554 self.setClickHandlers();
1555 self.twoPageSetCursor();
1556 self.pruneUnusedImgs();
1558 self.animating = false;
1560 self.updateSearchHilites2UP();
1561 self.updatePageNumBox2UP();
1563 self.twoPagePlaceFlipAreas();
1565 if (self.animationFinishedCallback) {
1566 self.animationFinishedCallback();
1567 self.animationFinishedCallback = null;
1575 //______________________________________________________________________________
1576 // Whether we flip left or right is dependent on the page progression
1577 // to flip forward one spread, pass index=null
1578 GnuBook.prototype.flipFwdToIndex = function(index) {
1580 if (this.animating) return;
1582 if (null != this.leafEdgeTmp) {
1583 alert('error: leafEdgeTmp should be null!');
1587 if (null == index) {
1588 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1590 if (index > this.lastDisplayableIndex()) return;
1592 this.animating = true;
1594 var nextIndices = this.getSpreadIndices(index);
1596 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1598 if ('rl' != this.pageProgression) {
1599 // We did not specify RTL
1600 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1601 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1604 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1605 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1609 // flipRightToLeft(nextL, nextR, gutter)
1610 // $$$ better not to have to pass gutter in
1611 //______________________________________________________________________________
1612 // Flip from left to right and show the nextL and nextR indices on those sides
1613 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1614 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1615 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1616 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1617 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1619 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1621 var top = this.twoPageTop();
1622 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1624 var middle = this.twoPage.middle;
1625 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1627 this.leafEdgeTmp = document.createElement('div');
1628 $(this.leafEdgeTmp).css({
1629 borderStyle: 'solid none solid solid',
1630 borderColor: 'rgb(51, 51, 34)',
1631 borderWidth: '1px 0px 1px 1px',
1632 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1633 width: leafEdgeTmpW + 'px',
1634 height: this.twoPage.height-1 + 'px',
1635 left: gutter+scaledW+'px',
1637 position: 'absolute',
1639 }).appendTo('#GBtwopageview');
1641 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1642 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1644 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1645 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1646 var newWidthL = this.getPageWidth2UP(newIndexL);
1647 var newWidthR = this.getPageWidth2UP(newIndexR);
1649 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1651 var self = this; // closure-tastic!
1653 var speed = this.flipSpeed;
1655 this.removeSearchHilites();
1657 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1658 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1659 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1660 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1661 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1663 $(self.leafEdgeL).css({
1664 width: newLeafEdgeWidthL+'px',
1665 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1668 // Resizes the book cover
1669 $(self.twoPage.coverDiv).css({
1670 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1671 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1674 $(self.leafEdgeTmp).remove();
1675 self.leafEdgeTmp = null;
1677 self.twoPage.currentIndexL = newIndexL;
1678 self.twoPage.currentIndexR = newIndexR;
1679 self.twoPage.scaledWL = newWidthL;
1680 self.twoPage.scaledWR = newWidthR;
1682 self.firstIndex = self.twoPage.currentIndexL;
1683 self.displayedIndices = [newIndexL, newIndexR];
1684 self.setClickHandlers();
1685 self.twoPageSetCursor();
1686 self.pruneUnusedImgs();
1688 self.animating = false;
1691 self.updateSearchHilites2UP();
1692 self.updatePageNumBox2UP();
1694 self.twoPagePlaceFlipAreas();
1696 if (self.animationFinishedCallback) {
1697 self.animationFinishedCallback();
1698 self.animationFinishedCallback = null;
1705 //______________________________________________________________________________
1706 GnuBook.prototype.setClickHandlers = function() {
1709 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1714 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1721 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1722 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1726 //______________________________________________________________________________
1727 GnuBook.prototype.prefetchImg = function(index) {
1728 if (undefined == this.prefetchedImgs[index]) {
1729 //console.log('prefetching ' + index);
1730 var img = document.createElement("img");
1731 img.src = this.getPageURI(index);
1732 this.prefetchedImgs[index] = img;
1737 // prepareFlipLeftToRight()
1739 //______________________________________________________________________________
1741 // Prepare to flip the left page towards the right. This corresponds to moving
1742 // backward when the page progression is left to right.
1743 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1745 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1747 this.prefetchImg(prevL);
1748 this.prefetchImg(prevR);
1750 var height = this.getPageHeight(prevL);
1751 var width = this.getPageWidth(prevL);
1752 var middle = this.twoPage.middle;
1753 var top = this.twoPageTop();
1754 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1756 // The gutter is the dividing line between the left and right pages.
1757 // It is offset from the middle to create the illusion of thickness to the pages
1758 var gutter = middle + this.gutterOffsetForIndex(prevL);
1760 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1761 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1762 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1764 $(this.prefetchedImgs[prevL]).css({
1765 position: 'absolute',
1766 left: gutter-scaledW+'px',
1767 right: '', // clear right property
1769 backgroundColor: 'rgb(234, 226, 205)',
1770 height: this.twoPage.height,
1771 width: scaledW+'px',
1772 borderRight: '1px solid black',
1776 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1778 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1780 $(this.prefetchedImgs[prevR]).css({
1781 position: 'absolute',
1785 backgroundColor: 'rgb(234, 226, 205)',
1786 height: this.twoPage.height,
1788 borderLeft: '1px solid black',
1792 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1796 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1797 // prepareFlipRightToLeft()
1798 //______________________________________________________________________________
1799 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1801 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1804 this.prefetchImg(nextL);
1805 this.prefetchImg(nextR);
1807 var height = this.getPageHeight(nextR);
1808 var width = this.getPageWidth(nextR);
1809 var middle = this.twoPage.middle;
1810 var top = this.twoPageTop();
1811 var scaledW = this.twoPage.height*width/height;
1813 var gutter = middle + this.gutterOffsetForIndex(nextL);
1815 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1816 $(this.prefetchedImgs[nextR]).css({
1817 position: 'absolute',
1820 backgroundColor: 'rgb(234, 226, 205)',
1821 height: this.twoPage.height,
1822 width: scaledW+'px',
1823 borderLeft: '1px solid black',
1827 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1829 height = this.getPageHeight(nextL);
1830 width = this.getPageWidth(nextL);
1831 scaledW = this.twoPage.height*width/height;
1833 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1834 $(this.prefetchedImgs[nextL]).css({
1835 position: 'absolute',
1836 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1838 backgroundColor: 'rgb(234, 226, 205)',
1839 height: this.twoPage.height,
1840 width: 0+'px', // Start at 0 width, then grow to the left
1841 borderRight: '1px solid black',
1845 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1849 // getNextLeafs() -- NOT RTL AWARE
1850 //______________________________________________________________________________
1851 // GnuBook.prototype.getNextLeafs = function(o) {
1852 // //TODO: we might have two left or two right leafs in a row (damaged book)
1853 // //For now, assume that leafs are contiguous.
1855 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1856 // o.L = this.twoPage.currentIndexL+2;
1857 // o.R = this.twoPage.currentIndexL+3;
1860 // getprevLeafs() -- NOT RTL AWARE
1861 //______________________________________________________________________________
1862 // GnuBook.prototype.getPrevLeafs = function(o) {
1863 // //TODO: we might have two left or two right leafs in a row (damaged book)
1864 // //For now, assume that leafs are contiguous.
1866 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1867 // o.L = this.twoPage.currentIndexL-2;
1868 // o.R = this.twoPage.currentIndexL-1;
1871 // pruneUnusedImgs()
1872 //______________________________________________________________________________
1873 GnuBook.prototype.pruneUnusedImgs = function() {
1874 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1875 for (var key in this.prefetchedImgs) {
1876 //console.log('key is ' + key);
1877 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1878 //console.log('removing key '+ key);
1879 $(this.prefetchedImgs[key]).remove();
1881 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1882 //console.log('deleting key '+ key);
1883 delete this.prefetchedImgs[key];
1889 //______________________________________________________________________________
1890 GnuBook.prototype.prefetch = function() {
1892 var lim = this.twoPage.currentIndexL-4;
1894 lim = Math.max(lim, 0);
1895 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1896 this.prefetchImg(i);
1899 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1900 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1901 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1902 this.prefetchImg(i);
1907 // getPageWidth2UP()
1908 //______________________________________________________________________________
1909 GnuBook.prototype.getPageWidth2UP = function(index) {
1910 // We return the width based on the dominant height
1911 var height = this.getPageHeight(index);
1912 var width = this.getPageWidth(index);
1913 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1917 //______________________________________________________________________________
1918 GnuBook.prototype.search = function(term) {
1919 $('#GnuBookSearchScript').remove();
1920 var script = document.createElement("script");
1921 script.setAttribute('id', 'GnuBookSearchScript');
1922 script.setAttribute("type", "text/javascript");
1923 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1924 document.getElementsByTagName('head')[0].appendChild(script);
1925 $('#GnuBookSearchResults').html('Searching...');
1928 // GBSearchCallback()
1929 //______________________________________________________________________________
1930 GnuBook.prototype.GBSearchCallback = function(txt) {
1932 if (jQuery.browser.msie) {
1933 var dom=new ActiveXObject("Microsoft.XMLDOM");
1937 var parser = new DOMParser();
1938 var dom = parser.parseFromString(txt, "text/xml");
1941 $('#GnuBookSearchResults').empty();
1942 $('#GnuBookSearchResults').append('<ul>');
1944 for (var key in this.searchResults) {
1945 if (null != this.searchResults[key].div) {
1946 $(this.searchResults[key].div).remove();
1948 delete this.searchResults[key];
1951 var pages = dom.getElementsByTagName('PAGE');
1953 if (0 == pages.length) {
1954 // $$$ it would be nice to echo the (sanitized) search result here
1955 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1957 for (var i = 0; i < pages.length; i++){
1958 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1961 var re = new RegExp (/_(\d{4})/);
1962 var reMatch = re.exec(pages[i].getAttribute('file'));
1963 var index = parseInt(reMatch[1], 10);
1964 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1966 var children = pages[i].childNodes;
1968 for (var j=0; j<children.length; j++) {
1969 //console.log(j + ' - ' + children[j].nodeName);
1970 //console.log(children[j].firstChild.nodeValue);
1971 if ('CONTEXT' == children[j].nodeName) {
1972 context += children[j].firstChild.nodeValue;
1973 } else if ('WORD' == children[j].nodeName) {
1974 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1976 var index = this.leafNumToIndex(index);
1977 if (null != index) {
1978 //coordinates are [left, bottom, right, top, [baseline]]
1979 //we'll skip baseline for now...
1980 var coords = children[j].getAttribute('coords').split(',',4);
1981 if (4 == coords.length) {
1982 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1987 var pageName = this.getPageName(index);
1988 //TODO: remove hardcoded instance name
1989 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1992 $('#GnuBookSearchResults').append('</ul>');
1994 this.updateSearchHilites();
1997 // updateSearchHilites()
1998 //______________________________________________________________________________
1999 GnuBook.prototype.updateSearchHilites = function() {
2000 if (2 == this.mode) {
2001 this.updateSearchHilites2UP();
2003 this.updateSearchHilites1UP();
2007 // showSearchHilites1UP()
2008 //______________________________________________________________________________
2009 GnuBook.prototype.updateSearchHilites1UP = function() {
2011 for (var key in this.searchResults) {
2013 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2014 var result = this.searchResults[key];
2015 if(null == result.div) {
2016 result.div = document.createElement('div');
2017 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2018 //console.log('appending ' + key);
2021 width: (result.r-result.l)/this.reduce + 'px',
2022 height: (result.b-result.t)/this.reduce + 'px',
2023 left: (result.l)/this.reduce + 'px',
2024 top: (result.t)/this.reduce +'px'
2028 //console.log(key + ' not displayed');
2029 this.searchResults[key].div=null;
2035 //______________________________________________________________________________
2036 // Returns the position of the gutter (line between the page images)
2037 GnuBook.prototype.twoPageGutter = function() {
2038 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2042 //______________________________________________________________________________
2043 // Returns the offset for the top of the page images
2044 GnuBook.prototype.twoPageTop = function() {
2045 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2048 // twoPageCoverWidth()
2049 //______________________________________________________________________________
2050 // Returns the width of the cover div given the total page width
2051 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2052 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2055 // twoPageGetViewCenter()
2056 //______________________________________________________________________________
2057 // Returns the percentage offset into twopageview div at the center of container div
2058 // { percentageX: float, percentageY: float }
2059 GnuBook.prototype.twoPageGetViewCenter = function() {
2062 var containerOffset = $('#GBcontainer').offset();
2063 var viewOffset = $('#GBtwopageview').offset();
2064 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2065 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2070 // twoPageCenterView(percentageX, percentageY)
2071 //______________________________________________________________________________
2072 // Centers the point given by percentage from left,top of twopageview
2073 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2074 if ('undefined' == typeof(percentageX)) {
2077 if ('undefined' == typeof(percentageY)) {
2081 var viewWidth = $('#GBtwopageview').width();
2082 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2083 var intoViewX = percentageX * viewWidth;
2085 var viewHeight = $('#GBtwopageview').height();
2086 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2087 var intoViewY = percentageY * viewHeight;
2089 if (viewWidth < containerClientWidth) {
2090 // Can fit width without scrollbars - center by adjusting offset
2091 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2093 // Need to scroll to center
2094 $('#GBtwopageview').css('left', 0);
2095 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2098 if (viewHeight < containerClientHeight) {
2099 // Fits with scrollbars - add offset
2100 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2102 $('#GBtwopageview').css('top', 0);
2103 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2107 // twoPageFlipAreaHeight
2108 //______________________________________________________________________________
2109 // Returns the integer height of the click-to-flip areas at the edges of the book
2110 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2111 return parseInt(this.twoPage.height);
2114 // twoPageFlipAreaWidth
2115 //______________________________________________________________________________
2116 // Returns the integer width of the flip areas
2117 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2118 var max = 100; // $$$ TODO base on view width?
2121 var width = this.twoPage.width * 0.15;
2122 return parseInt(GnuBook.util.clamp(width, min, max));
2125 // twoPageFlipAreaTop
2126 //______________________________________________________________________________
2127 // Returns integer top offset for flip areas
2128 GnuBook.prototype.twoPageFlipAreaTop = function() {
2129 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2132 // twoPageLeftFlipAreaLeft
2133 //______________________________________________________________________________
2134 // Left offset for left flip area
2135 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2136 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2139 // twoPageRightFlipAreaLeft
2140 //______________________________________________________________________________
2141 // Left offset for right flip area
2142 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2143 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2146 // twoPagePlaceFlipAreas
2147 //______________________________________________________________________________
2148 // Readjusts position of flip areas based on current layout
2149 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2150 // We don't set top since it shouldn't change relative to view
2151 $(this.twoPage.leftFlipArea).css({
2152 left: this.twoPageLeftFlipAreaLeft() + 'px'
2154 $(this.twoPage.rightFlipArea).css({
2155 left: this.twoPageRightFlipAreaLeft() + 'px'
2159 // showSearchHilites2UP()
2160 //______________________________________________________________________________
2161 GnuBook.prototype.updateSearchHilites2UP = function() {
2163 for (var key in this.searchResults) {
2164 key = parseInt(key, 10);
2165 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2166 var result = this.searchResults[key];
2167 if(null == result.div) {
2168 result.div = document.createElement('div');
2169 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2170 //console.log('appending ' + key);
2173 // We calculate the reduction factor for the specific page because it can be different
2174 // for each page in the spread
2175 var height = this.getPageHeight(key);
2176 var width = this.getPageWidth(key)
2177 var reduce = this.twoPage.height/height;
2178 var scaledW = parseInt(width*reduce);
2180 var gutter = this.twoPageGutter();
2182 if ('L' == this.getPageSide(key)) {
2183 pageL = gutter-scaledW;
2187 var pageT = this.twoPageTop();
2190 width: (result.r-result.l)*reduce + 'px',
2191 height: (result.b-result.t)*reduce + 'px',
2192 left: pageL+(result.l)*reduce + 'px',
2193 top: pageT+(result.t)*reduce +'px'
2197 //console.log(key + ' not displayed');
2198 if (null != this.searchResults[key].div) {
2199 //console.log('removing ' + key);
2200 $(this.searchResults[key].div).remove();
2202 this.searchResults[key].div=null;
2207 // removeSearchHilites()
2208 //______________________________________________________________________________
2209 GnuBook.prototype.removeSearchHilites = function() {
2210 for (var key in this.searchResults) {
2211 if (null != this.searchResults[key].div) {
2212 $(this.searchResults[key].div).remove();
2213 this.searchResults[key].div=null;
2219 //______________________________________________________________________________
2220 GnuBook.prototype.showEmbedCode = function() {
2221 if (null != this.embedPopup) { // check if already showing
2225 this.embedPopup = document.createElement("div");
2226 $(this.embedPopup).css({
2227 position: 'absolute',
2229 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2232 border: "3px double #999999",
2234 backgroundColor: "#fff"
2235 }).appendTo('#GnuBook');
2237 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2238 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>';
2239 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2240 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2242 this.embedPopup.innerHTML = htmlStr;
2243 $(this.embedPopup).find('input').bind('click', function() {
2249 //______________________________________________________________________________
2250 GnuBook.prototype.autoToggle = function() {
2252 var bComingFrom1up = false;
2253 if (2 != this.mode) {
2254 bComingFrom1up = true;
2258 // Change to autofit if book is too large
2259 if (this.reduce < this.twoPageGetAutofitReduce()) {
2264 if (null == this.autoTimer) {
2265 this.flipSpeed = 2000;
2267 // $$$ Draw events currently cause layout problems when they occur during animation.
2268 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2269 // we workaround for now by not triggering immediate animation in that case.
2270 // See https://bugs.launchpad.net/gnubook/+bug/328327
2271 if (('rl' == this.pageProgression) && bComingFrom1up) {
2272 // don't flip immediately -- wait until timer fires
2275 this.flipFwdToIndex();
2278 $('#GBtoolbar .play').hide();
2279 $('#GBtoolbar .pause').show();
2280 this.autoTimer=setInterval(function(){
2281 if (self.animating) {return;}
2283 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2284 self.flipBackToIndex(1); // $$$ really what we want?
2286 self.flipFwdToIndex();
2295 //______________________________________________________________________________
2296 // Stop autoplay mode, allowing animations to finish
2297 GnuBook.prototype.autoStop = function() {
2298 if (null != this.autoTimer) {
2299 clearInterval(this.autoTimer);
2300 this.flipSpeed = 'fast';
2301 $('#GBtoolbar .pause').hide();
2302 $('#GBtoolbar .play').show();
2303 this.autoTimer = null;
2307 // stopFlipAnimations
2308 //______________________________________________________________________________
2309 // Immediately stop flip animations. Callbacks are triggered.
2310 GnuBook.prototype.stopFlipAnimations = function() {
2312 this.autoStop(); // Clear timers
2314 // Stop animation, clear queue, trigger callbacks
2315 if (this.leafEdgeTmp) {
2316 $(this.leafEdgeTmp).stop(false, true);
2318 jQuery.each(this.prefetchedImgs, function() {
2319 $(this).stop(false, true);
2322 // And again since animations also queued in callbacks
2323 if (this.leafEdgeTmp) {
2324 $(this.leafEdgeTmp).stop(false, true);
2326 jQuery.each(this.prefetchedImgs, function() {
2327 $(this).stop(false, true);
2332 // keyboardNavigationIsDisabled(event)
2333 // - returns true if keyboard navigation should be disabled for the event
2334 //______________________________________________________________________________
2335 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2336 if (event.target.tagName == "INPUT") {
2342 // gutterOffsetForIndex
2343 //______________________________________________________________________________
2345 // Returns the gutter offset for the spread containing the given index.
2346 // This function supports RTL
2347 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2349 // To find the offset of the gutter from the middle we calculate our percentage distance
2350 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2351 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2353 // But then again for RTL it's the opposite
2354 if ('rl' == this.pageProgression) {
2362 //______________________________________________________________________________
2363 // Returns the width of the leaf edge div for the page with index given
2364 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2365 // $$$ could there be single pixel rounding errors for L vs R?
2366 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2367 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2369 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2373 // jumpIndexForLeftEdgePageX
2374 //______________________________________________________________________________
2375 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2376 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2377 if ('rl' != this.pageProgression) {
2378 // LTR - flipping backward
2379 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2381 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2382 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2386 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2387 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2392 // jumpIndexForRightEdgePageX
2393 //______________________________________________________________________________
2394 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2395 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2396 if ('rl' != this.pageProgression) {
2398 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2399 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2402 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2403 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2408 GnuBook.prototype.initToolbar = function(mode, ui) {
2410 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2411 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2412 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2413 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2414 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2415 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2416 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2417 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2420 this.updateToolbarZoom(this.reduce); // Pretty format
2422 if (ui == "embed") {
2423 $("#GnuBook a.logo").attr("target","_blank");
2426 // $$$ turn this into a member variable
2427 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2429 // We build in mode 2
2430 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2431 + "<button class='GBicon rollover embed' />"
2432 + "<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>"
2433 + "<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>"
2434 + "<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>"
2435 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2437 this.bindToolbarNavHandlers(jToolbar);
2439 // Setup tooltips -- later we could load these from a file for i18n
2440 var titles = { '.logo': 'Go to Archive.org',
2441 '.zoom_in': 'Zoom in',
2442 '.zoom_out': 'Zoom out',
2443 '.one_page_mode': 'One-page view',
2444 '.two_page_mode': 'Two-page view',
2445 '.embed': 'Embed bookreader',
2446 '.book_left': 'Flip left',
2447 '.book_right': 'Flip right',
2448 '.book_up': 'Page up',
2449 '.book_down': 'Page down',
2452 '.book_top': 'First page',
2453 '.book_bottom': 'Last page'
2455 if ('rl' == this.pageProgression) {
2456 titles['.book_leftmost'] = 'Last page';
2457 titles['.book_rightmost'] = 'First page';
2459 titles['.book_leftmost'] = 'First page';
2460 titles['.book_rightmost'] = 'Last page';
2463 for (var icon in titles) {
2464 jToolbar.find(icon).attr('title', titles[icon]);
2467 // Hide mode buttons and autoplay if 2up is not available
2468 // $$$ if we end up with more than two modes we should show the applicable buttons
2469 if ( !this.canSwitchToMode(this.constMode2up) ) {
2470 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2473 // Switch to requested mode -- binds other click handlers
2474 this.switchToolbarMode(mode);
2479 // switchToolbarMode
2480 //______________________________________________________________________________
2481 // Update the toolbar for the given mode (changes navigation buttons)
2482 // $$$ we should soon split the toolbar out into its own module
2483 GnuBook.prototype.switchToolbarMode = function(mode) {
2486 $('#GBtoolbar .GBtoolbarmode2').hide();
2487 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2490 $('#GBtoolbar .GBtoolbarmode1').hide();
2491 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2495 // bindToolbarNavHandlers
2496 //______________________________________________________________________________
2497 // Binds the toolbar handlers
2498 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2500 jToolbar.find('.book_left').bind('click', function(e) {
2505 jToolbar.find('.book_right').bind('click', function(e) {
2510 jToolbar.find('.book_up').bind('click', function(e) {
2515 jToolbar.find('.book_down').bind('click', function(e) {
2520 jToolbar.find('.embed').bind('click', function(e) {
2525 jToolbar.find('.play').bind('click', function(e) {
2530 jToolbar.find('.pause').bind('click', function(e) {
2535 jToolbar.find('.book_top').bind('click', function(e) {
2540 jToolbar.find('.book_bottom').bind('click', function(e) {
2545 jToolbar.find('.book_leftmost').bind('click', function(e) {
2550 jToolbar.find('.book_rightmost').bind('click', function(e) {
2556 // updateToolbarZoom(reduce)
2557 //______________________________________________________________________________
2558 // Update the displayed zoom factor based on reduction factor
2559 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2561 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2564 value = (100 / reduce).toFixed(2);
2565 // Strip trailing zeroes and decimal if all zeroes
2566 value = value.replace(/0+$/,'');
2567 value = value.replace(/\.$/,'');
2570 $('#GBzoom').text(value);
2573 // firstDisplayableIndex
2574 //______________________________________________________________________________
2575 // Returns the index of the first visible page, dependent on the mode.
2576 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2577 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2578 GnuBook.prototype.firstDisplayableIndex = function() {
2579 if (this.mode == 0) {
2582 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2586 // lastDisplayableIndex
2587 //______________________________________________________________________________
2588 // Returns the index of the last visible page, dependent on the mode.
2589 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2590 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2591 GnuBook.prototype.lastDisplayableIndex = function() {
2592 if (this.mode == 2) {
2593 if (this.lastDisplayableIndex2up === null) {
2594 // Calculate and cache
2595 var candidate = this.numLeafs - 1;
2596 for ( ; candidate >= 0; candidate--) {
2597 var spreadIndices = this.getSpreadIndices(candidate);
2598 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2602 this.lastDisplayableIndex2up = candidate;
2604 return this.lastDisplayableIndex2up;
2606 return this.numLeafs - 1;
2610 // shortTitle(maximumCharacters)
2612 // Returns a shortened version of the title with the maximum number of characters
2613 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2614 if (this.bookTitle.length < maximumCharacters) {
2615 return this.bookTitle;
2618 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2625 // Parameter related functions
2627 // updateFromParams(params)
2629 // Update ourselves from the params object.
2631 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2632 GnuBook.prototype.updateFromParams = function(params) {
2633 if ('undefined' != typeof(params.mode)) {
2634 this.switchMode(params.mode);
2637 // $$$ process /search
2638 // $$$ process /zoom
2640 // We only respect page if index is not set
2641 if ('undefined' != typeof(params.index)) {
2642 if (params.index != this.currentIndex()) {
2643 this.jumpToIndex(params.index);
2645 } else if ('undefined' != typeof(params.page)) {
2646 // $$$ this assumes page numbers are unique
2647 if (params.page != this.getPageNum(this.currentIndex())) {
2648 this.jumpToPage(params.page);
2652 // $$$ process /region
2653 // $$$ process /highlight
2656 // paramsFromFragment(urlFragment)
2658 // Returns a object with configuration parametes from a URL fragment.
2660 // E.g paramsFromFragment(window.location.hash)
2661 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2662 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2666 // For convenience we allow an initial # character (as from window.location.hash)
2667 // but don't require it
2668 if (urlFragment.substr(0,1) == '#') {
2669 urlFragment = urlFragment.substr(1);
2672 // Simple #nn syntax
2673 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2674 if ( !isNaN(oldStyleLeafNum) ) {
2675 params.index = oldStyleLeafNum;
2677 // Done processing if using old-style syntax
2681 // Split into key-value pairs
2682 var urlArray = urlFragment.split('/');
2684 for (var i = 0; i < urlArray.length; i += 2) {
2685 urlHash[urlArray[i]] = urlArray[i+1];
2689 if ('1up' == urlHash['mode']) {
2690 params.mode = this.constMode1up;
2691 } else if ('2up' == urlHash['mode']) {
2692 params.mode = this.constMode2up;
2696 if ('undefined' != typeof(urlHash['page'])) {
2697 // page was set -- may not be int
2698 params.page = urlHash['page'];
2701 // $$$ process /region
2702 // $$$ process /search
2703 // $$$ process /highlight
2708 // paramsFromCurrent()
2710 // Create a params object from the current parameters.
2711 GnuBook.prototype.paramsFromCurrent = function() {
2715 var pageNum = this.getPageNum(this.currentIndex());
2716 if ((pageNum === 0) || pageNum) {
2717 params.page = pageNum;
2720 params.index = this.currentIndex();
2721 params.mode = this.mode;
2730 // fragmentFromParams(params)
2732 // Create a fragment string from the params object.
2733 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2734 GnuBook.prototype.fragmentFromParams = function(params) {
2735 var separator = '/';
2739 if ('undefined' != typeof(params.page)) {
2740 fragments.push('page', params.page);
2742 // Don't have page numbering -- use index instead
2743 fragments.push('page', 'n' + params.index);
2751 if ('undefined' != typeof(params.mode)) {
2752 if (params.mode == this.constMode1up) {
2753 fragments.push('mode', '1up');
2754 } else if (params.mode == this.constMode2up) {
2755 fragments.push('mode', '2up');
2757 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2761 return fragments.join(separator);
2764 // getPageIndex(pageNum)
2766 // Returns the *highest* index the given page number, or undefined
2767 GnuBook.prototype.getPageIndex = function(pageNum) {
2768 var pageIndices = this.getPageIndices(pageNum);
2770 if (pageIndices.length > 0) {
2771 return pageIndices[pageIndices.length - 1];
2777 // getPageIndices(pageNum)
2779 // Returns an array (possibly empty) of the indices with the given page number
2780 GnuBook.prototype.getPageIndices = function(pageNum) {
2783 // Check for special "nXX" page number
2784 if (pageNum.slice(0,1) == 'n') {
2786 var pageIntStr = pageNum.slice(1, pageNum.length);
2787 var pageIndex = parseInt(pageIntStr);
2788 indices.append(pageIndex);
2791 // Do nothing... will run through page names and see if one matches
2796 for (i=0; i<this.numLeafs; i++) {
2797 if (this.getPageNum(i) == pageNum) {
2805 // getPageName(index)
2807 // Returns the name of the page as it should be displayed in the user interface
2808 GnuBook.prototype.getPageName = function(index) {
2809 return 'Page ' + this.getPageNum(index);
2812 // updateLocationHash
2814 // Update the location hash from the current parameters. Call this instead of manually
2815 // using window.location.replace
2816 GnuBook.prototype.updateLocationHash = function() {
2817 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2818 window.location.replace(newHash);
2820 // This is the variable checked in the timer. Only user-generated changes
2821 // to the URL will trigger the event.
2822 this.oldLocationHash = newHash;
2825 // startLocationPolling
2827 // Starts polling of window.location to see hash fragment changes
2828 GnuBook.prototype.startLocationPolling = function() {
2829 var self = this; // remember who I am
2830 self.oldLocationHash = window.location.hash;
2832 if (this.locationPollId) {
2833 clearInterval(this.locationPollID);
2834 this.locationPollId = null;
2837 this.locationPollId = setInterval(function() {
2838 var newHash = window.location.hash;
2839 if (newHash != self.oldLocationHash) {
2840 if (newHash != self.oldUserHash) { // Only process new user hash once
2841 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2843 // Queue change if animating
2844 if (self.animating) {
2846 self.animationFinishedCallback = function() {
2847 self.updateFromParams(self.paramsFromFragment(newHash));
2849 } else { // update immediately
2850 self.updateFromParams(self.paramsFromFragment(newHash));
2852 self.oldUserHash = newHash;
2860 // Returns a URL for an embedded version of the current book
2861 GnuBook.prototype.getEmbedURL = function() {
2862 // We could generate a URL hash fragment here but for now we just leave at defaults
2863 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2868 // Returns the embed code HTML fragment suitable for copy and paste
2869 GnuBook.prototype.getEmbedCode = function() {
2870 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2875 // Returns true if we can switch to the requested mode
2876 GnuBook.prototype.canSwitchToMode = function(mode) {
2877 if (mode == this.constMode2up) {
2878 // check there are enough pages to display
2879 // $$$ this is a workaround for the mis-feature that we can't display
2880 // short books in 2up mode
2881 if (this.numLeafs < 6) {
2889 // Library functions
2891 clamp: function(value, min, max) {
2892 return Math.min(Math.max(value, min), max);