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) {
205 // Keyboard navigation
209 // In 1up mode page scrolling is handled by browser
210 if (2 == self.mode) {
217 if (2 == self.mode) {
231 if (self.keyboardNavigationIsDisabled(e)) {
235 if (2 == self.mode) {
241 if (self.keyboardNavigationIsDisabled(e)) {
245 if (2 == self.mode) {
255 //______________________________________________________________________________
256 GnuBook.prototype.drawLeafs = function() {
257 if (1 == this.mode) {
258 this.drawLeafsOnePage();
260 this.drawLeafsTwoPage();
265 //______________________________________________________________________________
266 GnuBook.prototype.setDragHandler = function(div) {
267 div.dragging = false;
269 $(div).unbind('mousedown').bind('mousedown', function(e) {
272 //console.log('mousedown at ' + e.pageY);
274 this.dragging = true;
275 this.prevMouseX = e.pageX;
276 this.prevMouseY = e.pageY;
278 var startX = e.pageX;
279 var startY = e.pageY;
280 var startTop = $('#GBcontainer').attr('scrollTop');
281 var startLeft = $('#GBcontainer').attr('scrollLeft');
285 $(div).unbind('mousemove').bind('mousemove', function(ee) {
288 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
290 var offsetX = ee.pageX - this.prevMouseX;
291 var offsetY = ee.pageY - this.prevMouseY;
294 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
295 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
298 this.prevMouseX = ee.pageX;
299 this.prevMouseY = ee.pageY;
303 $(div).unbind('mouseup').bind('mouseup', function(ee) {
305 //console.log('mouseup');
307 this.dragging = false;
310 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
312 //console.log('mouseleave');
314 this.dragging = false;
317 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
319 //console.log('mouseenter');
321 this.dragging = false;
325 // setDragHandler2up()
326 //______________________________________________________________________________
327 GnuBook.prototype.setDragHandler2up = function(div) {
328 div.dragging = false;
330 $(div).unbind('mousedown').bind('mousedown', function(e) {
333 //console.log('mousedown at ' + e.pageY);
335 this.dragStart = {x: e.pageX, y: e.pageY };
336 this.mouseDown = true;
337 this.dragging = false; // wait until drag distance
338 this.prevMouseX = e.pageX;
339 this.prevMouseY = e.pageY;
341 var startX = e.pageX;
342 var startY = e.pageY;
343 var startTop = $('#GBcontainer').attr('scrollTop');
344 var startLeft = $('#GBcontainer').attr('scrollLeft');
348 $(div).unbind('mousemove').bind('mousemove', function(ee) {
351 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
353 var offsetX = ee.pageX - this.prevMouseX;
354 var offsetY = ee.pageY - this.prevMouseY;
356 var minDragDistance = 5; // $$$ constant
358 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
360 if (this.mouseDown && (distance > minDragDistance)) {
361 //console.log('drag start!');
363 this.dragging = true;
367 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
368 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
369 this.prevMouseX = ee.pageX;
370 this.prevMouseY = ee.pageY;
377 $(div).unbind('mouseup').bind('mouseup', function(ee) {
379 //console.log('mouseup');
381 this.dragging = false;
382 this.mouseDown = false;
387 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
389 //console.log('mouseleave');
391 this.dragging = false;
392 this.mouseDown = false;
395 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
397 //console.log('mouseenter');
399 this.dragging = false;
400 this.mouseDown = false;
404 GnuBook.prototype.setClickHandler2up = function( element, data, handler) {
405 //console.log('setting handler');
406 //console.log(element.tagName);
408 $(element).unbind('click').bind('click', data, function(e) {
411 //console.log('click!');
413 if (this.mouseDown && (!this.dragging)) {
414 //console.log('click not dragging!');
418 this.dragging = false;
419 this.mouseDown = false;
423 // drawLeafsOnePage()
424 //______________________________________________________________________________
425 GnuBook.prototype.drawLeafsOnePage = function() {
426 //alert('drawing leafs!');
430 var scrollTop = $('#GBcontainer').attr('scrollTop');
431 var scrollBottom = scrollTop + $('#GBcontainer').height();
432 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
434 var indicesToDisplay = [];
439 for (i=0; i<this.numLeafs; i++) {
440 var height = parseInt(this.getPageHeight(i)/this.reduce);
442 leafBottom += height;
443 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
444 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
445 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
446 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
447 if (topInView | bottomInView | middleInView) {
448 //console.log('displayed: ' + this.displayedIndices);
449 //console.log('to display: ' + i);
450 indicesToDisplay.push(i);
452 leafTop += height +10;
456 var firstIndexToDraw = indicesToDisplay[0];
457 this.firstIndex = firstIndexToDraw;
459 // Update hash, but only if we're currently displaying a leaf
460 // Hack that fixes #365790
461 if (this.displayedIndices.length > 0) {
462 this.updateLocationHash();
465 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
467 indicesToDisplay.unshift(firstIndexToDraw);
470 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
471 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
472 indicesToDisplay.push(lastIndexToDraw+1);
477 for (i=0; i<firstIndexToDraw; i++) {
478 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
481 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
482 var viewWidth = $('#GBcontainer').attr('scrollWidth');
485 for (i=0; i<indicesToDisplay.length; i++) {
486 var index = indicesToDisplay[i];
487 var height = parseInt(this.getPageHeight(index)/this.reduce);
489 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
490 var width = parseInt(this.getPageWidth(index)/this.reduce);
491 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
492 var div = document.createElement("div");
493 div.className = 'GBpagediv1up';
494 div.id = 'pagediv'+index;
495 div.style.position = "absolute";
496 $(div).css('top', leafTop + 'px');
497 var left = (viewWidth-width)>>1;
498 if (left<0) left = 0;
499 $(div).css('left', left+'px');
500 $(div).css('width', width+'px');
501 $(div).css('height', height+'px');
502 //$(div).text('loading...');
504 this.setDragHandler(div);
506 $('#GBpageview').append(div);
508 var img = document.createElement("img");
509 img.src = this.getPageURI(index);
510 $(img).css('width', width+'px');
511 $(img).css('height', height+'px');
515 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
518 leafTop += height +10;
522 for (i=0; i<this.displayedIndices.length; i++) {
523 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
524 var index = this.displayedIndices[i];
525 //console.log('Removing leaf ' + index);
526 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
527 $('#pagediv'+index).remove();
529 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
533 this.displayedIndices = indicesToDisplay.slice();
534 this.updateSearchHilites();
536 if (null != this.getPageNum(firstIndexToDraw)) {
537 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
539 $("#GBpagenum").val('');
542 this.updateToolbarZoom(this.reduce);
546 // drawLeafsTwoPage()
547 //______________________________________________________________________________
548 GnuBook.prototype.drawLeafsTwoPage = function() {
549 var scrollTop = $('#GBtwopageview').attr('scrollTop');
550 var scrollBottom = scrollTop + $('#GBtwopageview').height();
552 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
554 var indexL = this.twoPage.currentIndexL;
555 var heightL = this.getPageHeight(indexL);
556 var widthL = this.getPageWidth(indexL);
558 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
559 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
560 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
561 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
562 //console.log(leafEdgeWidthL);
564 var middle = this.twoPage.middle; // $$$ getter instead?
565 var top = this.twoPageTop();
566 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
568 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
569 this.twoPage.gutter = this.twoPageGutter();
571 this.prefetchImg(indexL);
572 $(this.prefetchedImgs[indexL]).css({
573 position: 'absolute',
574 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
577 backgroundColor: 'rgb(234, 226, 205)',
578 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
579 width: this.twoPage.scaledWL + 'px',
580 borderRight: '1px solid black',
582 }).appendTo('#GBtwopageview');
584 var indexR = this.twoPage.currentIndexR;
585 var heightR = this.getPageHeight(indexR);
586 var widthR = this.getPageWidth(indexR);
588 // $$$ should use getwidth2up?
589 //var scaledWR = this.twoPage.height*widthR/heightR;
590 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
591 this.prefetchImg(indexR);
592 $(this.prefetchedImgs[indexR]).css({
593 position: 'absolute',
594 left: this.twoPage.gutter+'px',
597 backgroundColor: 'rgb(234, 226, 205)',
598 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
599 width: this.twoPage.scaledWR + 'px',
600 borderLeft: '1px solid black',
602 }).appendTo('#GBtwopageview');
605 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
606 this.setClickHandlers();
607 this.twoPageSetCursor();
609 this.updatePageNumBox2UP();
610 this.updateToolbarZoom(this.reduce);
612 this.twoPagePlaceFlipAreas();
616 // updatePageNumBox2UP
617 //______________________________________________________________________________
618 GnuBook.prototype.updatePageNumBox2UP = function() {
619 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
620 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
622 $("#GBpagenum").val('');
624 this.updateLocationHash();
628 //______________________________________________________________________________
629 GnuBook.prototype.loadLeafs = function() {
633 if (null == this.timer) {
634 this.timer=setTimeout(function(){self.drawLeafs()},250);
636 clearTimeout(this.timer);
637 this.timer=setTimeout(function(){self.drawLeafs()},250);
643 // Pass 1 to zoom in, anything else to zoom out
644 //______________________________________________________________________________
645 GnuBook.prototype.zoom = function(direction) {
647 case this.constMode1up:
648 return this.zoom1up(direction);
649 case this.constMode2up:
650 return this.zoom2up(direction);
655 //______________________________________________________________________________
656 GnuBook.prototype.zoom1up = function(dir) {
657 if (2 == this.mode) { //can only zoom in 1-page mode
662 // $$$ with flexible zoom we could "snap" to /2 page reductions
663 // for better scaling
665 if (this.reduce <= 0.5) return;
666 this.reduce*=0.5; //zoom in
668 if (this.reduce >= 8) return;
669 this.reduce*=2; //zoom out
672 this.resizePageView();
674 $('#GBpageview').empty()
675 this.displayedIndices = [];
678 this.updateToolbarZoom(this.reduce);
682 //______________________________________________________________________________
683 GnuBook.prototype.resizePageView = function() {
686 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
687 var viewWidth = $('#GBcontainer').attr('clientWidth');
689 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
690 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
691 var oldPageViewHeight = $('#GBpageview').height();
692 var oldPageViewWidth = $('#GBpageview').width();
694 var oldCenterY = this.centerY1up();
695 var oldCenterX = this.centerX1up();
697 if (0 != oldPageViewHeight) {
698 var scrollRatio = oldCenterY / oldPageViewHeight;
703 for (i=0; i<this.numLeafs; i++) {
704 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
705 var width = parseInt(this.getPageWidth(i)/this.reduce);
706 if (width>viewWidth) viewWidth=width;
708 $('#GBpageview').height(viewHeight);
709 $('#GBpageview').width(viewWidth);
711 var newCenterY = scrollRatio*viewHeight;
712 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
713 $('#GBcontainer').attr('scrollTop', newTop);
715 // We use clientWidth here to avoid miscalculating due to scroll bar
716 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
717 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
718 newLeft = Math.max(newLeft, 0);
719 $('#GBcontainer').attr('scrollLeft', newLeft);
720 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
722 //this.centerPageView();
728 //______________________________________________________________________________
729 // Returns the current offset of the viewport center in scaled document coordinates.
730 GnuBook.prototype.centerX1up = function() {
732 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
733 centerX = $('#GBpageview').width();
735 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
737 centerX = Math.floor(centerX);
742 //______________________________________________________________________________
743 // Returns the current offset of the viewport center in scaled document coordinates.
744 GnuBook.prototype.centerY1up = function() {
745 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
746 return Math.floor(centerY);
750 //______________________________________________________________________________
751 GnuBook.prototype.centerPageView = function() {
753 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
754 var clientWidth = $('#GBcontainer').attr('clientWidth');
755 //console.log('sW='+scrollWidth+' cW='+clientWidth);
756 if (scrollWidth > clientWidth) {
757 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
762 // zoom2up(direction)
763 //______________________________________________________________________________
764 GnuBook.prototype.zoom2up = function(direction) {
766 // Hard stop autoplay
767 this.stopFlipAnimations();
769 // Get new zoom state
770 var newZoom = this.twoPageNextReduce(this.reduce, direction);
771 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
774 this.twoPage.autofit = newZoom.autofit;
775 this.reduce = newZoom.reduce;
777 // Preserve view center position
778 var oldCenter = this.twoPageGetViewCenter();
780 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
781 // $$$ An improvement would be to use the low res image until the larger one is loaded.
782 if (1 == direction) {
783 for (var img in this.prefetchedImgs) {
784 delete this.prefetchedImgs[img];
788 // Prepare view with new center to minimize visual glitches
789 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
793 // quantizeReduce(reduce)
794 //______________________________________________________________________________
795 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
796 GnuBook.prototype.quantizeReduce = function(reduce) {
797 var quantized = this.reductionFactors[0];
798 var distance = Math.abs(reduce - quantized);
799 for (var i = 1; i < this.reductionFactors.length; i++) {
800 newDistance = Math.abs(reduce - this.reductionFactors[i]);
801 if (newDistance < distance) {
802 distance = newDistance;
803 quantized = this.reductionFactors[i];
810 // twoPageNextReduce()
811 //______________________________________________________________________________
812 // Returns the next reduction level
813 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
815 var autofitReduce = this.twoPageGetAutofitReduce();
817 if (0 == direction) { // autofit
818 result.autofit = true;
819 result.reduce = autofitReduce;
821 } else if (1 == direction) { // zoom in
822 var newReduce = this.reductionFactors[0];
824 for (var i = 1; i < this.reductionFactors.length; i++) {
825 if (this.reductionFactors[i] < reduce) {
826 newReduce = this.reductionFactors[i];
830 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
832 result.autofit = true;
833 result.reduce = autofitReduce;
835 result.autofit = false;
836 result.reduce = newReduce;
840 var lastIndex = this.reductionFactors.length - 1;
841 var newReduce = this.reductionFactors[lastIndex];
843 for (var i = lastIndex; i >= 0; i--) {
844 if (this.reductionFactors[i] > reduce) {
845 newReduce = this.reductionFactors[i];
849 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
851 result.autofit = true;
852 result.reduce = autofitReduce;
854 result.autofit = false;
855 result.reduce = newReduce;
863 //______________________________________________________________________________
864 // Attempts to jump to page. Returns true if page could be found, false otherwise.
865 GnuBook.prototype.jumpToPage = function(pageNum) {
867 var pageIndex = this.getPageIndex(pageNum);
869 if ('undefined' != typeof(pageIndex)) {
872 this.jumpToIndex(pageIndex);
873 $('#GBcontainer').attr('scrollTop', leafTop);
882 //______________________________________________________________________________
883 GnuBook.prototype.jumpToIndex = function(index) {
885 if (2 == this.mode) {
888 // By checking against min/max we do nothing if requested index
890 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
891 this.flipBackToIndex(index);
892 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
893 this.flipFwdToIndex(index);
900 for (i=0; i<index; i++) {
901 h = parseInt(this.getPageHeight(i)/this.reduce);
902 leafTop += h + this.padding;
904 //$('#GBcontainer').attr('scrollTop', leafTop);
905 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
912 //______________________________________________________________________________
913 GnuBook.prototype.switchMode = function(mode) {
915 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
917 if (mode == this.mode) return;
919 if (!this.canSwitchToMode(mode)) {
924 this.removeSearchHilites();
928 this.switchToolbarMode(mode);
930 // $$$ TODO preserve center of view when switching between mode
931 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
934 this.reduce = this.quantizeReduce(this.reduce);
935 this.prepareOnePageView();
937 this.twoPage.autofit = false; // Take zoom level from other mode
938 this.reduce = this.quantizeReduce(this.reduce);
939 this.prepareTwoPageView();
940 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
945 //prepareOnePageView()
946 //______________________________________________________________________________
947 GnuBook.prototype.prepareOnePageView = function() {
949 // var startLeaf = this.displayedIndices[0];
950 var startLeaf = this.currentIndex();
952 $('#GBcontainer').empty();
953 $('#GBcontainer').css({
958 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
960 this.resizePageView();
962 this.jumpToIndex(startLeaf);
963 this.displayedIndices = [];
965 this.drawLeafsOnePage();
967 // Bind mouse handlers
968 // Disable mouse click to avoid selected/highlighted page images - bug 354239
969 gbPageView.bind('mousedown', function(e) {
970 // $$$ check here for right-click and don't disable. Also use jQuery style
971 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
974 // Special hack for IE7
975 gbPageView[0].onselectstart = function(e) { return false; };
978 // prepareTwoPageView()
979 //______________________________________________________________________________
980 // Some decisions about two page view:
982 // Both pages will be displayed at the same height, even if they were different physical/scanned
983 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
984 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
985 // aspect ratio to determine the height.
987 // The two page view div is resized to keep the middle of the book in the middle of the div
988 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
989 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
990 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
991 $('#GBcontainer').empty();
992 $('#GBcontainer').css('overflow', 'auto');
994 // We want to display two facing pages. We may be missing
995 // one side of the spread because it is the first/last leaf,
996 // foldouts, missing pages, etc
998 //var targetLeaf = this.displayedIndices[0];
999 var targetLeaf = this.firstIndex;
1001 if (targetLeaf < this.firstDisplayableIndex()) {
1002 targetLeaf = this.firstDisplayableIndex();
1005 if (targetLeaf > this.lastDisplayableIndex()) {
1006 targetLeaf = this.lastDisplayableIndex();
1009 //this.twoPage.currentIndexL = null;
1010 //this.twoPage.currentIndexR = null;
1011 //this.pruneUnusedImgs();
1013 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1014 this.twoPage.currentIndexL = currentSpreadIndices[0];
1015 this.twoPage.currentIndexR = currentSpreadIndices[1];
1016 this.firstIndex = this.twoPage.currentIndexL;
1018 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1020 this.pruneUnusedImgs();
1021 this.prefetch(); // Preload images or reload if scaling has changed
1023 //console.dir(this.twoPage);
1025 // Add the two page view
1026 // $$$ Can we get everything set up and then append?
1027 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1029 // $$$ calculate first then set
1030 $('#GBtwopageview').css( {
1031 height: this.twoPage.totalHeight + 'px',
1032 width: this.twoPage.totalWidth + 'px',
1033 position: 'absolute'
1036 // If there will not be scrollbars (e.g. when zooming out) we center the book
1037 // since otherwise the book will be stuck off-center
1038 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1039 centerPercentageX = 0.5;
1041 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1042 centerPercentageY = 0.5;
1045 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1047 this.twoPage.coverDiv = document.createElement('div');
1048 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1049 border: '1px solid rgb(68, 25, 17)',
1050 width: this.twoPage.bookCoverDivWidth + 'px',
1051 height: this.twoPage.bookCoverDivHeight+'px',
1052 visibility: 'visible',
1053 position: 'absolute',
1054 backgroundColor: '#663929',
1055 left: this.twoPage.bookCoverDivLeft + 'px',
1056 top: this.twoPage.bookCoverDivTop+'px',
1057 MozBorderRadiusTopleft: '7px',
1058 MozBorderRadiusTopright: '7px',
1059 MozBorderRadiusBottomright: '7px',
1060 MozBorderRadiusBottomleft: '7px'
1061 }).appendTo('#GBtwopageview');
1063 this.leafEdgeR = document.createElement('div');
1064 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1065 $(this.leafEdgeR).css({
1066 borderStyle: 'solid solid solid none',
1067 borderColor: 'rgb(51, 51, 34)',
1068 borderWidth: '1px 1px 1px 0px',
1069 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1070 width: this.twoPage.leafEdgeWidthR + 'px',
1071 height: this.twoPage.height-1 + 'px',
1073 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1074 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1075 position: 'absolute'
1076 }).appendTo('#GBtwopageview');
1078 this.leafEdgeL = document.createElement('div');
1079 this.leafEdgeL.className = 'leafEdgeL';
1080 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1081 borderStyle: 'solid none solid solid',
1082 borderColor: 'rgb(51, 51, 34)',
1083 borderWidth: '1px 0px 1px 1px',
1084 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1085 width: this.twoPage.leafEdgeWidthL + 'px',
1086 height: this.twoPage.height-1 + 'px',
1087 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1088 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1089 position: 'absolute'
1090 }).appendTo('#GBtwopageview');
1092 div = document.createElement('div');
1093 $(div).attr('id', 'GBbookspine').css({
1094 border: '1px solid rgb(68, 25, 17)',
1095 width: this.twoPage.bookSpineDivWidth+'px',
1096 height: this.twoPage.bookSpineDivHeight+'px',
1097 position: 'absolute',
1098 backgroundColor: 'rgb(68, 25, 17)',
1099 left: this.twoPage.bookSpineDivLeft+'px',
1100 top: this.twoPage.bookSpineDivTop+'px'
1101 }).appendTo('#GBtwopageview');
1103 var self = this; // for closure
1106 this.twoPage.leftFlipArea = document.createElement('div');
1107 this.twoPage.leftFlipArea.className = 'GBfliparea';
1108 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1110 width: this.twoPageFlipAreaWidth() + 'px',
1111 height: this.twoPageFlipAreaHeight() + 'px',
1112 position: 'absolute',
1113 left: this.twoPageLeftFlipAreaLeft() + 'px',
1114 top: this.twoPageFlipAreaTop() + 'px',
1117 }).bind('click', function(e) {
1119 }).bind('mousedown', function(e) {
1121 }).appendTo('#GBtwopageview');
1123 this.twoPage.rightFlipArea = document.createElement('div');
1124 this.twoPage.rightFlipArea.className = 'GBfliparea';
1125 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1127 width: this.twoPageFlipAreaWidth() + 'px',
1128 height: this.twoPageFlipAreaHeight() + 'px',
1129 position: 'absolute',
1130 left: this.twoPageRightFlipAreaLeft() + 'px',
1131 top: this.twoPageFlipAreaTop() + 'px',
1134 }).bind('click', function(e) {
1136 }).bind('mousedown', function(e) {
1138 }).appendTo('#GBtwopageview');
1141 this.prepareTwoPagePopUp();
1143 this.displayedIndices = [];
1145 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1146 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1148 this.drawLeafsTwoPage();
1149 this.updateSearchHilites2UP();
1150 this.updateToolbarZoom(this.reduce);
1155 // prepareTwoPagePopUp()
1157 // This function prepares the "View Page n" popup that shows while the mouse is
1158 // over the left/right "stack of sheets" edges. It also binds the mouse
1159 // events for these divs.
1160 //______________________________________________________________________________
1161 GnuBook.prototype.prepareTwoPagePopUp = function() {
1163 this.twoPagePopUp = document.createElement('div');
1164 $(this.twoPagePopUp).css({
1165 border: '1px solid black',
1167 position: 'absolute',
1168 fontFamily: 'sans-serif',
1171 backgroundColor: 'rgb(255, 255, 238)',
1173 }).appendTo('#GBcontainer');
1174 $(this.twoPagePopUp).hide();
1176 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1177 $(e.data.twoPagePopUp).show();
1180 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1181 $(e.data.twoPagePopUp).hide();
1184 $(this.leafEdgeL).bind('click', this, function(e) {
1186 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1187 e.data.jumpToIndex(jumpIndex);
1190 $(this.leafEdgeR).bind('click', this, function(e) {
1192 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1193 e.data.jumpToIndex(jumpIndex);
1196 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1198 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1199 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1201 // $$$ TODO: Make sure popup is positioned so that it is in view
1202 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1203 $(e.data.twoPagePopUp).css({
1204 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1205 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1209 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1211 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1212 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1214 // $$$ TODO: Make sure popup is positioned so that it is in view
1215 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1216 $(e.data.twoPagePopUp).css({
1217 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1218 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1223 // calculateSpreadSize()
1224 //______________________________________________________________________________
1225 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1226 // this.twoPage.currentIndexR
1227 // This function sets this.twoPage.height, twoPage.width
1229 GnuBook.prototype.calculateSpreadSize = function() {
1231 var firstIndex = this.twoPage.currentIndexL;
1232 var secondIndex = this.twoPage.currentIndexR;
1233 //console.log('first page is ' + firstIndex);
1235 // Calculate page sizes and total leaf width
1237 if ( this.twoPage.autofit) {
1238 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1240 // set based on reduction factor
1241 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1244 // Both pages together
1245 this.twoPage.height = spreadSize.height;
1246 this.twoPage.width = spreadSize.width;
1249 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1250 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1253 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1254 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1255 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1259 // The width of the book cover div. The combined width of both pages, twice the width
1260 // of the book cover internal padding (2*10) and the page edges
1261 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1262 // The height of the book cover div
1263 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1266 // We calculate the total width and height for the div so that we can make the book
1268 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1269 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1270 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1271 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1272 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1273 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1275 // We want to minimize the unused space in two-up mode (maximize the amount of page
1276 // shown). We give width to the leaf edges and these widths change (though the sum
1277 // of the two remains constant) as we flip through the book. With the book
1278 // cover centered and fixed in the GBcontainer div the page images will meet
1279 // at the "gutter" which is generally offset from the center.
1280 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1281 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1283 // The left edge of the book cover moves depending on the width of the pages
1284 // $$$ change to getter
1285 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1286 // The top edge of the book cover stays a fixed distance from the top
1287 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1290 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1291 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1292 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1295 this.reduce = spreadSize.reduce; // $$$ really set this here?
1298 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1301 // We check which page is closest to a "normal" page and use that to set the height
1302 // for both pages. This means that foldouts and other odd size pages will be displayed
1303 // smaller than the nominal zoom amount.
1304 var canon5Dratio = 1.5;
1307 height: this.getPageHeight(firstIndex),
1308 width: this.getPageWidth(firstIndex)
1312 height: this.getPageHeight(secondIndex),
1313 width: this.getPageWidth(secondIndex)
1316 var firstIndexRatio = first.height / first.width;
1317 var secondIndexRatio = second.height / second.width;
1318 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1321 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1322 ratio = firstIndexRatio;
1323 //console.log('using firstIndexRatio ' + ratio);
1325 ratio = secondIndexRatio;
1326 //console.log('using secondIndexRatio ' + ratio);
1329 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1330 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1331 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1333 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1334 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1336 ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1337 ideal.width -= 10; // $$$ fudge factor
1338 ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1339 ideal.height -= 20; // fudge factor
1340 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1342 if (ideal.height/ratio <= ideal.width) {
1344 ideal.width = parseInt(ideal.height/ratio);
1347 ideal.height = parseInt(ideal.width*ratio);
1350 // $$$ check this logic with large spreads
1351 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1356 // getSpreadSizeFromReduce()
1357 //______________________________________________________________________________
1358 // Returns the spread size calculated from the reduction factor for the given pages
1359 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1360 var spreadSize = {};
1361 // $$$ Scale this based on reduce?
1362 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1363 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1364 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1366 // $$$ Possibly incorrect -- we should make height "dominant"
1367 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1368 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1369 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1370 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1371 spreadSize.reduce = reduce;
1376 // twoPageGetAutofitReduce()
1377 //______________________________________________________________________________
1378 // Returns the current ideal reduction factor
1379 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1380 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1381 return spreadSize.reduce;
1384 // twoPageSetCursor()
1385 //______________________________________________________________________________
1386 // Set the cursor for two page view
1387 GnuBook.prototype.twoPageSetCursor = function() {
1388 // console.log('setting cursor');
1389 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1390 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1391 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1392 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1394 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1395 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1400 //______________________________________________________________________________
1401 // Returns the currently active index.
1402 GnuBook.prototype.currentIndex = function() {
1403 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1404 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1405 return this.firstIndex;
1407 throw 'currentIndex called for unimplemented mode ' + this.mode;
1412 //______________________________________________________________________________
1413 // Flip the right page over onto the left
1414 GnuBook.prototype.right = function() {
1415 if ('rl' != this.pageProgression) {
1425 //______________________________________________________________________________
1426 // Flip to the rightmost page
1427 GnuBook.prototype.rightmost = function() {
1428 if ('rl' != this.pageProgression) {
1436 //______________________________________________________________________________
1437 // Flip the left page over onto the right.
1438 GnuBook.prototype.left = function() {
1439 if ('rl' != this.pageProgression) {
1449 //______________________________________________________________________________
1450 // Flip to the leftmost page
1451 GnuBook.prototype.leftmost = function() {
1452 if ('rl' != this.pageProgression) {
1460 //______________________________________________________________________________
1461 GnuBook.prototype.next = function() {
1462 if (2 == this.mode) {
1464 this.flipFwdToIndex(null);
1466 if (this.firstIndex < this.lastDisplayableIndex()) {
1467 this.jumpToIndex(this.firstIndex+1);
1473 //______________________________________________________________________________
1474 GnuBook.prototype.prev = function() {
1475 if (2 == this.mode) {
1477 this.flipBackToIndex(null);
1479 if (this.firstIndex >= 1) {
1480 this.jumpToIndex(this.firstIndex-1);
1485 GnuBook.prototype.first = function() {
1486 if (2 == this.mode) {
1487 this.jumpToIndex(2);
1490 this.jumpToIndex(0);
1494 GnuBook.prototype.last = function() {
1495 if (2 == this.mode) {
1496 this.jumpToIndex(this.lastDisplayableIndex());
1499 this.jumpToIndex(this.lastDisplayableIndex());
1503 // flipBackToIndex()
1504 //______________________________________________________________________________
1505 // to flip back one spread, pass index=null
1506 GnuBook.prototype.flipBackToIndex = function(index) {
1507 if (1 == this.mode) return;
1509 var leftIndex = this.twoPage.currentIndexL;
1511 // $$$ Need to change this to be able to see first spread.
1512 // See https://bugs.launchpad.net/gnubook/+bug/296788
1513 if (leftIndex <= 2) return;
1514 if (this.animating) return;
1516 if (null != this.leafEdgeTmp) {
1517 alert('error: leafEdgeTmp should be null!');
1521 if (null == index) {
1522 index = leftIndex-2;
1524 //if (index<0) return;
1526 var previousIndices = this.getSpreadIndices(index);
1528 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1532 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1534 this.animating = true;
1536 if ('rl' != this.pageProgression) {
1537 // Assume LTR and we are going backward
1538 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1539 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1541 // RTL and going backward
1542 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1543 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1547 // flipLeftToRight()
1548 //______________________________________________________________________________
1549 // Flips the page on the left towards the page on the right
1550 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1552 var leftLeaf = this.twoPage.currentIndexL;
1554 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1555 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1556 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1558 var currWidthL = this.getPageWidth2UP(leftLeaf);
1559 var newWidthL = this.getPageWidth2UP(newIndexL);
1560 var newWidthR = this.getPageWidth2UP(newIndexR);
1562 var top = this.twoPageTop();
1563 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1565 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1566 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1568 //animation strategy:
1569 // 0. remove search highlight, if any.
1570 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1571 // of the left leaf and where the user clicked in the leaf edge.
1572 // Note that if this function was triggered by left() and not a
1573 // mouse click, the width of leafEdgeTmp is very small (zero px).
1574 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1575 // leftLeaf to width=0.
1576 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1577 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1578 // its new full width.
1579 // 4. After step 3 is finished, do the following:
1580 // - remove leafEdgeTmp from the dom.
1581 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1582 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1583 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1584 // and width=newLeafEdgeWidthL.
1585 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1586 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1587 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1588 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1589 // - prefetch new adjacent leafs.
1590 // - set up click handlers for both new left and right leafs.
1591 // - redraw the search highlight.
1592 // - update the pagenum box and the url.
1595 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1597 this.leafEdgeTmp = document.createElement('div');
1598 $(this.leafEdgeTmp).css({
1599 borderStyle: 'solid none solid solid',
1600 borderColor: 'rgb(51, 51, 34)',
1601 borderWidth: '1px 0px 1px 1px',
1602 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1603 width: leafEdgeTmpW + 'px',
1604 height: this.twoPage.height-1 + 'px',
1605 left: leftEdgeTmpLeft + 'px',
1607 position: 'absolute',
1609 }).appendTo('#GBtwopageview');
1611 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1612 $(this.leafEdgeL).css({
1613 width: newLeafEdgeWidthL+'px',
1614 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1617 // Left gets the offset of the current left leaf from the document
1618 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1619 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1620 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1622 // We change the left leaf to right positioning
1623 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1624 $(this.prefetchedImgs[leftLeaf]).css({
1629 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1630 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1634 this.removeSearchHilites();
1636 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1637 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1639 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1640 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1642 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1643 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1644 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1646 $(self.leafEdgeR).css({
1647 // Moves the right leaf edge
1648 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1649 left: gutter+newWidthR+'px'
1652 $(self.leafEdgeL).css({
1653 // Moves and resizes the left leaf edge
1654 width: newLeafEdgeWidthL+'px',
1655 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1658 // Resizes the brown border div
1659 $(self.twoPage.coverDiv).css({
1660 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1661 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1664 $(self.leafEdgeTmp).remove();
1665 self.leafEdgeTmp = null;
1667 // $$$ TODO refactor with opposite direction flip
1669 self.twoPage.currentIndexL = newIndexL;
1670 self.twoPage.currentIndexR = newIndexR;
1671 self.twoPage.scaledWL = newWidthL;
1672 self.twoPage.scaledWR = newWidthR;
1673 self.twoPage.gutter = gutter;
1675 self.firstIndex = self.twoPage.currentIndexL;
1676 self.displayedIndices = [newIndexL, newIndexR];
1677 self.pruneUnusedImgs();
1679 self.animating = false;
1681 self.updateSearchHilites2UP();
1682 self.updatePageNumBox2UP();
1684 self.twoPagePlaceFlipAreas();
1685 self.setClickHandlers();
1686 self.twoPageSetCursor();
1688 if (self.animationFinishedCallback) {
1689 self.animationFinishedCallback();
1690 self.animationFinishedCallback = null;
1698 //______________________________________________________________________________
1699 // Whether we flip left or right is dependent on the page progression
1700 // to flip forward one spread, pass index=null
1701 GnuBook.prototype.flipFwdToIndex = function(index) {
1703 if (this.animating) return;
1705 if (null != this.leafEdgeTmp) {
1706 alert('error: leafEdgeTmp should be null!');
1710 if (null == index) {
1711 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1713 if (index > this.lastDisplayableIndex()) return;
1715 this.animating = true;
1717 var nextIndices = this.getSpreadIndices(index);
1719 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1721 if ('rl' != this.pageProgression) {
1722 // We did not specify RTL
1723 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1724 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1727 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1728 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1732 // flipRightToLeft(nextL, nextR, gutter)
1733 // $$$ better not to have to pass gutter in
1734 //______________________________________________________________________________
1735 // Flip from left to right and show the nextL and nextR indices on those sides
1736 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1737 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1738 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1739 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1740 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1742 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1744 var top = this.twoPageTop();
1745 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1747 var middle = this.twoPage.middle;
1748 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1750 this.leafEdgeTmp = document.createElement('div');
1751 $(this.leafEdgeTmp).css({
1752 borderStyle: 'solid none solid solid',
1753 borderColor: 'rgb(51, 51, 34)',
1754 borderWidth: '1px 0px 1px 1px',
1755 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1756 width: leafEdgeTmpW + 'px',
1757 height: this.twoPage.height-1 + 'px',
1758 left: gutter+scaledW+'px',
1760 position: 'absolute',
1762 }).appendTo('#GBtwopageview');
1764 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1765 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1767 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1768 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1769 var newWidthL = this.getPageWidth2UP(newIndexL);
1770 var newWidthR = this.getPageWidth2UP(newIndexR);
1772 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1774 var self = this; // closure-tastic!
1776 var speed = this.flipSpeed;
1778 this.removeSearchHilites();
1780 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1781 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1782 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1783 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1784 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1786 $(self.leafEdgeL).css({
1787 width: newLeafEdgeWidthL+'px',
1788 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1791 // Resizes the book cover
1792 $(self.twoPage.coverDiv).css({
1793 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1794 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1797 $(self.leafEdgeTmp).remove();
1798 self.leafEdgeTmp = null;
1800 self.twoPage.currentIndexL = newIndexL;
1801 self.twoPage.currentIndexR = newIndexR;
1802 self.twoPage.scaledWL = newWidthL;
1803 self.twoPage.scaledWR = newWidthR;
1804 self.twoPage.gutter = gutter;
1806 self.firstIndex = self.twoPage.currentIndexL;
1807 self.displayedIndices = [newIndexL, newIndexR];
1808 self.pruneUnusedImgs();
1810 self.animating = false;
1813 self.updateSearchHilites2UP();
1814 self.updatePageNumBox2UP();
1816 self.twoPagePlaceFlipAreas();
1817 self.setClickHandlers();
1818 self.twoPageSetCursor();
1820 if (self.animationFinishedCallback) {
1821 self.animationFinishedCallback();
1822 self.animationFinishedCallback = null;
1829 //______________________________________________________________________________
1830 GnuBook.prototype.setClickHandlers = function() {
1832 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1837 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1844 this.setDragHandler2up( this.prefetchedImgs[this.twoPage.currentIndexL] );
1845 this.setClickHandler2up( this.prefetchedImgs[this.twoPage.currentIndexL],
1852 this.setDragHandler2up( this.prefetchedImgs[this.twoPage.currentIndexR] );
1853 this.setClickHandler2up( this.prefetchedImgs[this.twoPage.currentIndexR],
1856 e.data.self.right();
1862 //______________________________________________________________________________
1863 GnuBook.prototype.prefetchImg = function(index) {
1864 var pageURI = this.getPageURI(index);
1866 // Load image if not loaded or URI has changed (e.g. due to scaling)
1867 var loadImage = false;
1868 if (undefined == this.prefetchedImgs[index]) {
1869 //console.log('no image for ' + index);
1871 } else if (pageURI != this.prefetchedImgs[index].uri) {
1872 //console.log('uri changed for ' + index);
1877 //console.log('prefetching ' + index);
1878 var img = document.createElement("img");
1880 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1881 this.prefetchedImgs[index] = img;
1886 // prepareFlipLeftToRight()
1888 //______________________________________________________________________________
1890 // Prepare to flip the left page towards the right. This corresponds to moving
1891 // backward when the page progression is left to right.
1892 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1894 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1896 this.prefetchImg(prevL);
1897 this.prefetchImg(prevR);
1899 var height = this.getPageHeight(prevL);
1900 var width = this.getPageWidth(prevL);
1901 var middle = this.twoPage.middle;
1902 var top = this.twoPageTop();
1903 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1905 // The gutter is the dividing line between the left and right pages.
1906 // It is offset from the middle to create the illusion of thickness to the pages
1907 var gutter = middle + this.gutterOffsetForIndex(prevL);
1909 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1910 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1911 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1913 $(this.prefetchedImgs[prevL]).css({
1914 position: 'absolute',
1915 left: gutter-scaledW+'px',
1916 right: '', // clear right property
1918 backgroundColor: 'rgb(234, 226, 205)',
1919 height: this.twoPage.height,
1920 width: scaledW+'px',
1921 borderRight: '1px solid black',
1925 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1927 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1929 $(this.prefetchedImgs[prevR]).css({
1930 position: 'absolute',
1934 backgroundColor: 'rgb(234, 226, 205)',
1935 height: this.twoPage.height,
1937 borderLeft: '1px solid black',
1941 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1945 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1946 // prepareFlipRightToLeft()
1947 //______________________________________________________________________________
1948 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1950 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1953 this.prefetchImg(nextL);
1954 this.prefetchImg(nextR);
1956 var height = this.getPageHeight(nextR);
1957 var width = this.getPageWidth(nextR);
1958 var middle = this.twoPage.middle;
1959 var top = this.twoPageTop();
1960 var scaledW = this.twoPage.height*width/height;
1962 var gutter = middle + this.gutterOffsetForIndex(nextL);
1964 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1965 $(this.prefetchedImgs[nextR]).css({
1966 position: 'absolute',
1969 backgroundColor: 'rgb(234, 226, 205)',
1970 height: this.twoPage.height,
1971 width: scaledW+'px',
1972 borderLeft: '1px solid black',
1976 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1978 height = this.getPageHeight(nextL);
1979 width = this.getPageWidth(nextL);
1980 scaledW = this.twoPage.height*width/height;
1982 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1983 $(this.prefetchedImgs[nextL]).css({
1984 position: 'absolute',
1985 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1987 backgroundColor: 'rgb(234, 226, 205)',
1988 height: this.twoPage.height,
1989 width: 0+'px', // Start at 0 width, then grow to the left
1990 borderRight: '1px solid black',
1994 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1998 // getNextLeafs() -- NOT RTL AWARE
1999 //______________________________________________________________________________
2000 // GnuBook.prototype.getNextLeafs = function(o) {
2001 // //TODO: we might have two left or two right leafs in a row (damaged book)
2002 // //For now, assume that leafs are contiguous.
2004 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2005 // o.L = this.twoPage.currentIndexL+2;
2006 // o.R = this.twoPage.currentIndexL+3;
2009 // getprevLeafs() -- NOT RTL AWARE
2010 //______________________________________________________________________________
2011 // GnuBook.prototype.getPrevLeafs = function(o) {
2012 // //TODO: we might have two left or two right leafs in a row (damaged book)
2013 // //For now, assume that leafs are contiguous.
2015 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2016 // o.L = this.twoPage.currentIndexL-2;
2017 // o.R = this.twoPage.currentIndexL-1;
2020 // pruneUnusedImgs()
2021 //______________________________________________________________________________
2022 GnuBook.prototype.pruneUnusedImgs = function() {
2023 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2024 for (var key in this.prefetchedImgs) {
2025 //console.log('key is ' + key);
2026 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2027 //console.log('removing key '+ key);
2028 $(this.prefetchedImgs[key]).remove();
2030 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2031 //console.log('deleting key '+ key);
2032 delete this.prefetchedImgs[key];
2038 //______________________________________________________________________________
2039 GnuBook.prototype.prefetch = function() {
2041 // prefetch visible pages first
2042 this.prefetchImg(this.twoPage.currentIndexL);
2043 this.prefetchImg(this.twoPage.currentIndexR);
2045 var adjacentPagesToLoad = 3;
2047 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2048 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2050 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2051 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2053 // Load images spreading out from current
2054 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2055 var goingDown = lowCurrent - i;
2056 if (goingDown >= start) {
2057 this.prefetchImg(goingDown);
2059 var goingUp = highCurrent + i;
2060 if (goingUp <= end) {
2061 this.prefetchImg(goingUp);
2066 var lim = this.twoPage.currentIndexL-4;
2068 lim = Math.max(lim, 0);
2069 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2070 this.prefetchImg(i);
2073 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2074 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2075 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2076 this.prefetchImg(i);
2082 // getPageWidth2UP()
2083 //______________________________________________________________________________
2084 GnuBook.prototype.getPageWidth2UP = function(index) {
2085 // We return the width based on the dominant height
2086 var height = this.getPageHeight(index);
2087 var width = this.getPageWidth(index);
2088 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2092 //______________________________________________________________________________
2093 GnuBook.prototype.search = function(term) {
2094 $('#GnuBookSearchScript').remove();
2095 var script = document.createElement("script");
2096 script.setAttribute('id', 'GnuBookSearchScript');
2097 script.setAttribute("type", "text/javascript");
2098 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2099 document.getElementsByTagName('head')[0].appendChild(script);
2100 $('#GnuBookSearchResults').html('Searching...');
2103 // GBSearchCallback()
2104 //______________________________________________________________________________
2105 GnuBook.prototype.GBSearchCallback = function(txt) {
2107 if (jQuery.browser.msie) {
2108 var dom=new ActiveXObject("Microsoft.XMLDOM");
2112 var parser = new DOMParser();
2113 var dom = parser.parseFromString(txt, "text/xml");
2116 $('#GnuBookSearchResults').empty();
2117 $('#GnuBookSearchResults').append('<ul>');
2119 for (var key in this.searchResults) {
2120 if (null != this.searchResults[key].div) {
2121 $(this.searchResults[key].div).remove();
2123 delete this.searchResults[key];
2126 var pages = dom.getElementsByTagName('PAGE');
2128 if (0 == pages.length) {
2129 // $$$ it would be nice to echo the (sanitized) search result here
2130 $('#GnuBookSearchResults').append('<li>No search results found</li>');
2132 for (var i = 0; i < pages.length; i++){
2133 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2136 var re = new RegExp (/_(\d{4})/);
2137 var reMatch = re.exec(pages[i].getAttribute('file'));
2138 var index = parseInt(reMatch[1], 10);
2139 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2141 var children = pages[i].childNodes;
2143 for (var j=0; j<children.length; j++) {
2144 //console.log(j + ' - ' + children[j].nodeName);
2145 //console.log(children[j].firstChild.nodeValue);
2146 if ('CONTEXT' == children[j].nodeName) {
2147 context += children[j].firstChild.nodeValue;
2148 } else if ('WORD' == children[j].nodeName) {
2149 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2151 var index = this.leafNumToIndex(index);
2152 if (null != index) {
2153 //coordinates are [left, bottom, right, top, [baseline]]
2154 //we'll skip baseline for now...
2155 var coords = children[j].getAttribute('coords').split(',',4);
2156 if (4 == coords.length) {
2157 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
2162 var pageName = this.getPageName(index);
2163 //TODO: remove hardcoded instance name
2164 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
2167 $('#GnuBookSearchResults').append('</ul>');
2169 this.updateSearchHilites();
2172 // updateSearchHilites()
2173 //______________________________________________________________________________
2174 GnuBook.prototype.updateSearchHilites = function() {
2175 if (2 == this.mode) {
2176 this.updateSearchHilites2UP();
2178 this.updateSearchHilites1UP();
2182 // showSearchHilites1UP()
2183 //______________________________________________________________________________
2184 GnuBook.prototype.updateSearchHilites1UP = function() {
2186 for (var key in this.searchResults) {
2188 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2189 var result = this.searchResults[key];
2190 if(null == result.div) {
2191 result.div = document.createElement('div');
2192 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2193 //console.log('appending ' + key);
2196 width: (result.r-result.l)/this.reduce + 'px',
2197 height: (result.b-result.t)/this.reduce + 'px',
2198 left: (result.l)/this.reduce + 'px',
2199 top: (result.t)/this.reduce +'px'
2203 //console.log(key + ' not displayed');
2204 this.searchResults[key].div=null;
2210 //______________________________________________________________________________
2211 // Returns the position of the gutter (line between the page images)
2212 GnuBook.prototype.twoPageGutter = function() {
2213 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2217 //______________________________________________________________________________
2218 // Returns the offset for the top of the page images
2219 GnuBook.prototype.twoPageTop = function() {
2220 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2223 // twoPageCoverWidth()
2224 //______________________________________________________________________________
2225 // Returns the width of the cover div given the total page width
2226 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2227 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2230 // twoPageGetViewCenter()
2231 //______________________________________________________________________________
2232 // Returns the percentage offset into twopageview div at the center of container div
2233 // { percentageX: float, percentageY: float }
2234 GnuBook.prototype.twoPageGetViewCenter = function() {
2237 var containerOffset = $('#GBcontainer').offset();
2238 var viewOffset = $('#GBtwopageview').offset();
2239 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2240 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2245 // twoPageCenterView(percentageX, percentageY)
2246 //______________________________________________________________________________
2247 // Centers the point given by percentage from left,top of twopageview
2248 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2249 if ('undefined' == typeof(percentageX)) {
2252 if ('undefined' == typeof(percentageY)) {
2256 var viewWidth = $('#GBtwopageview').width();
2257 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2258 var intoViewX = percentageX * viewWidth;
2260 var viewHeight = $('#GBtwopageview').height();
2261 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2262 var intoViewY = percentageY * viewHeight;
2264 if (viewWidth < containerClientWidth) {
2265 // Can fit width without scrollbars - center by adjusting offset
2266 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2268 // Need to scroll to center
2269 $('#GBtwopageview').css('left', 0);
2270 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2273 if (viewHeight < containerClientHeight) {
2274 // Fits with scrollbars - add offset
2275 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2277 $('#GBtwopageview').css('top', 0);
2278 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2282 // twoPageFlipAreaHeight
2283 //______________________________________________________________________________
2284 // Returns the integer height of the click-to-flip areas at the edges of the book
2285 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2286 return parseInt(this.twoPage.height);
2289 // twoPageFlipAreaWidth
2290 //______________________________________________________________________________
2291 // Returns the integer width of the flip areas
2292 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2293 var max = 100; // $$$ TODO base on view width?
2296 var width = this.twoPage.width * 0.15;
2297 return parseInt(GnuBook.util.clamp(width, min, max));
2300 // twoPageFlipAreaTop
2301 //______________________________________________________________________________
2302 // Returns integer top offset for flip areas
2303 GnuBook.prototype.twoPageFlipAreaTop = function() {
2304 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2307 // twoPageLeftFlipAreaLeft
2308 //______________________________________________________________________________
2309 // Left offset for left flip area
2310 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2311 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2314 // twoPageRightFlipAreaLeft
2315 //______________________________________________________________________________
2316 // Left offset for right flip area
2317 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2318 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2321 // twoPagePlaceFlipAreas
2322 //______________________________________________________________________________
2323 // Readjusts position of flip areas based on current layout
2324 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2325 // We don't set top since it shouldn't change relative to view
2326 $(this.twoPage.leftFlipArea).css({
2327 left: this.twoPageLeftFlipAreaLeft() + 'px',
2328 width: this.twoPageFlipAreaWidth() + 'px'
2330 $(this.twoPage.rightFlipArea).css({
2331 left: this.twoPageRightFlipAreaLeft() + 'px',
2332 width: this.twoPageFlipAreaWidth() + 'px'
2336 // showSearchHilites2UP()
2337 //______________________________________________________________________________
2338 GnuBook.prototype.updateSearchHilites2UP = function() {
2340 for (var key in this.searchResults) {
2341 key = parseInt(key, 10);
2342 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2343 var result = this.searchResults[key];
2344 if(null == result.div) {
2345 result.div = document.createElement('div');
2346 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2347 //console.log('appending ' + key);
2350 // We calculate the reduction factor for the specific page because it can be different
2351 // for each page in the spread
2352 var height = this.getPageHeight(key);
2353 var width = this.getPageWidth(key)
2354 var reduce = this.twoPage.height/height;
2355 var scaledW = parseInt(width*reduce);
2357 var gutter = this.twoPageGutter();
2359 if ('L' == this.getPageSide(key)) {
2360 pageL = gutter-scaledW;
2364 var pageT = this.twoPageTop();
2367 width: (result.r-result.l)*reduce + 'px',
2368 height: (result.b-result.t)*reduce + 'px',
2369 left: pageL+(result.l)*reduce + 'px',
2370 top: pageT+(result.t)*reduce +'px'
2374 //console.log(key + ' not displayed');
2375 if (null != this.searchResults[key].div) {
2376 //console.log('removing ' + key);
2377 $(this.searchResults[key].div).remove();
2379 this.searchResults[key].div=null;
2384 // removeSearchHilites()
2385 //______________________________________________________________________________
2386 GnuBook.prototype.removeSearchHilites = function() {
2387 for (var key in this.searchResults) {
2388 if (null != this.searchResults[key].div) {
2389 $(this.searchResults[key].div).remove();
2390 this.searchResults[key].div=null;
2396 //______________________________________________________________________________
2397 GnuBook.prototype.showEmbedCode = function() {
2398 if (null != this.embedPopup) { // check if already showing
2402 this.embedPopup = document.createElement("div");
2403 $(this.embedPopup).css({
2404 position: 'absolute',
2406 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2409 border: "3px double #999999",
2411 backgroundColor: "#fff"
2412 }).appendTo('#GnuBook');
2414 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2415 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>';
2416 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2417 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2419 this.embedPopup.innerHTML = htmlStr;
2420 $(this.embedPopup).find('input').bind('click', function() {
2426 //______________________________________________________________________________
2427 GnuBook.prototype.autoToggle = function() {
2429 var bComingFrom1up = false;
2430 if (2 != this.mode) {
2431 bComingFrom1up = true;
2435 // Change to autofit if book is too large
2436 if (this.reduce < this.twoPageGetAutofitReduce()) {
2441 if (null == this.autoTimer) {
2442 this.flipSpeed = 2000;
2444 // $$$ Draw events currently cause layout problems when they occur during animation.
2445 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2446 // we workaround for now by not triggering immediate animation in that case.
2447 // See https://bugs.launchpad.net/gnubook/+bug/328327
2448 if (('rl' == this.pageProgression) && bComingFrom1up) {
2449 // don't flip immediately -- wait until timer fires
2452 this.flipFwdToIndex();
2455 $('#GBtoolbar .play').hide();
2456 $('#GBtoolbar .pause').show();
2457 this.autoTimer=setInterval(function(){
2458 if (self.animating) {return;}
2460 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2461 self.flipBackToIndex(1); // $$$ really what we want?
2463 self.flipFwdToIndex();
2472 //______________________________________________________________________________
2473 // Stop autoplay mode, allowing animations to finish
2474 GnuBook.prototype.autoStop = function() {
2475 if (null != this.autoTimer) {
2476 clearInterval(this.autoTimer);
2477 this.flipSpeed = 'fast';
2478 $('#GBtoolbar .pause').hide();
2479 $('#GBtoolbar .play').show();
2480 this.autoTimer = null;
2484 // stopFlipAnimations
2485 //______________________________________________________________________________
2486 // Immediately stop flip animations. Callbacks are triggered.
2487 GnuBook.prototype.stopFlipAnimations = function() {
2489 this.autoStop(); // Clear timers
2491 // Stop animation, clear queue, trigger callbacks
2492 if (this.leafEdgeTmp) {
2493 $(this.leafEdgeTmp).stop(false, true);
2495 jQuery.each(this.prefetchedImgs, function() {
2496 $(this).stop(false, true);
2499 // And again since animations also queued in callbacks
2500 if (this.leafEdgeTmp) {
2501 $(this.leafEdgeTmp).stop(false, true);
2503 jQuery.each(this.prefetchedImgs, function() {
2504 $(this).stop(false, true);
2509 // keyboardNavigationIsDisabled(event)
2510 // - returns true if keyboard navigation should be disabled for the event
2511 //______________________________________________________________________________
2512 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2513 if (event.target.tagName == "INPUT") {
2519 // gutterOffsetForIndex
2520 //______________________________________________________________________________
2522 // Returns the gutter offset for the spread containing the given index.
2523 // This function supports RTL
2524 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2526 // To find the offset of the gutter from the middle we calculate our percentage distance
2527 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2528 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2530 // But then again for RTL it's the opposite
2531 if ('rl' == this.pageProgression) {
2539 //______________________________________________________________________________
2540 // Returns the width of the leaf edge div for the page with index given
2541 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2542 // $$$ could there be single pixel rounding errors for L vs R?
2543 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2544 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2546 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2550 // jumpIndexForLeftEdgePageX
2551 //______________________________________________________________________________
2552 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2553 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2554 if ('rl' != this.pageProgression) {
2555 // LTR - flipping backward
2556 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2558 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2559 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2563 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2564 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2569 // jumpIndexForRightEdgePageX
2570 //______________________________________________________________________________
2571 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2572 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2573 if ('rl' != this.pageProgression) {
2575 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2576 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2579 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2580 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2585 GnuBook.prototype.initToolbar = function(mode, ui) {
2587 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2588 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2589 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2590 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2591 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2592 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2593 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2594 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2597 this.updateToolbarZoom(this.reduce); // Pretty format
2599 if (ui == "embed") {
2600 $("#GnuBook a.logo").attr("target","_blank");
2603 // $$$ turn this into a member variable
2604 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2606 // We build in mode 2
2607 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2608 + "<button class='GBicon rollover embed' />"
2609 + "<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>"
2610 + "<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>"
2611 + "<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>"
2612 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2614 this.bindToolbarNavHandlers(jToolbar);
2616 // Setup tooltips -- later we could load these from a file for i18n
2617 var titles = { '.logo': 'Go to Archive.org',
2618 '.zoom_in': 'Zoom in',
2619 '.zoom_out': 'Zoom out',
2620 '.one_page_mode': 'One-page view',
2621 '.two_page_mode': 'Two-page view',
2622 '.embed': 'Embed bookreader',
2623 '.book_left': 'Flip left',
2624 '.book_right': 'Flip right',
2625 '.book_up': 'Page up',
2626 '.book_down': 'Page down',
2629 '.book_top': 'First page',
2630 '.book_bottom': 'Last page'
2632 if ('rl' == this.pageProgression) {
2633 titles['.book_leftmost'] = 'Last page';
2634 titles['.book_rightmost'] = 'First page';
2636 titles['.book_leftmost'] = 'First page';
2637 titles['.book_rightmost'] = 'Last page';
2640 for (var icon in titles) {
2641 jToolbar.find(icon).attr('title', titles[icon]);
2644 // Hide mode buttons and autoplay if 2up is not available
2645 // $$$ if we end up with more than two modes we should show the applicable buttons
2646 if ( !this.canSwitchToMode(this.constMode2up) ) {
2647 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2650 // Switch to requested mode -- binds other click handlers
2651 this.switchToolbarMode(mode);
2656 // switchToolbarMode
2657 //______________________________________________________________________________
2658 // Update the toolbar for the given mode (changes navigation buttons)
2659 // $$$ we should soon split the toolbar out into its own module
2660 GnuBook.prototype.switchToolbarMode = function(mode) {
2663 $('#GBtoolbar .GBtoolbarmode2').hide();
2664 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2667 $('#GBtoolbar .GBtoolbarmode1').hide();
2668 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2672 // bindToolbarNavHandlers
2673 //______________________________________________________________________________
2674 // Binds the toolbar handlers
2675 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2677 jToolbar.find('.book_left').bind('click', function(e) {
2682 jToolbar.find('.book_right').bind('click', function(e) {
2687 jToolbar.find('.book_up').bind('click', function(e) {
2692 jToolbar.find('.book_down').bind('click', function(e) {
2697 jToolbar.find('.embed').bind('click', function(e) {
2702 jToolbar.find('.play').bind('click', function(e) {
2707 jToolbar.find('.pause').bind('click', function(e) {
2712 jToolbar.find('.book_top').bind('click', function(e) {
2717 jToolbar.find('.book_bottom').bind('click', function(e) {
2722 jToolbar.find('.book_leftmost').bind('click', function(e) {
2727 jToolbar.find('.book_rightmost').bind('click', function(e) {
2733 // updateToolbarZoom(reduce)
2734 //______________________________________________________________________________
2735 // Update the displayed zoom factor based on reduction factor
2736 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2738 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2741 value = (100 / reduce).toFixed(2);
2742 // Strip trailing zeroes and decimal if all zeroes
2743 value = value.replace(/0+$/,'');
2744 value = value.replace(/\.$/,'');
2747 $('#GBzoom').text(value);
2750 // firstDisplayableIndex
2751 //______________________________________________________________________________
2752 // Returns the index of the first visible page, dependent on the mode.
2753 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2754 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2755 GnuBook.prototype.firstDisplayableIndex = function() {
2756 if (this.mode == 0) {
2759 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2763 // lastDisplayableIndex
2764 //______________________________________________________________________________
2765 // Returns the index of the last visible page, dependent on the mode.
2766 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2767 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2768 GnuBook.prototype.lastDisplayableIndex = function() {
2769 if (this.mode == 2) {
2770 if (this.lastDisplayableIndex2up === null) {
2771 // Calculate and cache
2772 var candidate = this.numLeafs - 1;
2773 for ( ; candidate >= 0; candidate--) {
2774 var spreadIndices = this.getSpreadIndices(candidate);
2775 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2779 this.lastDisplayableIndex2up = candidate;
2781 return this.lastDisplayableIndex2up;
2783 return this.numLeafs - 1;
2787 // shortTitle(maximumCharacters)
2789 // Returns a shortened version of the title with the maximum number of characters
2790 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2791 if (this.bookTitle.length < maximumCharacters) {
2792 return this.bookTitle;
2795 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2802 // Parameter related functions
2804 // updateFromParams(params)
2806 // Update ourselves from the params object.
2808 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2809 GnuBook.prototype.updateFromParams = function(params) {
2810 if ('undefined' != typeof(params.mode)) {
2811 this.switchMode(params.mode);
2814 // $$$ process /search
2815 // $$$ process /zoom
2817 // We only respect page if index is not set
2818 if ('undefined' != typeof(params.index)) {
2819 if (params.index != this.currentIndex()) {
2820 this.jumpToIndex(params.index);
2822 } else if ('undefined' != typeof(params.page)) {
2823 // $$$ this assumes page numbers are unique
2824 if (params.page != this.getPageNum(this.currentIndex())) {
2825 this.jumpToPage(params.page);
2829 // $$$ process /region
2830 // $$$ process /highlight
2833 // paramsFromFragment(urlFragment)
2835 // Returns a object with configuration parametes from a URL fragment.
2837 // E.g paramsFromFragment(window.location.hash)
2838 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2839 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2843 // For convenience we allow an initial # character (as from window.location.hash)
2844 // but don't require it
2845 if (urlFragment.substr(0,1) == '#') {
2846 urlFragment = urlFragment.substr(1);
2849 // Simple #nn syntax
2850 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2851 if ( !isNaN(oldStyleLeafNum) ) {
2852 params.index = oldStyleLeafNum;
2854 // Done processing if using old-style syntax
2858 // Split into key-value pairs
2859 var urlArray = urlFragment.split('/');
2861 for (var i = 0; i < urlArray.length; i += 2) {
2862 urlHash[urlArray[i]] = urlArray[i+1];
2866 if ('1up' == urlHash['mode']) {
2867 params.mode = this.constMode1up;
2868 } else if ('2up' == urlHash['mode']) {
2869 params.mode = this.constMode2up;
2873 if ('undefined' != typeof(urlHash['page'])) {
2874 // page was set -- may not be int
2875 params.page = urlHash['page'];
2878 // $$$ process /region
2879 // $$$ process /search
2880 // $$$ process /highlight
2885 // paramsFromCurrent()
2887 // Create a params object from the current parameters.
2888 GnuBook.prototype.paramsFromCurrent = function() {
2892 var pageNum = this.getPageNum(this.currentIndex());
2893 if ((pageNum === 0) || pageNum) {
2894 params.page = pageNum;
2897 params.index = this.currentIndex();
2898 params.mode = this.mode;
2907 // fragmentFromParams(params)
2909 // Create a fragment string from the params object.
2910 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2911 GnuBook.prototype.fragmentFromParams = function(params) {
2912 var separator = '/';
2916 if ('undefined' != typeof(params.page)) {
2917 fragments.push('page', params.page);
2919 // Don't have page numbering -- use index instead
2920 fragments.push('page', 'n' + params.index);
2928 if ('undefined' != typeof(params.mode)) {
2929 if (params.mode == this.constMode1up) {
2930 fragments.push('mode', '1up');
2931 } else if (params.mode == this.constMode2up) {
2932 fragments.push('mode', '2up');
2934 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2938 return fragments.join(separator);
2941 // getPageIndex(pageNum)
2943 // Returns the *highest* index the given page number, or undefined
2944 GnuBook.prototype.getPageIndex = function(pageNum) {
2945 var pageIndices = this.getPageIndices(pageNum);
2947 if (pageIndices.length > 0) {
2948 return pageIndices[pageIndices.length - 1];
2954 // getPageIndices(pageNum)
2956 // Returns an array (possibly empty) of the indices with the given page number
2957 GnuBook.prototype.getPageIndices = function(pageNum) {
2960 // Check for special "nXX" page number
2961 if (pageNum.slice(0,1) == 'n') {
2963 var pageIntStr = pageNum.slice(1, pageNum.length);
2964 var pageIndex = parseInt(pageIntStr);
2965 indices.append(pageIndex);
2968 // Do nothing... will run through page names and see if one matches
2973 for (i=0; i<this.numLeafs; i++) {
2974 if (this.getPageNum(i) == pageNum) {
2982 // getPageName(index)
2984 // Returns the name of the page as it should be displayed in the user interface
2985 GnuBook.prototype.getPageName = function(index) {
2986 return 'Page ' + this.getPageNum(index);
2989 // updateLocationHash
2991 // Update the location hash from the current parameters. Call this instead of manually
2992 // using window.location.replace
2993 GnuBook.prototype.updateLocationHash = function() {
2994 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2995 window.location.replace(newHash);
2997 // This is the variable checked in the timer. Only user-generated changes
2998 // to the URL will trigger the event.
2999 this.oldLocationHash = newHash;
3002 // startLocationPolling
3004 // Starts polling of window.location to see hash fragment changes
3005 GnuBook.prototype.startLocationPolling = function() {
3006 var self = this; // remember who I am
3007 self.oldLocationHash = window.location.hash;
3009 if (this.locationPollId) {
3010 clearInterval(this.locationPollID);
3011 this.locationPollId = null;
3014 this.locationPollId = setInterval(function() {
3015 var newHash = window.location.hash;
3016 if (newHash != self.oldLocationHash) {
3017 if (newHash != self.oldUserHash) { // Only process new user hash once
3018 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3020 // Queue change if animating
3021 if (self.animating) {
3023 self.animationFinishedCallback = function() {
3024 self.updateFromParams(self.paramsFromFragment(newHash));
3026 } else { // update immediately
3027 self.updateFromParams(self.paramsFromFragment(newHash));
3029 self.oldUserHash = newHash;
3037 // Returns a URL for an embedded version of the current book
3038 GnuBook.prototype.getEmbedURL = function() {
3039 // We could generate a URL hash fragment here but for now we just leave at defaults
3040 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
3045 // Returns the embed code HTML fragment suitable for copy and paste
3046 GnuBook.prototype.getEmbedCode = function() {
3047 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
3052 // Returns true if we can switch to the requested mode
3053 GnuBook.prototype.canSwitchToMode = function(mode) {
3054 if (mode == this.constMode2up) {
3055 // check there are enough pages to display
3056 // $$$ this is a workaround for the mis-feature that we can't display
3057 // short books in 2up mode
3058 if (this.numLeafs < 6) {
3066 // Library functions
3068 clamp: function(value, min, max) {
3069 return Math.min(Math.max(value, min), max);