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;
53 this.printPopup = null;
56 this.searchResults = {};
58 this.firstIndex = null;
60 this.lastDisplayableIndex2up = null;
62 // We link to index.php to avoid redirect which breaks back button
63 this.logoURL = 'http://www.archive.org/index.php';
65 // Base URL for images
66 this.imagesBaseURL = '/bookreader/images/';
69 this.constMode1up = 1;
70 this.constMode2up = 2;
73 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
75 // Object to hold parameters related to 2up mode
77 coverInternalPadding: 10, // Width of cover
78 coverExternalPadding: 10, // Padding outside of cover
79 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
85 //______________________________________________________________________________
86 GnuBook.prototype.init = function() {
88 var startIndex = undefined;
90 // Find start index and mode if set in location hash
91 var params = this.paramsFromFragment(window.location.hash);
93 if ('undefined' != typeof(params.index)) {
94 startIndex = params.index;
95 } else if ('undefined' != typeof(params.page)) {
96 startIndex = this.getPageIndex(params.page);
99 if ('undefined' == typeof(startIndex)) {
100 if ('undefined' != typeof(this.titleLeaf)) {
101 startIndex = this.leafNumToIndex(this.titleLeaf);
105 if ('undefined' == typeof(startIndex)) {
109 if ('undefined' != typeof(params.mode)) {
110 this.mode = params.mode;
113 // Set document title -- may have already been set in enclosing html for
114 // search engine visibility
115 document.title = this.shortTitle(50);
117 // Sanitize parameters
118 if ( !this.canSwitchToMode( this.mode ) ) {
119 this.mode = this.constMode1up;
122 $("#GnuBook").empty();
123 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
124 $("#GnuBook").append("<div id='GBcontainer'></div>");
125 $("#GBcontainer").append("<div id='GBpageview'></div>");
127 $("#GBcontainer").bind('scroll', this, function(e) {
131 this.setupKeyListeners();
132 this.startLocationPolling();
134 $(window).bind('resize', this, function(e) {
135 //console.log('resize!');
136 if (1 == e.data.mode) {
137 //console.log('centering 1page view');
138 e.data.centerPageView();
139 $('#GBpageview').empty()
140 e.data.displayedIndices = [];
141 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
144 //console.log('drawing 2 page view');
146 // We only need to prepare again in autofit (size of spread changes)
147 if (e.data.twoPage.autofit) {
148 e.data.prepareTwoPageView();
150 // Re-center if the scrollbars have disappeared
151 var center = e.data.twoPageGetViewCenter();
152 var doRecenter = false;
153 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
154 center.percentageX = 0.5;
157 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
158 center.percentageY = 0.5;
162 e.data.twoPageCenterView(center.percentageX, center.percentageY);
168 $('.GBpagediv1up').bind('mousedown', this, function(e) {
169 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
170 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
173 if (1 == this.mode) {
174 this.resizePageView();
175 this.firstIndex = startIndex;
176 this.jumpToIndex(startIndex);
178 //this.resizePageView();
180 this.displayedIndices=[0];
181 this.firstIndex = startIndex;
182 this.displayedIndices = [this.firstIndex];
183 //console.log('titleLeaf: %d', this.titleLeaf);
184 //console.log('displayedIndices: %s', this.displayedIndices);
185 this.prepareTwoPageView();
188 // Enact other parts of initial params
189 this.updateFromParams(params);
192 GnuBook.prototype.setupKeyListeners = function() {
205 // We use document here instead of window to avoid a bug in jQuery on IE7
206 $(document).keydown(function(e) {
208 // Keyboard navigation
209 if (!self.keyboardNavigationIsDisabled(e)) {
213 // In 1up mode page scrolling is handled by browser
214 if (2 == self.mode) {
221 if (2 == self.mode) {
235 if (2 == self.mode) {
241 if (2 == self.mode) {
252 //______________________________________________________________________________
253 GnuBook.prototype.drawLeafs = function() {
254 if (1 == this.mode) {
255 this.drawLeafsOnePage();
257 this.drawLeafsTwoPage();
262 //______________________________________________________________________________
263 GnuBook.prototype.setDragHandler = function(div) {
264 div.dragging = false;
266 $(div).unbind('mousedown').bind('mousedown', function(e) {
269 //console.log('mousedown at ' + e.pageY);
271 this.dragging = true;
272 this.prevMouseX = e.pageX;
273 this.prevMouseY = e.pageY;
275 var startX = e.pageX;
276 var startY = e.pageY;
277 var startTop = $('#GBcontainer').attr('scrollTop');
278 var startLeft = $('#GBcontainer').attr('scrollLeft');
282 $(div).unbind('mousemove').bind('mousemove', function(ee) {
285 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
287 var offsetX = ee.pageX - this.prevMouseX;
288 var offsetY = ee.pageY - this.prevMouseY;
291 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
292 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
295 this.prevMouseX = ee.pageX;
296 this.prevMouseY = ee.pageY;
300 $(div).unbind('mouseup').bind('mouseup', function(ee) {
302 //console.log('mouseup');
304 this.dragging = false;
307 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
309 //console.log('mouseleave');
311 this.dragging = false;
314 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
316 //console.log('mouseenter');
318 this.dragging = false;
322 // setDragHandler2UP()
323 //______________________________________________________________________________
324 GnuBook.prototype.setDragHandler2UP = function(div) {
325 div.dragging = false;
327 $(div).unbind('mousedown').bind('mousedown', function(e) {
330 //console.log('mousedown at ' + e.pageY);
332 this.dragStart = {x: e.pageX, y: e.pageY };
333 this.mouseDown = true;
334 this.dragging = false; // wait until drag distance
335 this.prevMouseX = e.pageX;
336 this.prevMouseY = e.pageY;
338 var startX = e.pageX;
339 var startY = e.pageY;
340 var startTop = $('#GBcontainer').attr('scrollTop');
341 var startLeft = $('#GBcontainer').attr('scrollLeft');
345 $(div).unbind('mousemove').bind('mousemove', function(ee) {
348 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
350 var offsetX = ee.pageX - this.prevMouseX;
351 var offsetY = ee.pageY - this.prevMouseY;
353 var minDragDistance = 5; // $$$ constant
355 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
357 if (this.mouseDown && (distance > minDragDistance)) {
358 //console.log('drag start!');
360 this.dragging = true;
364 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
365 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
366 this.prevMouseX = ee.pageX;
367 this.prevMouseY = ee.pageY;
374 $(div).unbind('mouseup').bind('mouseup', function(ee) {
376 //console.log('mouseup');
378 this.dragging = false;
379 this.mouseDown = false;
384 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
386 //console.log('mouseleave');
388 this.dragging = false;
389 this.mouseDown = false;
392 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
394 //console.log('mouseenter');
396 this.dragging = false;
397 this.mouseDown = false;
401 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
402 //console.log('setting handler');
403 //console.log(element.tagName);
405 $(element).unbind('click').bind('click', data, function(e) {
408 //console.log('click!');
410 if (this.mouseDown && (!this.dragging)) {
411 //console.log('click not dragging!');
415 this.dragging = false;
416 this.mouseDown = false;
420 // drawLeafsOnePage()
421 //______________________________________________________________________________
422 GnuBook.prototype.drawLeafsOnePage = function() {
423 //alert('drawing leafs!');
427 var scrollTop = $('#GBcontainer').attr('scrollTop');
428 var scrollBottom = scrollTop + $('#GBcontainer').height();
429 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
431 var indicesToDisplay = [];
436 for (i=0; i<this.numLeafs; i++) {
437 var height = parseInt(this.getPageHeight(i)/this.reduce);
439 leafBottom += height;
440 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
441 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
442 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
443 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
444 if (topInView | bottomInView | middleInView) {
445 //console.log('displayed: ' + this.displayedIndices);
446 //console.log('to display: ' + i);
447 indicesToDisplay.push(i);
449 leafTop += height +10;
453 var firstIndexToDraw = indicesToDisplay[0];
454 this.firstIndex = firstIndexToDraw;
456 // Update hash, but only if we're currently displaying a leaf
457 // Hack that fixes #365790
458 if (this.displayedIndices.length > 0) {
459 this.updateLocationHash();
462 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
464 indicesToDisplay.unshift(firstIndexToDraw);
467 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
468 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
469 indicesToDisplay.push(lastIndexToDraw+1);
474 for (i=0; i<firstIndexToDraw; i++) {
475 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
478 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
479 var viewWidth = $('#GBcontainer').attr('scrollWidth');
482 for (i=0; i<indicesToDisplay.length; i++) {
483 var index = indicesToDisplay[i];
484 var height = parseInt(this.getPageHeight(index)/this.reduce);
486 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
487 var width = parseInt(this.getPageWidth(index)/this.reduce);
488 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
489 var div = document.createElement("div");
490 div.className = 'GBpagediv1up';
491 div.id = 'pagediv'+index;
492 div.style.position = "absolute";
493 $(div).css('top', leafTop + 'px');
494 var left = (viewWidth-width)>>1;
495 if (left<0) left = 0;
496 $(div).css('left', left+'px');
497 $(div).css('width', width+'px');
498 $(div).css('height', height+'px');
499 //$(div).text('loading...');
501 this.setDragHandler(div);
503 $('#GBpageview').append(div);
505 var img = document.createElement("img");
506 img.src = this.getPageURI(index, this.reduce, 0);
507 $(img).css('width', width+'px');
508 $(img).css('height', height+'px');
512 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
515 leafTop += height +10;
519 for (i=0; i<this.displayedIndices.length; i++) {
520 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
521 var index = this.displayedIndices[i];
522 //console.log('Removing leaf ' + index);
523 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
524 $('#pagediv'+index).remove();
526 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
530 this.displayedIndices = indicesToDisplay.slice();
531 this.updateSearchHilites();
533 if (null != this.getPageNum(firstIndexToDraw)) {
534 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
536 $("#GBpagenum").val('');
539 this.updateToolbarZoom(this.reduce);
543 // drawLeafsTwoPage()
544 //______________________________________________________________________________
545 GnuBook.prototype.drawLeafsTwoPage = function() {
546 var scrollTop = $('#GBtwopageview').attr('scrollTop');
547 var scrollBottom = scrollTop + $('#GBtwopageview').height();
549 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
551 var indexL = this.twoPage.currentIndexL;
552 var heightL = this.getPageHeight(indexL);
553 var widthL = this.getPageWidth(indexL);
555 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
556 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
557 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
558 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
559 //console.log(leafEdgeWidthL);
561 var middle = this.twoPage.middle; // $$$ getter instead?
562 var top = this.twoPageTop();
563 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
565 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
566 this.twoPage.gutter = this.twoPageGutter();
568 this.prefetchImg(indexL);
569 $(this.prefetchedImgs[indexL]).css({
570 position: 'absolute',
571 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
574 backgroundColor: 'rgb(234, 226, 205)',
575 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
576 width: this.twoPage.scaledWL + 'px',
577 borderRight: '1px solid black',
579 }).appendTo('#GBtwopageview');
581 var indexR = this.twoPage.currentIndexR;
582 var heightR = this.getPageHeight(indexR);
583 var widthR = this.getPageWidth(indexR);
585 // $$$ should use getwidth2up?
586 //var scaledWR = this.twoPage.height*widthR/heightR;
587 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
588 this.prefetchImg(indexR);
589 $(this.prefetchedImgs[indexR]).css({
590 position: 'absolute',
591 left: this.twoPage.gutter+'px',
594 backgroundColor: 'rgb(234, 226, 205)',
595 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
596 width: this.twoPage.scaledWR + 'px',
597 borderLeft: '1px solid black',
599 }).appendTo('#GBtwopageview');
602 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
603 this.setMouseHandlers2UP();
604 this.twoPageSetCursor();
606 this.updatePageNumBox2UP();
607 this.updateToolbarZoom(this.reduce);
609 // this.twoPagePlaceFlipAreas(); // No longer used
613 // updatePageNumBox2UP
614 //______________________________________________________________________________
615 GnuBook.prototype.updatePageNumBox2UP = function() {
616 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
617 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
619 $("#GBpagenum").val('');
621 this.updateLocationHash();
625 //______________________________________________________________________________
626 GnuBook.prototype.loadLeafs = function() {
630 if (null == this.timer) {
631 this.timer=setTimeout(function(){self.drawLeafs()},250);
633 clearTimeout(this.timer);
634 this.timer=setTimeout(function(){self.drawLeafs()},250);
640 // Pass 1 to zoom in, anything else to zoom out
641 //______________________________________________________________________________
642 GnuBook.prototype.zoom = function(direction) {
644 case this.constMode1up:
645 return this.zoom1up(direction);
646 case this.constMode2up:
647 return this.zoom2up(direction);
652 //______________________________________________________________________________
653 GnuBook.prototype.zoom1up = function(dir) {
654 if (2 == this.mode) { //can only zoom in 1-page mode
659 // $$$ with flexible zoom we could "snap" to /2 page reductions
660 // for better scaling
662 if (this.reduce <= 0.5) return;
663 this.reduce*=0.5; //zoom in
665 if (this.reduce >= 8) return;
666 this.reduce*=2; //zoom out
669 this.resizePageView();
671 $('#GBpageview').empty()
672 this.displayedIndices = [];
675 this.updateToolbarZoom(this.reduce);
679 //______________________________________________________________________________
680 GnuBook.prototype.resizePageView = function() {
683 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
684 var viewWidth = $('#GBcontainer').attr('clientWidth');
686 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
687 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
688 var oldPageViewHeight = $('#GBpageview').height();
689 var oldPageViewWidth = $('#GBpageview').width();
691 var oldCenterY = this.centerY1up();
692 var oldCenterX = this.centerX1up();
694 if (0 != oldPageViewHeight) {
695 var scrollRatio = oldCenterY / oldPageViewHeight;
700 for (i=0; i<this.numLeafs; i++) {
701 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
702 var width = parseInt(this.getPageWidth(i)/this.reduce);
703 if (width>viewWidth) viewWidth=width;
705 $('#GBpageview').height(viewHeight);
706 $('#GBpageview').width(viewWidth);
708 var newCenterY = scrollRatio*viewHeight;
709 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
710 $('#GBcontainer').attr('scrollTop', newTop);
712 // We use clientWidth here to avoid miscalculating due to scroll bar
713 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
714 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
715 newLeft = Math.max(newLeft, 0);
716 $('#GBcontainer').attr('scrollLeft', newLeft);
717 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
719 //this.centerPageView();
725 //______________________________________________________________________________
726 // Returns the current offset of the viewport center in scaled document coordinates.
727 GnuBook.prototype.centerX1up = function() {
729 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
730 centerX = $('#GBpageview').width();
732 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
734 centerX = Math.floor(centerX);
739 //______________________________________________________________________________
740 // Returns the current offset of the viewport center in scaled document coordinates.
741 GnuBook.prototype.centerY1up = function() {
742 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
743 return Math.floor(centerY);
747 //______________________________________________________________________________
748 GnuBook.prototype.centerPageView = function() {
750 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
751 var clientWidth = $('#GBcontainer').attr('clientWidth');
752 //console.log('sW='+scrollWidth+' cW='+clientWidth);
753 if (scrollWidth > clientWidth) {
754 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
759 // zoom2up(direction)
760 //______________________________________________________________________________
761 GnuBook.prototype.zoom2up = function(direction) {
763 // Hard stop autoplay
764 this.stopFlipAnimations();
766 // Get new zoom state
767 var newZoom = this.twoPageNextReduce(this.reduce, direction);
768 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
771 this.twoPage.autofit = newZoom.autofit;
772 this.reduce = newZoom.reduce;
774 // Preserve view center position
775 var oldCenter = this.twoPageGetViewCenter();
777 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
778 // $$$ An improvement would be to use the low res image until the larger one is loaded.
779 if (1 == direction) {
780 for (var img in this.prefetchedImgs) {
781 delete this.prefetchedImgs[img];
785 // Prepare view with new center to minimize visual glitches
786 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
790 // quantizeReduce(reduce)
791 //______________________________________________________________________________
792 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
793 GnuBook.prototype.quantizeReduce = function(reduce) {
794 var quantized = this.reductionFactors[0];
795 var distance = Math.abs(reduce - quantized);
796 for (var i = 1; i < this.reductionFactors.length; i++) {
797 newDistance = Math.abs(reduce - this.reductionFactors[i]);
798 if (newDistance < distance) {
799 distance = newDistance;
800 quantized = this.reductionFactors[i];
807 // twoPageNextReduce()
808 //______________________________________________________________________________
809 // Returns the next reduction level
810 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
812 var autofitReduce = this.twoPageGetAutofitReduce();
814 if (0 == direction) { // autofit
815 result.autofit = true;
816 result.reduce = autofitReduce;
818 } else if (1 == direction) { // zoom in
819 var newReduce = this.reductionFactors[0];
821 for (var i = 1; i < this.reductionFactors.length; i++) {
822 if (this.reductionFactors[i] < reduce) {
823 newReduce = this.reductionFactors[i];
827 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
829 result.autofit = true;
830 result.reduce = autofitReduce;
832 result.autofit = false;
833 result.reduce = newReduce;
837 var lastIndex = this.reductionFactors.length - 1;
838 var newReduce = this.reductionFactors[lastIndex];
840 for (var i = lastIndex; i >= 0; i--) {
841 if (this.reductionFactors[i] > reduce) {
842 newReduce = this.reductionFactors[i];
846 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
848 result.autofit = true;
849 result.reduce = autofitReduce;
851 result.autofit = false;
852 result.reduce = newReduce;
860 //______________________________________________________________________________
861 // Attempts to jump to page. Returns true if page could be found, false otherwise.
862 GnuBook.prototype.jumpToPage = function(pageNum) {
864 var pageIndex = this.getPageIndex(pageNum);
866 if ('undefined' != typeof(pageIndex)) {
869 this.jumpToIndex(pageIndex);
870 $('#GBcontainer').attr('scrollTop', leafTop);
879 //______________________________________________________________________________
880 GnuBook.prototype.jumpToIndex = function(index) {
882 if (2 == this.mode) {
885 // By checking against min/max we do nothing if requested index
887 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
888 this.flipBackToIndex(index);
889 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
890 this.flipFwdToIndex(index);
897 for (i=0; i<index; i++) {
898 h = parseInt(this.getPageHeight(i)/this.reduce);
899 leafTop += h + this.padding;
901 //$('#GBcontainer').attr('scrollTop', leafTop);
902 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
909 //______________________________________________________________________________
910 GnuBook.prototype.switchMode = function(mode) {
912 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
914 if (mode == this.mode) return;
916 if (!this.canSwitchToMode(mode)) {
921 this.removeSearchHilites();
925 this.switchToolbarMode(mode);
927 // $$$ TODO preserve center of view when switching between mode
928 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
931 this.reduce = this.quantizeReduce(this.reduce);
932 this.prepareOnePageView();
934 this.twoPage.autofit = false; // Take zoom level from other mode
935 this.reduce = this.quantizeReduce(this.reduce);
936 this.prepareTwoPageView();
937 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
942 //prepareOnePageView()
943 //______________________________________________________________________________
944 GnuBook.prototype.prepareOnePageView = function() {
946 // var startLeaf = this.displayedIndices[0];
947 var startLeaf = this.currentIndex();
949 $('#GBcontainer').empty();
950 $('#GBcontainer').css({
955 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
957 this.resizePageView();
959 this.jumpToIndex(startLeaf);
960 this.displayedIndices = [];
962 this.drawLeafsOnePage();
964 // Bind mouse handlers
965 // Disable mouse click to avoid selected/highlighted page images - bug 354239
966 gbPageView.bind('mousedown', function(e) {
967 // $$$ check here for right-click and don't disable. Also use jQuery style
968 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
971 // Special hack for IE7
972 gbPageView[0].onselectstart = function(e) { return false; };
975 // prepareTwoPageView()
976 //______________________________________________________________________________
977 // Some decisions about two page view:
979 // Both pages will be displayed at the same height, even if they were different physical/scanned
980 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
981 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
982 // aspect ratio to determine the height.
984 // The two page view div is resized to keep the middle of the book in the middle of the div
985 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
986 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
987 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
988 $('#GBcontainer').empty();
989 $('#GBcontainer').css('overflow', 'auto');
991 // We want to display two facing pages. We may be missing
992 // one side of the spread because it is the first/last leaf,
993 // foldouts, missing pages, etc
995 //var targetLeaf = this.displayedIndices[0];
996 var targetLeaf = this.firstIndex;
998 if (targetLeaf < this.firstDisplayableIndex()) {
999 targetLeaf = this.firstDisplayableIndex();
1002 if (targetLeaf > this.lastDisplayableIndex()) {
1003 targetLeaf = this.lastDisplayableIndex();
1006 //this.twoPage.currentIndexL = null;
1007 //this.twoPage.currentIndexR = null;
1008 //this.pruneUnusedImgs();
1010 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1011 this.twoPage.currentIndexL = currentSpreadIndices[0];
1012 this.twoPage.currentIndexR = currentSpreadIndices[1];
1013 this.firstIndex = this.twoPage.currentIndexL;
1015 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1017 this.pruneUnusedImgs();
1018 this.prefetch(); // Preload images or reload if scaling has changed
1020 //console.dir(this.twoPage);
1022 // Add the two page view
1023 // $$$ Can we get everything set up and then append?
1024 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1026 // $$$ calculate first then set
1027 $('#GBtwopageview').css( {
1028 height: this.twoPage.totalHeight + 'px',
1029 width: this.twoPage.totalWidth + 'px',
1030 position: 'absolute'
1033 // If there will not be scrollbars (e.g. when zooming out) we center the book
1034 // since otherwise the book will be stuck off-center
1035 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1036 centerPercentageX = 0.5;
1038 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1039 centerPercentageY = 0.5;
1042 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1044 this.twoPage.coverDiv = document.createElement('div');
1045 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1046 border: '1px solid rgb(68, 25, 17)',
1047 width: this.twoPage.bookCoverDivWidth + 'px',
1048 height: this.twoPage.bookCoverDivHeight+'px',
1049 visibility: 'visible',
1050 position: 'absolute',
1051 backgroundColor: '#663929',
1052 left: this.twoPage.bookCoverDivLeft + 'px',
1053 top: this.twoPage.bookCoverDivTop+'px',
1054 MozBorderRadiusTopleft: '7px',
1055 MozBorderRadiusTopright: '7px',
1056 MozBorderRadiusBottomright: '7px',
1057 MozBorderRadiusBottomleft: '7px'
1058 }).appendTo('#GBtwopageview');
1060 this.leafEdgeR = document.createElement('div');
1061 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1062 $(this.leafEdgeR).css({
1063 borderStyle: 'solid solid solid none',
1064 borderColor: 'rgb(51, 51, 34)',
1065 borderWidth: '1px 1px 1px 0px',
1066 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1067 width: this.twoPage.leafEdgeWidthR + 'px',
1068 height: this.twoPage.height-1 + 'px',
1070 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1071 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1072 position: 'absolute'
1073 }).appendTo('#GBtwopageview');
1075 this.leafEdgeL = document.createElement('div');
1076 this.leafEdgeL.className = 'leafEdgeL';
1077 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1078 borderStyle: 'solid none solid solid',
1079 borderColor: 'rgb(51, 51, 34)',
1080 borderWidth: '1px 0px 1px 1px',
1081 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1082 width: this.twoPage.leafEdgeWidthL + 'px',
1083 height: this.twoPage.height-1 + 'px',
1084 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1085 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1086 position: 'absolute'
1087 }).appendTo('#GBtwopageview');
1089 div = document.createElement('div');
1090 $(div).attr('id', 'GBbookspine').css({
1091 border: '1px solid rgb(68, 25, 17)',
1092 width: this.twoPage.bookSpineDivWidth+'px',
1093 height: this.twoPage.bookSpineDivHeight+'px',
1094 position: 'absolute',
1095 backgroundColor: 'rgb(68, 25, 17)',
1096 left: this.twoPage.bookSpineDivLeft+'px',
1097 top: this.twoPage.bookSpineDivTop+'px'
1098 }).appendTo('#GBtwopageview');
1100 var self = this; // for closure
1102 /* Flip areas no longer used
1103 this.twoPage.leftFlipArea = document.createElement('div');
1104 this.twoPage.leftFlipArea.className = 'GBfliparea';
1105 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1107 width: this.twoPageFlipAreaWidth() + 'px',
1108 height: this.twoPageFlipAreaHeight() + 'px',
1109 position: 'absolute',
1110 left: this.twoPageLeftFlipAreaLeft() + 'px',
1111 top: this.twoPageFlipAreaTop() + 'px',
1114 }).bind('click', function(e) {
1116 }).bind('mousedown', function(e) {
1118 }).appendTo('#GBtwopageview');
1120 this.twoPage.rightFlipArea = document.createElement('div');
1121 this.twoPage.rightFlipArea.className = 'GBfliparea';
1122 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1124 width: this.twoPageFlipAreaWidth() + 'px',
1125 height: this.twoPageFlipAreaHeight() + 'px',
1126 position: 'absolute',
1127 left: this.twoPageRightFlipAreaLeft() + 'px',
1128 top: this.twoPageFlipAreaTop() + 'px',
1131 }).bind('click', function(e) {
1133 }).bind('mousedown', function(e) {
1135 }).appendTo('#GBtwopageview');
1138 this.prepareTwoPagePopUp();
1140 this.displayedIndices = [];
1142 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1143 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1145 this.drawLeafsTwoPage();
1146 this.updateSearchHilites2UP();
1147 this.updateToolbarZoom(this.reduce);
1152 // prepareTwoPagePopUp()
1154 // This function prepares the "View Page n" popup that shows while the mouse is
1155 // over the left/right "stack of sheets" edges. It also binds the mouse
1156 // events for these divs.
1157 //______________________________________________________________________________
1158 GnuBook.prototype.prepareTwoPagePopUp = function() {
1160 this.twoPagePopUp = document.createElement('div');
1161 $(this.twoPagePopUp).css({
1162 border: '1px solid black',
1164 position: 'absolute',
1165 fontFamily: 'sans-serif',
1168 backgroundColor: 'rgb(255, 255, 238)',
1170 }).appendTo('#GBcontainer');
1171 $(this.twoPagePopUp).hide();
1173 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1174 $(e.data.twoPagePopUp).show();
1177 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1178 $(e.data.twoPagePopUp).hide();
1181 $(this.leafEdgeL).bind('click', this, function(e) {
1183 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1184 e.data.jumpToIndex(jumpIndex);
1187 $(this.leafEdgeR).bind('click', this, function(e) {
1189 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1190 e.data.jumpToIndex(jumpIndex);
1193 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1195 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1196 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1198 // $$$ TODO: Make sure popup is positioned so that it is in view
1199 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1200 $(e.data.twoPagePopUp).css({
1201 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1202 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1206 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1208 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1209 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1211 // $$$ TODO: Make sure popup is positioned so that it is in view
1212 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1213 $(e.data.twoPagePopUp).css({
1214 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1215 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1220 // calculateSpreadSize()
1221 //______________________________________________________________________________
1222 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1223 // this.twoPage.currentIndexR
1224 // This function sets this.twoPage.height, twoPage.width
1226 GnuBook.prototype.calculateSpreadSize = function() {
1228 var firstIndex = this.twoPage.currentIndexL;
1229 var secondIndex = this.twoPage.currentIndexR;
1230 //console.log('first page is ' + firstIndex);
1232 // Calculate page sizes and total leaf width
1234 if ( this.twoPage.autofit) {
1235 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1237 // set based on reduction factor
1238 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1241 // Both pages together
1242 this.twoPage.height = spreadSize.height;
1243 this.twoPage.width = spreadSize.width;
1246 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1247 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1250 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1251 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1252 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1256 // The width of the book cover div. The combined width of both pages, twice the width
1257 // of the book cover internal padding (2*10) and the page edges
1258 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1259 // The height of the book cover div
1260 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1263 // We calculate the total width and height for the div so that we can make the book
1265 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1266 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1267 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1268 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1269 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1270 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1272 // We want to minimize the unused space in two-up mode (maximize the amount of page
1273 // shown). We give width to the leaf edges and these widths change (though the sum
1274 // of the two remains constant) as we flip through the book. With the book
1275 // cover centered and fixed in the GBcontainer div the page images will meet
1276 // at the "gutter" which is generally offset from the center.
1277 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1278 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1280 // The left edge of the book cover moves depending on the width of the pages
1281 // $$$ change to getter
1282 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1283 // The top edge of the book cover stays a fixed distance from the top
1284 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1287 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1288 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1289 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1292 this.reduce = spreadSize.reduce; // $$$ really set this here?
1295 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1298 // We check which page is closest to a "normal" page and use that to set the height
1299 // for both pages. This means that foldouts and other odd size pages will be displayed
1300 // smaller than the nominal zoom amount.
1301 var canon5Dratio = 1.5;
1304 height: this.getPageHeight(firstIndex),
1305 width: this.getPageWidth(firstIndex)
1309 height: this.getPageHeight(secondIndex),
1310 width: this.getPageWidth(secondIndex)
1313 var firstIndexRatio = first.height / first.width;
1314 var secondIndexRatio = second.height / second.width;
1315 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1318 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1319 ratio = firstIndexRatio;
1320 //console.log('using firstIndexRatio ' + ratio);
1322 ratio = secondIndexRatio;
1323 //console.log('using secondIndexRatio ' + ratio);
1326 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1327 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1328 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1330 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1331 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1333 ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1334 ideal.width -= 10; // $$$ fudge factor
1335 ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1336 ideal.height -= 20; // fudge factor
1337 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1339 if (ideal.height/ratio <= ideal.width) {
1341 ideal.width = parseInt(ideal.height/ratio);
1344 ideal.height = parseInt(ideal.width*ratio);
1347 // $$$ check this logic with large spreads
1348 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1353 // getSpreadSizeFromReduce()
1354 //______________________________________________________________________________
1355 // Returns the spread size calculated from the reduction factor for the given pages
1356 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1357 var spreadSize = {};
1358 // $$$ Scale this based on reduce?
1359 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1360 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1361 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1363 // $$$ Possibly incorrect -- we should make height "dominant"
1364 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1365 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1366 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1367 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1368 spreadSize.reduce = reduce;
1373 // twoPageGetAutofitReduce()
1374 //______________________________________________________________________________
1375 // Returns the current ideal reduction factor
1376 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1377 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1378 return spreadSize.reduce;
1381 // twoPageSetCursor()
1382 //______________________________________________________________________________
1383 // Set the cursor for two page view
1384 GnuBook.prototype.twoPageSetCursor = function() {
1385 // console.log('setting cursor');
1386 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1387 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1388 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1389 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1391 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1392 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1397 //______________________________________________________________________________
1398 // Returns the currently active index.
1399 GnuBook.prototype.currentIndex = function() {
1400 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1401 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1402 return this.firstIndex;
1404 throw 'currentIndex called for unimplemented mode ' + this.mode;
1409 //______________________________________________________________________________
1410 // Flip the right page over onto the left
1411 GnuBook.prototype.right = function() {
1412 if ('rl' != this.pageProgression) {
1422 //______________________________________________________________________________
1423 // Flip to the rightmost page
1424 GnuBook.prototype.rightmost = function() {
1425 if ('rl' != this.pageProgression) {
1433 //______________________________________________________________________________
1434 // Flip the left page over onto the right.
1435 GnuBook.prototype.left = function() {
1436 if ('rl' != this.pageProgression) {
1446 //______________________________________________________________________________
1447 // Flip to the leftmost page
1448 GnuBook.prototype.leftmost = function() {
1449 if ('rl' != this.pageProgression) {
1457 //______________________________________________________________________________
1458 GnuBook.prototype.next = function() {
1459 if (2 == this.mode) {
1461 this.flipFwdToIndex(null);
1463 if (this.firstIndex < this.lastDisplayableIndex()) {
1464 this.jumpToIndex(this.firstIndex+1);
1470 //______________________________________________________________________________
1471 GnuBook.prototype.prev = function() {
1472 if (2 == this.mode) {
1474 this.flipBackToIndex(null);
1476 if (this.firstIndex >= 1) {
1477 this.jumpToIndex(this.firstIndex-1);
1482 GnuBook.prototype.first = function() {
1483 if (2 == this.mode) {
1484 this.jumpToIndex(2);
1487 this.jumpToIndex(0);
1491 GnuBook.prototype.last = function() {
1492 if (2 == this.mode) {
1493 this.jumpToIndex(this.lastDisplayableIndex());
1496 this.jumpToIndex(this.lastDisplayableIndex());
1500 // flipBackToIndex()
1501 //______________________________________________________________________________
1502 // to flip back one spread, pass index=null
1503 GnuBook.prototype.flipBackToIndex = function(index) {
1504 if (1 == this.mode) return;
1506 var leftIndex = this.twoPage.currentIndexL;
1508 // $$$ Need to change this to be able to see first spread.
1509 // See https://bugs.launchpad.net/gnubook/+bug/296788
1510 if (leftIndex <= 2) return;
1511 if (this.animating) return;
1513 if (null != this.leafEdgeTmp) {
1514 alert('error: leafEdgeTmp should be null!');
1518 if (null == index) {
1519 index = leftIndex-2;
1521 //if (index<0) return;
1523 var previousIndices = this.getSpreadIndices(index);
1525 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1529 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1531 this.animating = true;
1533 if ('rl' != this.pageProgression) {
1534 // Assume LTR and we are going backward
1535 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1536 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1538 // RTL and going backward
1539 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1540 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1544 // flipLeftToRight()
1545 //______________________________________________________________________________
1546 // Flips the page on the left towards the page on the right
1547 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1549 var leftLeaf = this.twoPage.currentIndexL;
1551 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1552 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1553 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1555 var currWidthL = this.getPageWidth2UP(leftLeaf);
1556 var newWidthL = this.getPageWidth2UP(newIndexL);
1557 var newWidthR = this.getPageWidth2UP(newIndexR);
1559 var top = this.twoPageTop();
1560 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1562 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1563 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1565 //animation strategy:
1566 // 0. remove search highlight, if any.
1567 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1568 // of the left leaf and where the user clicked in the leaf edge.
1569 // Note that if this function was triggered by left() and not a
1570 // mouse click, the width of leafEdgeTmp is very small (zero px).
1571 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1572 // leftLeaf to width=0.
1573 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1574 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1575 // its new full width.
1576 // 4. After step 3 is finished, do the following:
1577 // - remove leafEdgeTmp from the dom.
1578 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1579 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1580 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1581 // and width=newLeafEdgeWidthL.
1582 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1583 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1584 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1585 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1586 // - prefetch new adjacent leafs.
1587 // - set up click handlers for both new left and right leafs.
1588 // - redraw the search highlight.
1589 // - update the pagenum box and the url.
1592 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1594 this.leafEdgeTmp = document.createElement('div');
1595 $(this.leafEdgeTmp).css({
1596 borderStyle: 'solid none solid solid',
1597 borderColor: 'rgb(51, 51, 34)',
1598 borderWidth: '1px 0px 1px 1px',
1599 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1600 width: leafEdgeTmpW + 'px',
1601 height: this.twoPage.height-1 + 'px',
1602 left: leftEdgeTmpLeft + 'px',
1604 position: 'absolute',
1606 }).appendTo('#GBtwopageview');
1608 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1609 $(this.leafEdgeL).css({
1610 width: newLeafEdgeWidthL+'px',
1611 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1614 // Left gets the offset of the current left leaf from the document
1615 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1616 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1617 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1619 // We change the left leaf to right positioning
1620 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1621 $(this.prefetchedImgs[leftLeaf]).css({
1626 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1627 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1631 this.removeSearchHilites();
1633 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1634 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1636 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1637 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1639 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1640 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1641 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1643 $(self.leafEdgeR).css({
1644 // Moves the right leaf edge
1645 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1646 left: gutter+newWidthR+'px'
1649 $(self.leafEdgeL).css({
1650 // Moves and resizes the left leaf edge
1651 width: newLeafEdgeWidthL+'px',
1652 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1655 // Resizes the brown border div
1656 $(self.twoPage.coverDiv).css({
1657 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1658 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1661 $(self.leafEdgeTmp).remove();
1662 self.leafEdgeTmp = null;
1664 // $$$ TODO refactor with opposite direction flip
1666 self.twoPage.currentIndexL = newIndexL;
1667 self.twoPage.currentIndexR = newIndexR;
1668 self.twoPage.scaledWL = newWidthL;
1669 self.twoPage.scaledWR = newWidthR;
1670 self.twoPage.gutter = gutter;
1672 self.firstIndex = self.twoPage.currentIndexL;
1673 self.displayedIndices = [newIndexL, newIndexR];
1674 self.pruneUnusedImgs();
1676 self.animating = false;
1678 self.updateSearchHilites2UP();
1679 self.updatePageNumBox2UP();
1681 // self.twoPagePlaceFlipAreas(); // No longer used
1682 self.setMouseHandlers2UP();
1683 self.twoPageSetCursor();
1685 if (self.animationFinishedCallback) {
1686 self.animationFinishedCallback();
1687 self.animationFinishedCallback = null;
1695 //______________________________________________________________________________
1696 // Whether we flip left or right is dependent on the page progression
1697 // to flip forward one spread, pass index=null
1698 GnuBook.prototype.flipFwdToIndex = function(index) {
1700 if (this.animating) return;
1702 if (null != this.leafEdgeTmp) {
1703 alert('error: leafEdgeTmp should be null!');
1707 if (null == index) {
1708 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1710 if (index > this.lastDisplayableIndex()) return;
1712 this.animating = true;
1714 var nextIndices = this.getSpreadIndices(index);
1716 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1718 if ('rl' != this.pageProgression) {
1719 // We did not specify RTL
1720 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1721 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1724 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1725 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1729 // flipRightToLeft(nextL, nextR, gutter)
1730 // $$$ better not to have to pass gutter in
1731 //______________________________________________________________________________
1732 // Flip from left to right and show the nextL and nextR indices on those sides
1733 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1734 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1735 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1736 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1737 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1739 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1741 var top = this.twoPageTop();
1742 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1744 var middle = this.twoPage.middle;
1745 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1747 this.leafEdgeTmp = document.createElement('div');
1748 $(this.leafEdgeTmp).css({
1749 borderStyle: 'solid none solid solid',
1750 borderColor: 'rgb(51, 51, 34)',
1751 borderWidth: '1px 0px 1px 1px',
1752 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1753 width: leafEdgeTmpW + 'px',
1754 height: this.twoPage.height-1 + 'px',
1755 left: gutter+scaledW+'px',
1757 position: 'absolute',
1759 }).appendTo('#GBtwopageview');
1761 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1762 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1764 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1765 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1766 var newWidthL = this.getPageWidth2UP(newIndexL);
1767 var newWidthR = this.getPageWidth2UP(newIndexR);
1769 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1771 var self = this; // closure-tastic!
1773 var speed = this.flipSpeed;
1775 this.removeSearchHilites();
1777 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1778 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1779 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1780 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1781 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1783 $(self.leafEdgeL).css({
1784 width: newLeafEdgeWidthL+'px',
1785 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1788 // Resizes the book cover
1789 $(self.twoPage.coverDiv).css({
1790 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1791 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1794 $(self.leafEdgeTmp).remove();
1795 self.leafEdgeTmp = null;
1797 self.twoPage.currentIndexL = newIndexL;
1798 self.twoPage.currentIndexR = newIndexR;
1799 self.twoPage.scaledWL = newWidthL;
1800 self.twoPage.scaledWR = newWidthR;
1801 self.twoPage.gutter = gutter;
1803 self.firstIndex = self.twoPage.currentIndexL;
1804 self.displayedIndices = [newIndexL, newIndexR];
1805 self.pruneUnusedImgs();
1807 self.animating = false;
1810 self.updateSearchHilites2UP();
1811 self.updatePageNumBox2UP();
1813 // self.twoPagePlaceFlipAreas(); // No longer used
1814 self.setMouseHandlers2UP();
1815 self.twoPageSetCursor();
1817 if (self.animationFinishedCallback) {
1818 self.animationFinishedCallback();
1819 self.animationFinishedCallback = null;
1825 // setMouseHandlers2UP
1826 //______________________________________________________________________________
1827 GnuBook.prototype.setMouseHandlers2UP = function() {
1829 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1834 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1841 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
1842 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
1849 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
1850 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
1853 e.data.self.right();
1859 //______________________________________________________________________________
1860 GnuBook.prototype.prefetchImg = function(index) {
1861 var pageURI = this.getPageURI(index);
1863 // Load image if not loaded or URI has changed (e.g. due to scaling)
1864 var loadImage = false;
1865 if (undefined == this.prefetchedImgs[index]) {
1866 //console.log('no image for ' + index);
1868 } else if (pageURI != this.prefetchedImgs[index].uri) {
1869 //console.log('uri changed for ' + index);
1874 //console.log('prefetching ' + index);
1875 var img = document.createElement("img");
1877 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
1878 this.prefetchedImgs[index] = img;
1883 // prepareFlipLeftToRight()
1885 //______________________________________________________________________________
1887 // Prepare to flip the left page towards the right. This corresponds to moving
1888 // backward when the page progression is left to right.
1889 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1891 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1893 this.prefetchImg(prevL);
1894 this.prefetchImg(prevR);
1896 var height = this.getPageHeight(prevL);
1897 var width = this.getPageWidth(prevL);
1898 var middle = this.twoPage.middle;
1899 var top = this.twoPageTop();
1900 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1902 // The gutter is the dividing line between the left and right pages.
1903 // It is offset from the middle to create the illusion of thickness to the pages
1904 var gutter = middle + this.gutterOffsetForIndex(prevL);
1906 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1907 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1908 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1910 $(this.prefetchedImgs[prevL]).css({
1911 position: 'absolute',
1912 left: gutter-scaledW+'px',
1913 right: '', // clear right property
1915 backgroundColor: 'rgb(234, 226, 205)',
1916 height: this.twoPage.height,
1917 width: scaledW+'px',
1918 borderRight: '1px solid black',
1922 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1924 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1926 $(this.prefetchedImgs[prevR]).css({
1927 position: 'absolute',
1931 backgroundColor: 'rgb(234, 226, 205)',
1932 height: this.twoPage.height,
1934 borderLeft: '1px solid black',
1938 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1942 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1943 // prepareFlipRightToLeft()
1944 //______________________________________________________________________________
1945 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1947 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1950 this.prefetchImg(nextL);
1951 this.prefetchImg(nextR);
1953 var height = this.getPageHeight(nextR);
1954 var width = this.getPageWidth(nextR);
1955 var middle = this.twoPage.middle;
1956 var top = this.twoPageTop();
1957 var scaledW = this.twoPage.height*width/height;
1959 var gutter = middle + this.gutterOffsetForIndex(nextL);
1961 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1962 $(this.prefetchedImgs[nextR]).css({
1963 position: 'absolute',
1966 backgroundColor: 'rgb(234, 226, 205)',
1967 height: this.twoPage.height,
1968 width: scaledW+'px',
1969 borderLeft: '1px solid black',
1973 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1975 height = this.getPageHeight(nextL);
1976 width = this.getPageWidth(nextL);
1977 scaledW = this.twoPage.height*width/height;
1979 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1980 $(this.prefetchedImgs[nextL]).css({
1981 position: 'absolute',
1982 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1984 backgroundColor: 'rgb(234, 226, 205)',
1985 height: this.twoPage.height,
1986 width: 0+'px', // Start at 0 width, then grow to the left
1987 borderRight: '1px solid black',
1991 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1995 // getNextLeafs() -- NOT RTL AWARE
1996 //______________________________________________________________________________
1997 // GnuBook.prototype.getNextLeafs = function(o) {
1998 // //TODO: we might have two left or two right leafs in a row (damaged book)
1999 // //For now, assume that leafs are contiguous.
2001 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2002 // o.L = this.twoPage.currentIndexL+2;
2003 // o.R = this.twoPage.currentIndexL+3;
2006 // getprevLeafs() -- NOT RTL AWARE
2007 //______________________________________________________________________________
2008 // GnuBook.prototype.getPrevLeafs = function(o) {
2009 // //TODO: we might have two left or two right leafs in a row (damaged book)
2010 // //For now, assume that leafs are contiguous.
2012 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2013 // o.L = this.twoPage.currentIndexL-2;
2014 // o.R = this.twoPage.currentIndexL-1;
2017 // pruneUnusedImgs()
2018 //______________________________________________________________________________
2019 GnuBook.prototype.pruneUnusedImgs = function() {
2020 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2021 for (var key in this.prefetchedImgs) {
2022 //console.log('key is ' + key);
2023 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2024 //console.log('removing key '+ key);
2025 $(this.prefetchedImgs[key]).remove();
2027 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2028 //console.log('deleting key '+ key);
2029 delete this.prefetchedImgs[key];
2035 //______________________________________________________________________________
2036 GnuBook.prototype.prefetch = function() {
2038 // prefetch visible pages first
2039 this.prefetchImg(this.twoPage.currentIndexL);
2040 this.prefetchImg(this.twoPage.currentIndexR);
2042 var adjacentPagesToLoad = 3;
2044 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2045 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2047 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2048 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2050 // Load images spreading out from current
2051 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2052 var goingDown = lowCurrent - i;
2053 if (goingDown >= start) {
2054 this.prefetchImg(goingDown);
2056 var goingUp = highCurrent + i;
2057 if (goingUp <= end) {
2058 this.prefetchImg(goingUp);
2063 var lim = this.twoPage.currentIndexL-4;
2065 lim = Math.max(lim, 0);
2066 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2067 this.prefetchImg(i);
2070 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2071 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2072 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2073 this.prefetchImg(i);
2079 // getPageWidth2UP()
2080 //______________________________________________________________________________
2081 GnuBook.prototype.getPageWidth2UP = function(index) {
2082 // We return the width based on the dominant height
2083 var height = this.getPageHeight(index);
2084 var width = this.getPageWidth(index);
2085 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2089 //______________________________________________________________________________
2090 GnuBook.prototype.search = function(term) {
2091 term = term.replace(/\//g, ' '); // strip slashes
2092 this.searchTerm = term;
2093 $('#GnuBookSearchScript').remove();
2094 var script = document.createElement("script");
2095 script.setAttribute('id', 'GnuBookSearchScript');
2096 script.setAttribute("type", "text/javascript");
2097 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2098 document.getElementsByTagName('head')[0].appendChild(script);
2099 $('#GnuBookSearchBox').val(term);
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.printPage = function() {
2398 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2400 /* iframe implementation
2402 if (null != this.printPopup) { // check if already showing
2405 this.printPopup = document.createElement("div");
2406 $(this.printPopup).css({
2407 position: 'absolute',
2409 left: ($('#GBcontainer').width()-400)/2 + 'px',
2412 border: "3px double #999999",
2414 backgroundColor: "#fff"
2415 }).appendTo('#GnuBook');
2418 if (this.constMode1up == this.mode) {
2419 indexToPrint = this.firstIndex;
2421 indexToPrint = this.twoPage.currentIndexL;
2424 this.indexToPrint = indexToPrint;
2426 var htmlStr = '<div style="text-align: center;">';
2427 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2428 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2429 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2430 //htmlStr += '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
2431 //htmlStr += '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
2432 htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
2434 htmlStr += '</div>';
2435 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2436 htmlStr += '</div>';
2438 this.printPopup.innerHTML = htmlStr;
2440 var iframe = document.createElement('iframe');
2441 iframe.id = 'printFrame';
2442 iframe.name = 'printFrame';
2443 iframe.width = '233px'; // 8.5 x 11 aspect
2444 iframe.height = '300px';
2446 var self = this; // closure
2448 $(iframe).load(function() {
2449 var doc = GnuBook.util.getIFrameDocument(this);
2450 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2453 $('#printDiv').prepend(iframe);
2457 // Get print URI from current indices and mode
2458 GnuBook.prototype.getPrintURI = function() {
2460 if (this.constMode2up == this.mode) {
2461 indexToPrint = this.twoPage.currentIndexL;
2463 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2466 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2467 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2468 + '&width=' + this.getPageWidth(indexToPrint) + '&height=' + this.getPageHeight(indexToPrint);
2470 if (this.constMode2up == this.mode) {
2471 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this.getPageWidth(this.twoPage.currentIndexR);
2472 options += '&height2=' + this.getPageHeight(this.twoPage.currentIndexR);
2473 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2475 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2478 return '/bookreader/print.php?' + options;
2481 /* iframe implementation
2482 GnuBook.prototype.getPrintFrameContent = function(index) {
2483 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2484 // 8.5x11 so we should end up not overflowing on either paper size.
2485 var paperAspect = 8.5 / 11;
2486 var imageAspect = this.getPageWidth(index) / this.getPageHeight(index);
2490 // Rotate if possible and appropriate, to get larger image size on printed page
2491 if (this.canRotatePage(index)) {
2492 if (imageAspect > 1 && imageAspect > paperAspect) {
2493 // more wide than square, and more wide than paper
2495 imageAspect = 1/imageAspect;
2500 if (imageAspect > paperAspect) {
2501 // wider than paper, fit width
2502 fitAttrs = 'width="95%"';
2504 // taller than paper, fit height
2505 fitAttrs = 'height="95%"';
2508 var imageURL = this.getPageURI(index, 1, rotate);
2509 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2510 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2511 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2512 iframeStr += '</div>';
2513 iframeStr += '</body></html>';
2518 GnuBook.prototype.updatePrintFrame = function(delta) {
2519 var newIndex = this.indexToPrint + delta;
2520 newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
2521 if (newIndex == this.indexToPrint) {
2524 this.indexToPrint = newIndex;
2525 var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
2526 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2531 //______________________________________________________________________________
2532 GnuBook.prototype.showEmbedCode = function() {
2533 if (null != this.embedPopup) { // check if already showing
2537 this.embedPopup = document.createElement("div");
2538 $(this.embedPopup).css({
2539 position: 'absolute',
2541 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2544 border: "3px double #999999",
2546 backgroundColor: "#fff"
2547 }).appendTo('#GnuBook');
2549 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2550 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>';
2551 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2552 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2554 this.embedPopup.innerHTML = htmlStr;
2555 $(this.embedPopup).find('input').bind('click', function() {
2561 //______________________________________________________________________________
2562 GnuBook.prototype.autoToggle = function() {
2564 var bComingFrom1up = false;
2565 if (2 != this.mode) {
2566 bComingFrom1up = true;
2570 // Change to autofit if book is too large
2571 if (this.reduce < this.twoPageGetAutofitReduce()) {
2576 if (null == this.autoTimer) {
2577 this.flipSpeed = 2000;
2579 // $$$ Draw events currently cause layout problems when they occur during animation.
2580 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2581 // we workaround for now by not triggering immediate animation in that case.
2582 // See https://bugs.launchpad.net/gnubook/+bug/328327
2583 if (('rl' == this.pageProgression) && bComingFrom1up) {
2584 // don't flip immediately -- wait until timer fires
2587 this.flipFwdToIndex();
2590 $('#GBtoolbar .play').hide();
2591 $('#GBtoolbar .pause').show();
2592 this.autoTimer=setInterval(function(){
2593 if (self.animating) {return;}
2595 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2596 self.flipBackToIndex(1); // $$$ really what we want?
2598 self.flipFwdToIndex();
2607 //______________________________________________________________________________
2608 // Stop autoplay mode, allowing animations to finish
2609 GnuBook.prototype.autoStop = function() {
2610 if (null != this.autoTimer) {
2611 clearInterval(this.autoTimer);
2612 this.flipSpeed = 'fast';
2613 $('#GBtoolbar .pause').hide();
2614 $('#GBtoolbar .play').show();
2615 this.autoTimer = null;
2619 // stopFlipAnimations
2620 //______________________________________________________________________________
2621 // Immediately stop flip animations. Callbacks are triggered.
2622 GnuBook.prototype.stopFlipAnimations = function() {
2624 this.autoStop(); // Clear timers
2626 // Stop animation, clear queue, trigger callbacks
2627 if (this.leafEdgeTmp) {
2628 $(this.leafEdgeTmp).stop(false, true);
2630 jQuery.each(this.prefetchedImgs, function() {
2631 $(this).stop(false, true);
2634 // And again since animations also queued in callbacks
2635 if (this.leafEdgeTmp) {
2636 $(this.leafEdgeTmp).stop(false, true);
2638 jQuery.each(this.prefetchedImgs, function() {
2639 $(this).stop(false, true);
2644 // keyboardNavigationIsDisabled(event)
2645 // - returns true if keyboard navigation should be disabled for the event
2646 //______________________________________________________________________________
2647 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2648 if (event.target.tagName == "INPUT") {
2654 // gutterOffsetForIndex
2655 //______________________________________________________________________________
2657 // Returns the gutter offset for the spread containing the given index.
2658 // This function supports RTL
2659 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2661 // To find the offset of the gutter from the middle we calculate our percentage distance
2662 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2663 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2665 // But then again for RTL it's the opposite
2666 if ('rl' == this.pageProgression) {
2674 //______________________________________________________________________________
2675 // Returns the width of the leaf edge div for the page with index given
2676 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2677 // $$$ could there be single pixel rounding errors for L vs R?
2678 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2679 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2681 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2685 // jumpIndexForLeftEdgePageX
2686 //______________________________________________________________________________
2687 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2688 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2689 if ('rl' != this.pageProgression) {
2690 // LTR - flipping backward
2691 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2693 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2694 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2698 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2699 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2704 // jumpIndexForRightEdgePageX
2705 //______________________________________________________________________________
2706 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2707 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2708 if ('rl' != this.pageProgression) {
2710 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2711 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2714 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2715 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2720 GnuBook.prototype.initToolbar = function(mode, ui) {
2722 $("#GnuBook").append("<div id='GBtoolbar'>"
2723 + "<span id='GBtoolbarbuttons' style='float: right'>"
2724 + "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
2725 + "<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>"
2726 + "<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>"
2727 + "<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>"
2728 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
2732 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2733 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2734 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2735 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2736 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2737 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2740 + "<span id='#GBbooktitle'>"
2741 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
2745 this.updateToolbarZoom(this.reduce); // Pretty format
2747 if (ui == "embed") {
2748 $("#GnuBook a.logo").attr("target","_blank");
2751 // $$$ turn this into a member variable
2752 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2754 // We build in mode 2
2757 this.bindToolbarNavHandlers(jToolbar);
2759 // Setup tooltips -- later we could load these from a file for i18n
2760 var titles = { '.logo': 'Go to Archive.org',
2761 '.zoom_in': 'Zoom in',
2762 '.zoom_out': 'Zoom out',
2763 '.one_page_mode': 'One-page view',
2764 '.two_page_mode': 'Two-page view',
2765 '.print': 'Print this page',
2766 '.embed': 'Embed bookreader',
2767 '.book_left': 'Flip left',
2768 '.book_right': 'Flip right',
2769 '.book_up': 'Page up',
2770 '.book_down': 'Page down',
2773 '.book_top': 'First page',
2774 '.book_bottom': 'Last page'
2776 if ('rl' == this.pageProgression) {
2777 titles['.book_leftmost'] = 'Last page';
2778 titles['.book_rightmost'] = 'First page';
2780 titles['.book_leftmost'] = 'First page';
2781 titles['.book_rightmost'] = 'Last page';
2784 for (var icon in titles) {
2785 jToolbar.find(icon).attr('title', titles[icon]);
2788 // Hide mode buttons and autoplay if 2up is not available
2789 // $$$ if we end up with more than two modes we should show the applicable buttons
2790 if ( !this.canSwitchToMode(this.constMode2up) ) {
2791 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2794 // Switch to requested mode -- binds other click handlers
2795 this.switchToolbarMode(mode);
2800 // switchToolbarMode
2801 //______________________________________________________________________________
2802 // Update the toolbar for the given mode (changes navigation buttons)
2803 // $$$ we should soon split the toolbar out into its own module
2804 GnuBook.prototype.switchToolbarMode = function(mode) {
2807 $('#GBtoolbar .GBtoolbarmode2').hide();
2808 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2811 $('#GBtoolbar .GBtoolbarmode1').hide();
2812 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2816 // bindToolbarNavHandlers
2817 //______________________________________________________________________________
2818 // Binds the toolbar handlers
2819 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2821 jToolbar.find('.book_left').bind('click', function(e) {
2826 jToolbar.find('.book_right').bind('click', function(e) {
2831 jToolbar.find('.book_up').bind('click', function(e) {
2836 jToolbar.find('.book_down').bind('click', function(e) {
2841 jToolbar.find('.print').bind('click', function(e) {
2846 jToolbar.find('.embed').bind('click', function(e) {
2851 jToolbar.find('.play').bind('click', function(e) {
2856 jToolbar.find('.pause').bind('click', function(e) {
2861 jToolbar.find('.book_top').bind('click', function(e) {
2866 jToolbar.find('.book_bottom').bind('click', function(e) {
2871 jToolbar.find('.book_leftmost').bind('click', function(e) {
2876 jToolbar.find('.book_rightmost').bind('click', function(e) {
2882 // updateToolbarZoom(reduce)
2883 //______________________________________________________________________________
2884 // Update the displayed zoom factor based on reduction factor
2885 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2887 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2890 value = (100 / reduce).toFixed(2);
2891 // Strip trailing zeroes and decimal if all zeroes
2892 value = value.replace(/0+$/,'');
2893 value = value.replace(/\.$/,'');
2896 $('#GBzoom').text(value);
2899 // firstDisplayableIndex
2900 //______________________________________________________________________________
2901 // Returns the index of the first visible page, dependent on the mode.
2902 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2903 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2904 GnuBook.prototype.firstDisplayableIndex = function() {
2905 if (this.mode == 0) {
2908 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2912 // lastDisplayableIndex
2913 //______________________________________________________________________________
2914 // Returns the index of the last visible page, dependent on the mode.
2915 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2916 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2917 GnuBook.prototype.lastDisplayableIndex = function() {
2918 if (this.mode == 2) {
2919 if (this.lastDisplayableIndex2up === null) {
2920 // Calculate and cache
2921 var candidate = this.numLeafs - 1;
2922 for ( ; candidate >= 0; candidate--) {
2923 var spreadIndices = this.getSpreadIndices(candidate);
2924 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2928 this.lastDisplayableIndex2up = candidate;
2930 return this.lastDisplayableIndex2up;
2932 return this.numLeafs - 1;
2936 // shortTitle(maximumCharacters)
2938 // Returns a shortened version of the title with the maximum number of characters
2939 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2940 if (this.bookTitle.length < maximumCharacters) {
2941 return this.bookTitle;
2944 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2949 // Parameter related functions
2951 // updateFromParams(params)
2953 // Update ourselves from the params object.
2955 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2956 GnuBook.prototype.updateFromParams = function(params) {
2957 if ('undefined' != typeof(params.mode)) {
2958 this.switchMode(params.mode);
2962 if ('undefined' != typeof(params.searchTerm)) {
2963 if (this.searchTerm != params.searchTerm) {
2964 this.search(params.searchTerm);
2968 // $$$ process /zoom
2970 // We only respect page if index is not set
2971 if ('undefined' != typeof(params.index)) {
2972 if (params.index != this.currentIndex()) {
2973 this.jumpToIndex(params.index);
2975 } else if ('undefined' != typeof(params.page)) {
2976 // $$$ this assumes page numbers are unique
2977 if (params.page != this.getPageNum(this.currentIndex())) {
2978 this.jumpToPage(params.page);
2982 // $$$ process /region
2983 // $$$ process /highlight
2986 // paramsFromFragment(urlFragment)
2988 // Returns a object with configuration parametes from a URL fragment.
2990 // E.g paramsFromFragment(window.location.hash)
2991 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2992 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2996 // For convenience we allow an initial # character (as from window.location.hash)
2997 // but don't require it
2998 if (urlFragment.substr(0,1) == '#') {
2999 urlFragment = urlFragment.substr(1);
3002 // Simple #nn syntax
3003 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3004 if ( !isNaN(oldStyleLeafNum) ) {
3005 params.index = oldStyleLeafNum;
3007 // Done processing if using old-style syntax
3011 // Split into key-value pairs
3012 var urlArray = urlFragment.split('/');
3014 for (var i = 0; i < urlArray.length; i += 2) {
3015 urlHash[urlArray[i]] = urlArray[i+1];
3019 if ('1up' == urlHash['mode']) {
3020 params.mode = this.constMode1up;
3021 } else if ('2up' == urlHash['mode']) {
3022 params.mode = this.constMode2up;
3026 if ('undefined' != typeof(urlHash['page'])) {
3027 // page was set -- may not be int
3028 params.page = urlHash['page'];
3031 // $$$ process /region
3032 // $$$ process /search
3034 if (urlHash['search'] != undefined) {
3035 params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3038 // $$$ process /highlight
3043 // paramsFromCurrent()
3045 // Create a params object from the current parameters.
3046 GnuBook.prototype.paramsFromCurrent = function() {
3050 var pageNum = this.getPageNum(this.currentIndex());
3051 if ((pageNum === 0) || pageNum) {
3052 params.page = pageNum;
3055 params.index = this.currentIndex();
3056 params.mode = this.mode;
3062 if (this.searchHighlightVisible()) {
3063 params.searchTerm = this.searchTerm;
3069 // fragmentFromParams(params)
3071 // Create a fragment string from the params object.
3072 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3073 GnuBook.prototype.fragmentFromParams = function(params) {
3074 var separator = '/';
3078 if ('undefined' != typeof(params.page)) {
3079 fragments.push('page', params.page);
3081 // Don't have page numbering -- use index instead
3082 fragments.push('page', 'n' + params.index);
3089 if ('undefined' != typeof(params.mode)) {
3090 if (params.mode == this.constMode1up) {
3091 fragments.push('mode', '1up');
3092 } else if (params.mode == this.constMode2up) {
3093 fragments.push('mode', '2up');
3095 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3100 if (params.searchTerm) {
3101 fragments.push('search', params.searchTerm);
3104 return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3107 // getPageIndex(pageNum)
3109 // Returns the *highest* index the given page number, or undefined
3110 GnuBook.prototype.getPageIndex = function(pageNum) {
3111 var pageIndices = this.getPageIndices(pageNum);
3113 if (pageIndices.length > 0) {
3114 return pageIndices[pageIndices.length - 1];
3120 // getPageIndices(pageNum)
3122 // Returns an array (possibly empty) of the indices with the given page number
3123 GnuBook.prototype.getPageIndices = function(pageNum) {
3126 // Check for special "nXX" page number
3127 if (pageNum.slice(0,1) == 'n') {
3129 var pageIntStr = pageNum.slice(1, pageNum.length);
3130 var pageIndex = parseInt(pageIntStr);
3131 indices.push(pageIndex);
3134 // Do nothing... will run through page names and see if one matches
3139 for (i=0; i<this.numLeafs; i++) {
3140 if (this.getPageNum(i) == pageNum) {
3148 // getPageName(index)
3150 // Returns the name of the page as it should be displayed in the user interface
3151 GnuBook.prototype.getPageName = function(index) {
3152 return 'Page ' + this.getPageNum(index);
3155 // updateLocationHash
3157 // Update the location hash from the current parameters. Call this instead of manually
3158 // using window.location.replace
3159 GnuBook.prototype.updateLocationHash = function() {
3160 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3161 window.location.replace(newHash);
3163 // This is the variable checked in the timer. Only user-generated changes
3164 // to the URL will trigger the event.
3165 this.oldLocationHash = newHash;
3168 // startLocationPolling
3170 // Starts polling of window.location to see hash fragment changes
3171 GnuBook.prototype.startLocationPolling = function() {
3172 var self = this; // remember who I am
3173 self.oldLocationHash = window.location.hash;
3175 if (this.locationPollId) {
3176 clearInterval(this.locationPollID);
3177 this.locationPollId = null;
3180 this.locationPollId = setInterval(function() {
3181 var newHash = window.location.hash;
3182 if (newHash != self.oldLocationHash) {
3183 if (newHash != self.oldUserHash) { // Only process new user hash once
3184 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3186 // Queue change if animating
3187 if (self.animating) {
3189 self.animationFinishedCallback = function() {
3190 self.updateFromParams(self.paramsFromFragment(newHash));
3192 } else { // update immediately
3193 self.updateFromParams(self.paramsFromFragment(newHash));
3195 self.oldUserHash = newHash;
3203 // Returns true if we can switch to the requested mode
3204 GnuBook.prototype.canSwitchToMode = function(mode) {
3205 if (mode == this.constMode2up) {
3206 // check there are enough pages to display
3207 // $$$ this is a workaround for the mis-feature that we can't display
3208 // short books in 2up mode
3209 if (this.numLeafs < 6) {
3217 // searchHighlightVisible
3219 // Returns true if a search highlight is currently being displayed
3220 GnuBook.prototype.searchHighlightVisible = function() {
3221 if (this.constMode2up == this.mode) {
3222 if (this.searchResults[this.twoPage.currentIndexL]
3223 || this.searchResults[this.twoPage.currentIndexR]) {
3227 if (this.searchResults[this.currentIndex()]) {
3234 // Library functions
3236 clamp: function(value, min, max) {
3237 return Math.min(Math.max(value, min), max);
3240 getIFrameDocument: function(iframe) {
3241 // Adapted from http://xkr.us/articles/dom/iframe-document/
3242 var outer = (iframe.contentWindow || iframe.contentDocument);
3243 return (outer.document || outer);
3246 decodeURIComponentPlus: function(value) {
3247 // Decodes a URI component and converts '+' to ' '
3248 return decodeURIComponent(value).replace(/\+/g, ' ');
3251 encodeURIComponentPlus: function(value) {
3252 // Encodes a URI component and converts ' ' to '+'
3253 return encodeURIComponent(value).replace(/%20/g, '+');