2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GnuBook is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
31 // You must also add a numLeafs property before calling init().
36 this.mode = 1; //1 or 2
37 this.ui = 'full'; // UI mode
39 this.displayedIndices = [];
40 //this.indicesToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
45 this.animating = false;
47 this.autoTimer = null;
48 this.flipSpeed = 'fast';
50 this.twoPagePopUp = null;
51 this.leafEdgeTmp = null;
52 this.embedPopup = null;
54 this.searchResults = {};
56 this.firstIndex = null;
58 this.lastDisplayableIndex2up = null;
60 // We link to index.php to avoid redirect which breaks back button
61 this.logoURL = 'http://www.archive.org/index.php';
63 // Base URL for images
64 this.imagesBaseURL = '/bookreader/images/';
67 this.constMode1up = 1;
68 this.constMode2up = 2;
71 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
73 // Object to hold parameters related to 2up mode
75 coverInternalPadding: 10, // Width of cover
76 coverExternalPadding: 10, // Padding outside of cover
77 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
86 var startIndex = undefined;
88 // Find start index and mode if set in location hash
89 var params = this.paramsFromFragment(window.location.hash);
91 if ('undefined' != typeof(params.index)) {
92 startIndex = params.index;
93 } else if ('undefined' != typeof(params.page)) {
94 startIndex = this.getPageIndex(params.page);
97 if ('undefined' == typeof(startIndex)) {
98 if ('undefined' != typeof(this.titleLeaf)) {
99 startIndex = this.leafNumToIndex(this.titleLeaf);
103 if ('undefined' == typeof(startIndex)) {
107 if ('undefined' != typeof(params.mode)) {
108 this.mode = params.mode;
111 // Set document title -- may have already been set in enclosing html for
112 // search engine visibility
113 document.title = this.shortTitle(50);
115 // Sanitize parameters
116 if ( !this.canSwitchToMode( this.mode ) ) {
117 this.mode = this.constMode1up;
120 $("#GnuBook").empty();
121 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122 $("#GnuBook").append("<div id='GBcontainer'></div>");
123 $("#GBcontainer").append("<div id='GBpageview'></div>");
125 $("#GBcontainer").bind('scroll', this, function(e) {
129 this.setupKeyListeners();
130 this.startLocationPolling();
132 $(window).bind('resize', this, function(e) {
133 //console.log('resize!');
134 if (1 == e.data.mode) {
135 //console.log('centering 1page view');
136 e.data.centerPageView();
137 $('#GBpageview').empty()
138 e.data.displayedIndices = [];
139 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
142 //console.log('drawing 2 page view');
144 // We only need to prepare again in autofit (size of spread changes)
145 if (e.data.twoPage.autofit) {
146 e.data.prepareTwoPageView();
148 // Re-center if the scrollbars have disappeared
149 var center = e.data.twoPageGetViewCenter();
150 var doRecenter = false;
151 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
152 center.percentageX = 0.5;
155 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
156 center.percentageY = 0.5;
160 e.data.twoPageCenterView(center.percentageX, center.percentageY);
166 $('.GBpagediv1up').bind('mousedown', this, function(e) {
167 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
168 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
171 if (1 == this.mode) {
172 this.resizePageView();
173 this.firstIndex = startIndex;
174 this.jumpToIndex(startIndex);
176 //this.resizePageView();
178 this.displayedIndices=[0];
179 this.firstIndex = startIndex;
180 this.displayedIndices = [this.firstIndex];
181 //console.log('titleLeaf: %d', this.titleLeaf);
182 //console.log('displayedIndices: %s', this.displayedIndices);
183 this.prepareTwoPageView();
186 // Enact other parts of initial params
187 this.updateFromParams(params);
190 GnuBook.prototype.setupKeyListeners = function() {
203 // We use document here instead of window to avoid a bug in jQuery on IE7
204 $(document).keydown(function(e) {
206 // Keyboard navigation
210 // In 1up mode page scrolling is handled by browser
211 if (2 == self.mode) {
217 if (2 == self.mode) {
228 if (self.keyboardNavigationIsDisabled(e)) {
231 if (2 == self.mode) {
236 if (self.keyboardNavigationIsDisabled(e)) {
239 if (2 == self.mode) {
248 //______________________________________________________________________________
249 GnuBook.prototype.drawLeafs = function() {
250 if (1 == this.mode) {
251 this.drawLeafsOnePage();
253 this.drawLeafsTwoPage();
258 //______________________________________________________________________________
259 GnuBook.prototype.setDragHandler = function(div) {
260 div.dragging = false;
262 $(div).unbind('mousedown').bind('mousedown', function(e) {
263 //console.log('mousedown at ' + e.pageY);
265 this.dragging = true;
266 this.prevMouseX = e.pageX;
267 this.prevMouseY = e.pageY;
269 var startX = e.pageX;
270 var startY = e.pageY;
271 var startTop = $('#GBcontainer').attr('scrollTop');
272 var startLeft = $('#GBcontainer').attr('scrollLeft');
277 $(div).unbind('mousemove').bind('mousemove', function(ee) {
278 //console.log('mousemove ' + startY);
280 var offsetX = ee.pageX - this.prevMouseX;
281 var offsetY = ee.pageY - this.prevMouseY;
284 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
285 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
288 this.prevMouseX = ee.pageX;
289 this.prevMouseY = ee.pageY;
294 $(div).unbind('mouseup').bind('mouseup', function(ee) {
295 //console.log('mouseup');
297 this.dragging = false;
301 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
302 //console.log('mouseleave');
304 //$(this).unbind('mousemove mouseup');
305 this.dragging = false;
309 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
310 this.dragging = false;
314 // drawLeafsOnePage()
315 //______________________________________________________________________________
316 GnuBook.prototype.drawLeafsOnePage = function() {
317 //alert('drawing leafs!');
321 var scrollTop = $('#GBcontainer').attr('scrollTop');
322 var scrollBottom = scrollTop + $('#GBcontainer').height();
323 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
325 var indicesToDisplay = [];
330 for (i=0; i<this.numLeafs; i++) {
331 var height = parseInt(this.getPageHeight(i)/this.reduce);
333 leafBottom += height;
334 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
335 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
336 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
337 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
338 if (topInView | bottomInView | middleInView) {
339 //console.log('displayed: ' + this.displayedIndices);
340 //console.log('to display: ' + i);
341 indicesToDisplay.push(i);
343 leafTop += height +10;
347 var firstIndexToDraw = indicesToDisplay[0];
348 this.firstIndex = firstIndexToDraw;
350 // Update hash, but only if we're currently displaying a leaf
351 // Hack that fixes #365790
352 if (this.displayedIndices.length > 0) {
353 this.updateLocationHash();
356 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
358 indicesToDisplay.unshift(firstIndexToDraw);
361 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
362 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
363 indicesToDisplay.push(lastIndexToDraw+1);
368 for (i=0; i<firstIndexToDraw; i++) {
369 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
372 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
373 var viewWidth = $('#GBcontainer').attr('scrollWidth');
376 for (i=0; i<indicesToDisplay.length; i++) {
377 var index = indicesToDisplay[i];
378 var height = parseInt(this.getPageHeight(index)/this.reduce);
380 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
381 var width = parseInt(this.getPageWidth(index)/this.reduce);
382 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
383 var div = document.createElement("div");
384 div.className = 'GBpagediv1up';
385 div.id = 'pagediv'+index;
386 div.style.position = "absolute";
387 $(div).css('top', leafTop + 'px');
388 var left = (viewWidth-width)>>1;
389 if (left<0) left = 0;
390 $(div).css('left', left+'px');
391 $(div).css('width', width+'px');
392 $(div).css('height', height+'px');
393 //$(div).text('loading...');
395 this.setDragHandler(div);
397 $('#GBpageview').append(div);
399 var img = document.createElement("img");
400 img.src = this.getPageURI(index);
401 $(img).css('width', width+'px');
402 $(img).css('height', height+'px');
406 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
409 leafTop += height +10;
413 for (i=0; i<this.displayedIndices.length; i++) {
414 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
415 var index = this.displayedIndices[i];
416 //console.log('Removing leaf ' + index);
417 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
418 $('#pagediv'+index).remove();
420 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
424 this.displayedIndices = indicesToDisplay.slice();
425 this.updateSearchHilites();
427 if (null != this.getPageNum(firstIndexToDraw)) {
428 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
430 $("#GBpagenum").val('');
433 this.updateToolbarZoom(this.reduce);
437 // drawLeafsTwoPage()
438 //______________________________________________________________________________
439 GnuBook.prototype.drawLeafsTwoPage = function() {
440 var scrollTop = $('#GBtwopageview').attr('scrollTop');
441 var scrollBottom = scrollTop + $('#GBtwopageview').height();
443 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
445 var indexL = this.twoPage.currentIndexL;
446 var heightL = this.getPageHeight(indexL);
447 var widthL = this.getPageWidth(indexL);
449 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
450 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
451 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
452 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
453 //console.log(leafEdgeWidthL);
455 var middle = this.twoPage.middle; // $$$ getter instead?
456 var top = this.twoPageTop();
457 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
459 var scaledWL = this.getPageWidth2UP(indexL);
460 var gutter = this.twoPageGutter();
462 this.prefetchImg(indexL);
463 $(this.prefetchedImgs[indexL]).css({
464 position: 'absolute',
465 left: gutter-scaledWL+'px',
468 backgroundColor: 'rgb(234, 226, 205)',
469 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
470 width: scaledWL + 'px',
471 borderRight: '1px solid black',
473 }).appendTo('#GBtwopageview');
476 var indexR = this.twoPage.currentIndexR;
477 var heightR = this.getPageHeight(indexR);
478 var widthR = this.getPageWidth(indexR);
480 // $$$ should use getwidth2up?
481 //var scaledWR = this.twoPage.height*widthR/heightR;
482 var scaledWR = this.getPageWidth2UP(indexR);
483 this.prefetchImg(indexR);
484 $(this.prefetchedImgs[indexR]).css({
485 position: 'absolute',
489 backgroundColor: 'rgb(234, 226, 205)',
490 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
491 width: scaledWR + 'px',
492 borderLeft: '1px solid black',
494 }).appendTo('#GBtwopageview');
497 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
498 this.setClickHandlers();
499 this.twoPageSetCursor();
501 this.updatePageNumBox2UP();
502 this.updateToolbarZoom(this.reduce);
505 // updatePageNumBox2UP
506 //______________________________________________________________________________
507 GnuBook.prototype.updatePageNumBox2UP = function() {
508 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
509 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
511 $("#GBpagenum").val('');
513 this.updateLocationHash();
517 //______________________________________________________________________________
518 GnuBook.prototype.loadLeafs = function() {
522 if (null == this.timer) {
523 this.timer=setTimeout(function(){self.drawLeafs()},250);
525 clearTimeout(this.timer);
526 this.timer=setTimeout(function(){self.drawLeafs()},250);
532 // Pass 1 to zoom in, anything else to zoom out
533 //______________________________________________________________________________
534 GnuBook.prototype.zoom = function(direction) {
536 case this.constMode1up:
537 return this.zoom1up(direction);
538 case this.constMode2up:
539 return this.zoom2up(direction);
544 //______________________________________________________________________________
545 GnuBook.prototype.zoom1up = function(dir) {
546 if (2 == this.mode) { //can only zoom in 1-page mode
551 // $$$ with flexible zoom we could "snap" to /2 page reductions
552 // for better scaling
554 if (this.reduce <= 0.5) return;
555 this.reduce*=0.5; //zoom in
557 if (this.reduce >= 8) return;
558 this.reduce*=2; //zoom out
561 this.resizePageView();
563 $('#GBpageview').empty()
564 this.displayedIndices = [];
567 this.updateToolbarZoom(this.reduce);
571 //______________________________________________________________________________
572 GnuBook.prototype.resizePageView = function() {
575 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
576 var viewWidth = $('#GBcontainer').attr('clientWidth');
578 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
579 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
580 var oldPageViewHeight = $('#GBpageview').height();
581 var oldPageViewWidth = $('#GBpageview').width();
583 var oldCenterY = this.centerY1up();
584 var oldCenterX = this.centerX1up();
586 if (0 != oldPageViewHeight) {
587 var scrollRatio = oldCenterY / oldPageViewHeight;
592 for (i=0; i<this.numLeafs; i++) {
593 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
594 var width = parseInt(this.getPageWidth(i)/this.reduce);
595 if (width>viewWidth) viewWidth=width;
597 $('#GBpageview').height(viewHeight);
598 $('#GBpageview').width(viewWidth);
600 var newCenterY = scrollRatio*viewHeight;
601 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
602 $('#GBcontainer').attr('scrollTop', newTop);
604 // We use clientWidth here to avoid miscalculating due to scroll bar
605 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
606 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
607 newLeft = Math.max(newLeft, 0);
608 $('#GBcontainer').attr('scrollLeft', newLeft);
609 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
611 //this.centerPageView();
617 //______________________________________________________________________________
618 // Returns the current offset of the viewport center in scaled document coordinates.
619 GnuBook.prototype.centerX1up = function() {
621 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
622 centerX = $('#GBpageview').width();
624 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
626 centerX = Math.floor(centerX);
631 //______________________________________________________________________________
632 // Returns the current offset of the viewport center in scaled document coordinates.
633 GnuBook.prototype.centerY1up = function() {
634 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
635 return Math.floor(centerY);
639 //______________________________________________________________________________
640 GnuBook.prototype.centerPageView = function() {
642 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
643 var clientWidth = $('#GBcontainer').attr('clientWidth');
644 //console.log('sW='+scrollWidth+' cW='+clientWidth);
645 if (scrollWidth > clientWidth) {
646 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
651 // zoom2up(direction)
652 //______________________________________________________________________________
653 GnuBook.prototype.zoom2up = function(direction) {
655 // Hard stop autoplay
656 this.stopFlipAnimations();
658 // Get new zoom state
659 var newZoom = this.twoPageNextReduce(this.reduce, direction);
660 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
663 this.twoPage.autofit = newZoom.autofit;
664 this.reduce = newZoom.reduce;
666 // Preserve view center position
667 var oldCenter = this.twoPageGetViewCenter();
669 // Prepare view with new center to minimize visual glitches
670 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
674 // quantizeReduce(reduce)
675 //______________________________________________________________________________
676 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
677 GnuBook.prototype.quantizeReduce = function(reduce) {
678 var quantized = this.reductionFactors[0];
679 var distance = Math.abs(reduce - quantized);
680 for (var i = 1; i < this.reductionFactors.length; i++) {
681 newDistance = Math.abs(reduce - this.reductionFactors[i]);
682 if (newDistance < distance) {
683 distance = newDistance;
684 quantized = this.reductionFactors[i];
691 // twoPageNextReduce()
692 //______________________________________________________________________________
693 // Returns the next reduction level
694 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
696 var autofitReduce = this.twoPageGetAutofitReduce();
698 if (0 == direction) { // autofit
699 result.autofit = true;
700 result.reduce = autofitReduce;
702 } else if (1 == direction) { // zoom in
703 var newReduce = this.reductionFactors[0];
705 for (var i = 1; i < this.reductionFactors.length; i++) {
706 if (this.reductionFactors[i] < reduce) {
707 newReduce = this.reductionFactors[i];
711 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
713 result.autofit = true;
714 result.reduce = autofitReduce;
716 result.autofit = false;
717 result.reduce = newReduce;
721 var lastIndex = this.reductionFactors.length - 1;
722 var newReduce = this.reductionFactors[lastIndex];
724 for (var i = lastIndex; i >= 0; i--) {
725 if (this.reductionFactors[i] > reduce) {
726 newReduce = this.reductionFactors[i];
730 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
732 result.autofit = true;
733 result.reduce = autofitReduce;
735 result.autofit = false;
736 result.reduce = newReduce;
744 //______________________________________________________________________________
745 // Attempts to jump to page. Returns true if page could be found, false otherwise.
746 GnuBook.prototype.jumpToPage = function(pageNum) {
748 var pageIndex = this.getPageIndex(pageNum);
750 if ('undefined' != typeof(pageIndex)) {
753 this.jumpToIndex(pageIndex);
754 $('#GBcontainer').attr('scrollTop', leafTop);
763 //______________________________________________________________________________
764 GnuBook.prototype.jumpToIndex = function(index) {
766 if (2 == this.mode) {
769 // By checking against min/max we do nothing if requested index
771 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
772 this.flipBackToIndex(index);
773 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
774 this.flipFwdToIndex(index);
781 for (i=0; i<index; i++) {
782 h = parseInt(this.getPageHeight(i)/this.reduce);
783 leafTop += h + this.padding;
785 //$('#GBcontainer').attr('scrollTop', leafTop);
786 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
793 //______________________________________________________________________________
794 GnuBook.prototype.switchMode = function(mode) {
796 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
798 if (mode == this.mode) return;
800 if (!this.canSwitchToMode(mode)) {
805 this.removeSearchHilites();
809 this.switchToolbarMode(mode);
811 // $$$ TODO preserve center of view when switching between mode
812 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
815 this.reduce = this.quantizeReduce(this.reduce);
816 this.prepareOnePageView();
818 this.twoPage.autofit = false; // Take zoom level from other mode
819 this.reduce = this.quantizeReduce(this.reduce);
820 this.prepareTwoPageView();
821 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
826 //prepareOnePageView()
827 //______________________________________________________________________________
828 GnuBook.prototype.prepareOnePageView = function() {
830 // var startLeaf = this.displayedIndices[0];
831 var startLeaf = this.currentIndex();
833 $('#GBcontainer').empty();
834 $('#GBcontainer').css({
839 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
841 this.resizePageView();
843 this.jumpToIndex(startLeaf);
844 this.displayedIndices = [];
846 this.drawLeafsOnePage();
848 // Bind mouse handlers
849 // Disable mouse click to avoid selected/highlighted page images - bug 354239
850 gbPageView.bind('mousedown', function(e) {
851 // $$$ check here for right-click and don't disable. Also use jQuery style
852 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
855 // Special hack for IE7
856 gbPageView[0].onselectstart = function(e) { return false; };
859 // prepareTwoPageView()
860 //______________________________________________________________________________
861 // Some decisions about two page view:
863 // Both pages will be displayed at the same height, even if they were different physical/scanned
864 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
865 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
866 // aspect ratio to determine the height.
868 // The two page view div is resized to keep the middle of the book in the middle of the div
869 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
870 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
871 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
872 $('#GBcontainer').empty();
873 $('#GBcontainer').css('overflow', 'auto');
875 // We want to display two facing pages. We may be missing
876 // one side of the spread because it is the first/last leaf,
877 // foldouts, missing pages, etc
879 //var targetLeaf = this.displayedIndices[0];
880 var targetLeaf = this.firstIndex;
882 if (targetLeaf < this.firstDisplayableIndex()) {
883 targetLeaf = this.firstDisplayableIndex();
886 if (targetLeaf > this.lastDisplayableIndex()) {
887 targetLeaf = this.lastDisplayableIndex();
890 this.twoPage.currentIndexL = null;
891 this.twoPage.currentIndexR = null;
892 this.pruneUnusedImgs();
894 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
895 this.twoPage.currentIndexL = currentSpreadIndices[0];
896 this.twoPage.currentIndexR = currentSpreadIndices[1];
897 this.firstIndex = this.twoPage.currentIndexL;
899 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
901 //console.dir(this.twoPage);
903 // Add the two page view
904 // $$$ Can we get everything set up and then append?
905 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
907 // $$$ calculate first then set
908 $('#GBtwopageview').css( {
909 height: this.twoPage.totalHeight + 'px',
910 width: this.twoPage.totalWidth + 'px',
914 // If there will not be scrollbars (e.g. when zooming out) we center the book
915 // since otherwise the book will be stuck off-center
916 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
917 centerPercentageX = 0.5;
919 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
920 centerPercentageY = 0.5;
923 this.twoPageCenterView(centerPercentageX, centerPercentageY);
925 this.twoPage.coverDiv = document.createElement('div');
926 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
927 border: '1px solid rgb(68, 25, 17)',
928 width: this.twoPage.bookCoverDivWidth + 'px',
929 height: this.twoPage.bookCoverDivHeight+'px',
930 visibility: 'visible',
931 position: 'absolute',
932 backgroundColor: '#663929',
933 left: this.twoPage.bookCoverDivLeft + 'px',
934 top: this.twoPage.bookCoverDivTop+'px',
935 MozBorderRadiusTopleft: '7px',
936 MozBorderRadiusTopright: '7px',
937 MozBorderRadiusBottomright: '7px',
938 MozBorderRadiusBottomleft: '7px'
939 }).appendTo('#GBtwopageview');
941 this.leafEdgeR = document.createElement('div');
942 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
943 $(this.leafEdgeR).css({
944 borderStyle: 'solid solid solid none',
945 borderColor: 'rgb(51, 51, 34)',
946 borderWidth: '1px 1px 1px 0px',
947 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
948 width: this.twoPage.leafEdgeWidthR + 'px',
949 height: this.twoPage.height-1 + 'px',
951 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
952 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
954 }).appendTo('#GBtwopageview');
956 this.leafEdgeL = document.createElement('div');
957 this.leafEdgeL.className = 'leafEdgeL';
958 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
959 borderStyle: 'solid none solid solid',
960 borderColor: 'rgb(51, 51, 34)',
961 borderWidth: '1px 0px 1px 1px',
962 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
963 width: this.twoPage.leafEdgeWidthL + 'px',
964 height: this.twoPage.height-1 + 'px',
965 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
966 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
968 }).appendTo('#GBtwopageview');
970 div = document.createElement('div');
971 $(div).attr('id', 'GBbookspine').css({
972 border: '1px solid rgb(68, 25, 17)',
973 width: this.twoPage.bookSpineDivWidth+'px',
974 height: this.twoPage.bookSpineDivHeight+'px',
975 position: 'absolute',
976 backgroundColor: 'rgb(68, 25, 17)',
977 left: this.twoPage.bookSpineDivLeft+'px',
978 top: this.twoPage.bookSpineDivTop+'px'
979 }).appendTo('#GBtwopageview');
981 this.prepareTwoPagePopUp();
983 this.displayedIndices = [];
985 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
986 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
988 this.drawLeafsTwoPage();
989 this.updateSearchHilites2UP();
990 this.updateToolbarZoom(this.reduce);
995 // prepareTwoPagePopUp()
997 // This function prepares the "View Page n" popup that shows while the mouse is
998 // over the left/right "stack of sheets" edges. It also binds the mouse
999 // events for these divs.
1000 //______________________________________________________________________________
1001 GnuBook.prototype.prepareTwoPagePopUp = function() {
1003 this.twoPagePopUp = document.createElement('div');
1004 $(this.twoPagePopUp).css({
1005 border: '1px solid black',
1007 position: 'absolute',
1008 fontFamily: 'sans-serif',
1011 backgroundColor: 'rgb(255, 255, 238)',
1013 }).appendTo('#GBcontainer');
1014 $(this.twoPagePopUp).hide();
1016 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1017 $(e.data.twoPagePopUp).show();
1020 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1021 $(e.data.twoPagePopUp).hide();
1024 $(this.leafEdgeL).bind('click', this, function(e) {
1026 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1027 e.data.jumpToIndex(jumpIndex);
1030 $(this.leafEdgeR).bind('click', this, function(e) {
1032 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1033 e.data.jumpToIndex(jumpIndex);
1036 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1038 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1039 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1041 // $$$ TODO: Make sure popup is positioned so that it is in view
1042 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1043 $(e.data.twoPagePopUp).css({
1044 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1045 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1049 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1051 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1052 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1054 // $$$ TODO: Make sure popup is positioned so that it is in view
1055 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1056 $(e.data.twoPagePopUp).css({
1057 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1058 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1063 // calculateSpreadSize()
1064 //______________________________________________________________________________
1065 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1066 // this.twoPage.currentIndexR
1067 // This function sets this.twoPage.height, twoPage.width
1069 GnuBook.prototype.calculateSpreadSize = function() {
1071 var firstIndex = this.twoPage.currentIndexL;
1072 var secondIndex = this.twoPage.currentIndexR;
1073 //console.log('first page is ' + firstIndex);
1075 // Calculate page sizes and total leaf width
1077 if ( this.twoPage.autofit) {
1078 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1080 // set based on reduction factor
1081 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1084 // Both pages together
1085 this.twoPage.height = spreadSize.height;
1086 this.twoPage.width = spreadSize.width;
1089 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1090 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1093 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1094 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1095 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1099 // The width of the book cover div. The combined width of both pages, twice the width
1100 // of the book cover internal padding (2*10) and the page edges
1101 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1102 // The height of the book cover div
1103 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1106 // We calculate the total width and height for the div so that we can make the book
1108 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1109 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1110 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1111 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1112 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1113 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1115 // We want to minimize the unused space in two-up mode (maximize the amount of page
1116 // shown). We give width to the leaf edges and these widths change (though the sum
1117 // of the two remains constant) as we flip through the book. With the book
1118 // cover centered and fixed in the GBcontainer div the page images will meet
1119 // at the "gutter" which is generally offset from the center.
1120 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1121 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1123 // The left edge of the book cover moves depending on the width of the pages
1124 // $$$ change to getter
1125 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1126 // The top edge of the book cover stays a fixed distance from the top
1127 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1130 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1131 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1132 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1135 this.reduce = spreadSize.reduce; // $$$ really set this here?
1138 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1141 // We check which page is closest to a "normal" page and use that to set the height
1142 // for both pages. This means that foldouts and other odd size pages will be displayed
1143 // smaller than the nominal zoom amount.
1144 var canon5Dratio = 1.5;
1147 height: this.getPageHeight(firstIndex),
1148 width: this.getPageWidth(firstIndex)
1152 height: this.getPageHeight(secondIndex),
1153 width: this.getPageWidth(secondIndex)
1156 var firstIndexRatio = first.height / first.width;
1157 var secondIndexRatio = second.height / second.width;
1158 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1161 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1162 ratio = firstIndexRatio;
1163 //console.log('using firstIndexRatio ' + ratio);
1165 ratio = secondIndexRatio;
1166 //console.log('using secondIndexRatio ' + ratio);
1169 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1170 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1171 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1173 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1174 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1176 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1177 ideal.width -= 10; // $$$ fudge factor
1178 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1179 ideal.height -= 20; // fudge factor
1180 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1182 if (ideal.height/ratio <= ideal.width) {
1184 ideal.width = parseInt(ideal.height/ratio);
1187 ideal.height = parseInt(ideal.width*ratio);
1190 // $$$ check this logic with large spreads
1191 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1196 // getSpreadSizeFromReduce()
1197 //______________________________________________________________________________
1198 // Returns the spread size calculated from the reduction factor for the given pages
1199 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1200 var spreadSize = {};
1201 // $$$ Scale this based on reduce?
1202 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1203 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1204 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1206 // $$$ Possibly incorrect -- we should make height "dominant"
1207 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1208 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1209 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1210 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1211 spreadSize.reduce = reduce;
1216 // twoPageGetAutofitReduce()
1217 //______________________________________________________________________________
1218 // Returns the current ideal reduction factor
1219 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1220 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1221 return spreadSize.reduce;
1224 // twoPageSetCursor()
1225 //______________________________________________________________________________
1226 // Set the cursor for two page view
1227 GnuBook.prototype.twoPageSetCursor = function() {
1228 // console.log('setting cursor');
1229 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1230 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1231 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1232 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1234 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1235 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1240 //______________________________________________________________________________
1241 // Returns the currently active index.
1242 GnuBook.prototype.currentIndex = function() {
1243 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1244 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1245 return this.firstIndex;
1247 throw 'currentIndex called for unimplemented mode ' + this.mode;
1252 //______________________________________________________________________________
1253 // Flip the right page over onto the left
1254 GnuBook.prototype.right = function() {
1255 if ('rl' != this.pageProgression) {
1265 //______________________________________________________________________________
1266 // Flip to the rightmost page
1267 GnuBook.prototype.rightmost = function() {
1268 if ('rl' != this.pageProgression) {
1276 //______________________________________________________________________________
1277 // Flip the left page over onto the right.
1278 GnuBook.prototype.left = function() {
1279 if ('rl' != this.pageProgression) {
1289 //______________________________________________________________________________
1290 // Flip to the leftmost page
1291 GnuBook.prototype.leftmost = function() {
1292 if ('rl' != this.pageProgression) {
1300 //______________________________________________________________________________
1301 GnuBook.prototype.next = function() {
1302 if (2 == this.mode) {
1304 this.flipFwdToIndex(null);
1306 if (this.firstIndex < this.lastDisplayableIndex()) {
1307 this.jumpToIndex(this.firstIndex+1);
1313 //______________________________________________________________________________
1314 GnuBook.prototype.prev = function() {
1315 if (2 == this.mode) {
1317 this.flipBackToIndex(null);
1319 if (this.firstIndex >= 1) {
1320 this.jumpToIndex(this.firstIndex-1);
1325 GnuBook.prototype.first = function() {
1326 if (2 == this.mode) {
1327 this.jumpToIndex(2);
1330 this.jumpToIndex(0);
1334 GnuBook.prototype.last = function() {
1335 if (2 == this.mode) {
1336 this.jumpToIndex(this.lastDisplayableIndex());
1339 this.jumpToIndex(this.lastDisplayableIndex());
1343 // flipBackToIndex()
1344 //______________________________________________________________________________
1345 // to flip back one spread, pass index=null
1346 GnuBook.prototype.flipBackToIndex = function(index) {
1347 if (1 == this.mode) return;
1349 var leftIndex = this.twoPage.currentIndexL;
1351 // $$$ Need to change this to be able to see first spread.
1352 // See https://bugs.launchpad.net/gnubook/+bug/296788
1353 if (leftIndex <= 2) return;
1354 if (this.animating) return;
1356 if (null != this.leafEdgeTmp) {
1357 alert('error: leafEdgeTmp should be null!');
1361 if (null == index) {
1362 index = leftIndex-2;
1364 //if (index<0) return;
1366 var previousIndices = this.getSpreadIndices(index);
1368 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1372 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1374 this.animating = true;
1376 if ('rl' != this.pageProgression) {
1377 // Assume LTR and we are going backward
1378 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1379 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1381 // RTL and going backward
1382 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1383 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1387 // flipLeftToRight()
1388 //______________________________________________________________________________
1389 // Flips the page on the left towards the page on the right
1390 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1392 var leftLeaf = this.twoPage.currentIndexL;
1394 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1395 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1396 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1398 var currWidthL = this.getPageWidth2UP(leftLeaf);
1399 var newWidthL = this.getPageWidth2UP(newIndexL);
1400 var newWidthR = this.getPageWidth2UP(newIndexR);
1402 var top = this.twoPageTop();
1403 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1405 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1406 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1408 //animation strategy:
1409 // 0. remove search highlight, if any.
1410 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1411 // of the left leaf and where the user clicked in the leaf edge.
1412 // Note that if this function was triggered by left() and not a
1413 // mouse click, the width of leafEdgeTmp is very small (zero px).
1414 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1415 // leftLeaf to width=0.
1416 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1417 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1418 // its new full width.
1419 // 4. After step 3 is finished, do the following:
1420 // - remove leafEdgeTmp from the dom.
1421 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1422 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1423 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1424 // and width=newLeafEdgeWidthL.
1425 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1426 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1427 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1428 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1429 // - prefetch new adjacent leafs.
1430 // - set up click handlers for both new left and right leafs.
1431 // - redraw the search highlight.
1432 // - update the pagenum box and the url.
1435 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1437 this.leafEdgeTmp = document.createElement('div');
1438 $(this.leafEdgeTmp).css({
1439 borderStyle: 'solid none solid solid',
1440 borderColor: 'rgb(51, 51, 34)',
1441 borderWidth: '1px 0px 1px 1px',
1442 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1443 width: leafEdgeTmpW + 'px',
1444 height: this.twoPage.height-1 + 'px',
1445 left: leftEdgeTmpLeft + 'px',
1447 position: 'absolute',
1449 }).appendTo('#GBtwopageview');
1451 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1452 $(this.leafEdgeL).css({
1453 width: newLeafEdgeWidthL+'px',
1454 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1457 // Left gets the offset of the current left leaf from the document
1458 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1459 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1460 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1462 // We change the left leaf to right positioning
1463 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1464 $(this.prefetchedImgs[leftLeaf]).css({
1469 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1470 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1474 this.removeSearchHilites();
1476 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1477 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1479 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1480 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1482 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1483 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1484 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1486 $(self.leafEdgeR).css({
1487 // Moves the right leaf edge
1488 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1489 left: gutter+newWidthR+'px'
1492 $(self.leafEdgeL).css({
1493 // Moves and resizes the left leaf edge
1494 width: newLeafEdgeWidthL+'px',
1495 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1498 // Resizes the brown border div
1499 $(self.twoPage.coverDiv).css({
1500 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1501 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1504 $(self.leafEdgeTmp).remove();
1505 self.leafEdgeTmp = null;
1507 self.twoPage.currentIndexL = newIndexL;
1508 self.twoPage.currentIndexR = newIndexR;
1509 self.firstIndex = self.twoPage.currentIndexL;
1510 self.displayedIndices = [newIndexL, newIndexR];
1511 self.setClickHandlers();
1512 self.twoPageSetCursor();
1513 self.pruneUnusedImgs();
1515 self.animating = false;
1517 self.updateSearchHilites2UP();
1518 self.updatePageNumBox2UP();
1520 if (self.animationFinishedCallback) {
1521 self.animationFinishedCallback();
1522 self.animationFinishedCallback = null;
1530 //______________________________________________________________________________
1531 // Whether we flip left or right is dependent on the page progression
1532 // to flip forward one spread, pass index=null
1533 GnuBook.prototype.flipFwdToIndex = function(index) {
1535 if (this.animating) return;
1537 if (null != this.leafEdgeTmp) {
1538 alert('error: leafEdgeTmp should be null!');
1542 if (null == index) {
1543 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1545 if (index > this.lastDisplayableIndex()) return;
1547 this.animating = true;
1549 var nextIndices = this.getSpreadIndices(index);
1551 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1553 if ('rl' != this.pageProgression) {
1554 // We did not specify RTL
1555 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1556 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1559 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1560 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1564 // flipRightToLeft(nextL, nextR, gutter)
1565 // $$$ better not to have to pass gutter in
1566 //______________________________________________________________________________
1567 // Flip from left to right and show the nextL and nextR indices on those sides
1568 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1569 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1570 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1571 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1572 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1574 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1576 var top = this.twoPageTop();
1577 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1579 var middle = this.twoPage.middle;
1580 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1582 this.leafEdgeTmp = document.createElement('div');
1583 $(this.leafEdgeTmp).css({
1584 borderStyle: 'solid none solid solid',
1585 borderColor: 'rgb(51, 51, 34)',
1586 borderWidth: '1px 0px 1px 1px',
1587 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1588 width: leafEdgeTmpW + 'px',
1589 height: this.twoPage.height-1 + 'px',
1590 left: gutter+scaledW+'px',
1592 position: 'absolute',
1594 }).appendTo('#GBtwopageview');
1596 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1597 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1599 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1600 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1601 var newWidthL = this.getPageWidth2UP(newIndexL);
1602 var newWidthR = this.getPageWidth2UP(newIndexR);
1604 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1606 var self = this; // closure-tastic!
1608 var speed = this.flipSpeed;
1610 this.removeSearchHilites();
1612 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1613 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1614 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1615 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1616 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1618 $(self.leafEdgeL).css({
1619 width: newLeafEdgeWidthL+'px',
1620 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1623 // Resizes the book cover
1624 $(self.twoPage.coverDiv).css({
1625 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1626 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1629 $(self.leafEdgeTmp).remove();
1630 self.leafEdgeTmp = null;
1632 self.twoPage.currentIndexL = newIndexL;
1633 self.twoPage.currentIndexR = newIndexR;
1634 self.firstIndex = self.twoPage.currentIndexL;
1635 self.displayedIndices = [newIndexL, newIndexR];
1636 self.setClickHandlers();
1637 self.twoPageSetCursor();
1638 self.pruneUnusedImgs();
1640 self.animating = false;
1643 self.updateSearchHilites2UP();
1644 self.updatePageNumBox2UP();
1646 if (self.animationFinishedCallback) {
1647 self.animationFinishedCallback();
1648 self.animationFinishedCallback = null;
1655 //______________________________________________________________________________
1656 GnuBook.prototype.setClickHandlers = function() {
1658 // $$$ TODO don't set again if already set
1659 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1664 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1670 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1671 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1675 //______________________________________________________________________________
1676 GnuBook.prototype.prefetchImg = function(index) {
1677 if (undefined == this.prefetchedImgs[index]) {
1678 //console.log('prefetching ' + index);
1679 var img = document.createElement("img");
1680 img.src = this.getPageURI(index);
1681 this.prefetchedImgs[index] = img;
1686 // prepareFlipLeftToRight()
1688 //______________________________________________________________________________
1690 // Prepare to flip the left page towards the right. This corresponds to moving
1691 // backward when the page progression is left to right.
1692 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1694 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1696 this.prefetchImg(prevL);
1697 this.prefetchImg(prevR);
1699 var height = this.getPageHeight(prevL);
1700 var width = this.getPageWidth(prevL);
1701 var middle = this.twoPage.middle;
1702 var top = this.twoPageTop();
1703 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1705 // The gutter is the dividing line between the left and right pages.
1706 // It is offset from the middle to create the illusion of thickness to the pages
1707 var gutter = middle + this.gutterOffsetForIndex(prevL);
1709 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1710 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1711 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1713 $(this.prefetchedImgs[prevL]).css({
1714 position: 'absolute',
1715 left: gutter-scaledW+'px',
1716 right: '', // clear right property
1718 backgroundColor: 'rgb(234, 226, 205)',
1719 height: this.twoPage.height,
1720 width: scaledW+'px',
1721 borderRight: '1px solid black',
1725 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1727 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1729 $(this.prefetchedImgs[prevR]).css({
1730 position: 'absolute',
1734 backgroundColor: 'rgb(234, 226, 205)',
1735 height: this.twoPage.height,
1737 borderLeft: '1px solid black',
1741 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1745 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1746 // prepareFlipRightToLeft()
1747 //______________________________________________________________________________
1748 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1750 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1753 this.prefetchImg(nextL);
1754 this.prefetchImg(nextR);
1756 var height = this.getPageHeight(nextR);
1757 var width = this.getPageWidth(nextR);
1758 var middle = this.twoPage.middle;
1759 var top = this.twoPageTop();
1760 var scaledW = this.twoPage.height*width/height;
1762 var gutter = middle + this.gutterOffsetForIndex(nextL);
1764 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1765 $(this.prefetchedImgs[nextR]).css({
1766 position: 'absolute',
1769 backgroundColor: 'rgb(234, 226, 205)',
1770 height: this.twoPage.height,
1771 width: scaledW+'px',
1772 borderLeft: '1px solid black',
1776 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1778 height = this.getPageHeight(nextL);
1779 width = this.getPageWidth(nextL);
1780 scaledW = this.twoPage.height*width/height;
1782 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1783 $(this.prefetchedImgs[nextL]).css({
1784 position: 'absolute',
1785 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1787 backgroundColor: 'rgb(234, 226, 205)',
1788 height: this.twoPage.height,
1789 width: 0+'px', // Start at 0 width, then grow to the left
1790 borderRight: '1px solid black',
1794 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1798 // getNextLeafs() -- NOT RTL AWARE
1799 //______________________________________________________________________________
1800 // GnuBook.prototype.getNextLeafs = function(o) {
1801 // //TODO: we might have two left or two right leafs in a row (damaged book)
1802 // //For now, assume that leafs are contiguous.
1804 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1805 // o.L = this.twoPage.currentIndexL+2;
1806 // o.R = this.twoPage.currentIndexL+3;
1809 // getprevLeafs() -- NOT RTL AWARE
1810 //______________________________________________________________________________
1811 // GnuBook.prototype.getPrevLeafs = function(o) {
1812 // //TODO: we might have two left or two right leafs in a row (damaged book)
1813 // //For now, assume that leafs are contiguous.
1815 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1816 // o.L = this.twoPage.currentIndexL-2;
1817 // o.R = this.twoPage.currentIndexL-1;
1820 // pruneUnusedImgs()
1821 //______________________________________________________________________________
1822 GnuBook.prototype.pruneUnusedImgs = function() {
1823 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1824 for (var key in this.prefetchedImgs) {
1825 //console.log('key is ' + key);
1826 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1827 //console.log('removing key '+ key);
1828 $(this.prefetchedImgs[key]).remove();
1830 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1831 //console.log('deleting key '+ key);
1832 delete this.prefetchedImgs[key];
1838 //______________________________________________________________________________
1839 GnuBook.prototype.prefetch = function() {
1841 var lim = this.twoPage.currentIndexL-4;
1843 lim = Math.max(lim, 0);
1844 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1845 this.prefetchImg(i);
1848 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1849 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1850 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1851 this.prefetchImg(i);
1856 // getPageWidth2UP()
1857 //______________________________________________________________________________
1858 GnuBook.prototype.getPageWidth2UP = function(index) {
1859 // We return the width based on the dominant height
1860 var height = this.getPageHeight(index);
1861 var width = this.getPageWidth(index);
1862 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1866 //______________________________________________________________________________
1867 GnuBook.prototype.search = function(term) {
1868 $('#GnuBookSearchScript').remove();
1869 var script = document.createElement("script");
1870 script.setAttribute('id', 'GnuBookSearchScript');
1871 script.setAttribute("type", "text/javascript");
1872 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1873 document.getElementsByTagName('head')[0].appendChild(script);
1874 $('#GnuBookSearchResults').html('Searching...');
1877 // GBSearchCallback()
1878 //______________________________________________________________________________
1879 GnuBook.prototype.GBSearchCallback = function(txt) {
1881 if (jQuery.browser.msie) {
1882 var dom=new ActiveXObject("Microsoft.XMLDOM");
1886 var parser = new DOMParser();
1887 var dom = parser.parseFromString(txt, "text/xml");
1890 $('#GnuBookSearchResults').empty();
1891 $('#GnuBookSearchResults').append('<ul>');
1893 for (var key in this.searchResults) {
1894 if (null != this.searchResults[key].div) {
1895 $(this.searchResults[key].div).remove();
1897 delete this.searchResults[key];
1900 var pages = dom.getElementsByTagName('PAGE');
1902 if (0 == pages.length) {
1903 // $$$ it would be nice to echo the (sanitized) search result here
1904 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1906 for (var i = 0; i < pages.length; i++){
1907 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1910 var re = new RegExp (/_(\d{4})/);
1911 var reMatch = re.exec(pages[i].getAttribute('file'));
1912 var index = parseInt(reMatch[1], 10);
1913 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1915 var children = pages[i].childNodes;
1917 for (var j=0; j<children.length; j++) {
1918 //console.log(j + ' - ' + children[j].nodeName);
1919 //console.log(children[j].firstChild.nodeValue);
1920 if ('CONTEXT' == children[j].nodeName) {
1921 context += children[j].firstChild.nodeValue;
1922 } else if ('WORD' == children[j].nodeName) {
1923 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1925 var index = this.leafNumToIndex(index);
1926 if (null != index) {
1927 //coordinates are [left, bottom, right, top, [baseline]]
1928 //we'll skip baseline for now...
1929 var coords = children[j].getAttribute('coords').split(',',4);
1930 if (4 == coords.length) {
1931 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1936 var pageName = this.getPageName(index);
1937 //TODO: remove hardcoded instance name
1938 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1941 $('#GnuBookSearchResults').append('</ul>');
1943 this.updateSearchHilites();
1946 // updateSearchHilites()
1947 //______________________________________________________________________________
1948 GnuBook.prototype.updateSearchHilites = function() {
1949 if (2 == this.mode) {
1950 this.updateSearchHilites2UP();
1952 this.updateSearchHilites1UP();
1956 // showSearchHilites1UP()
1957 //______________________________________________________________________________
1958 GnuBook.prototype.updateSearchHilites1UP = function() {
1960 for (var key in this.searchResults) {
1962 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1963 var result = this.searchResults[key];
1964 if(null == result.div) {
1965 result.div = document.createElement('div');
1966 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1967 //console.log('appending ' + key);
1970 width: (result.r-result.l)/this.reduce + 'px',
1971 height: (result.b-result.t)/this.reduce + 'px',
1972 left: (result.l)/this.reduce + 'px',
1973 top: (result.t)/this.reduce +'px'
1977 //console.log(key + ' not displayed');
1978 this.searchResults[key].div=null;
1984 //______________________________________________________________________________
1985 // Returns the position of the gutter (line between the page images)
1986 GnuBook.prototype.twoPageGutter = function() {
1987 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1991 //______________________________________________________________________________
1992 // Returns the offset for the top of the page images
1993 GnuBook.prototype.twoPageTop = function() {
1994 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1997 // twoPageCoverWidth()
1998 //______________________________________________________________________________
1999 // Returns the width of the cover div given the total page width
2000 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2001 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2004 // twoPageGetViewCenter()
2005 //______________________________________________________________________________
2006 // Returns the percentage offset into twopageview div at the center of container div
2007 // { percentageX: float, percentageY: float }
2008 GnuBook.prototype.twoPageGetViewCenter = function() {
2011 var containerOffset = $('#GBcontainer').offset();
2012 var viewOffset = $('#GBtwopageview').offset();
2013 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2014 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2019 // twoPageCenterView(percentageX, percentageY)
2020 //______________________________________________________________________________
2021 // Centers the point given by percentage from left,top of twopageview
2022 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2023 if ('undefined' == typeof(percentageX)) {
2026 if ('undefined' == typeof(percentageY)) {
2030 var viewWidth = $('#GBtwopageview').width();
2031 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2032 var intoViewX = percentageX * viewWidth;
2034 var viewHeight = $('#GBtwopageview').height();
2035 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2036 var intoViewY = percentageY * viewHeight;
2038 if (viewWidth < containerClientWidth) {
2039 // Can fit width without scrollbars - center by adjusting offset
2040 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2042 // Need to scroll to center
2043 $('#GBtwopageview').css('left', 0);
2044 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2047 if (viewHeight < containerClientHeight) {
2048 // Fits with scrollbars - add offset
2049 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2051 $('#GBtwopageview').css('top', 0);
2052 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2056 // showSearchHilites2UP()
2057 //______________________________________________________________________________
2058 GnuBook.prototype.updateSearchHilites2UP = function() {
2060 for (var key in this.searchResults) {
2061 key = parseInt(key, 10);
2062 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2063 var result = this.searchResults[key];
2064 if(null == result.div) {
2065 result.div = document.createElement('div');
2066 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2067 //console.log('appending ' + key);
2070 // We calculate the reduction factor for the specific page because it can be different
2071 // for each page in the spread
2072 var height = this.getPageHeight(key);
2073 var width = this.getPageWidth(key)
2074 var reduce = this.twoPage.height/height;
2075 var scaledW = parseInt(width*reduce);
2077 var gutter = this.twoPageGutter();
2079 if ('L' == this.getPageSide(key)) {
2080 pageL = gutter-scaledW;
2084 var pageT = this.twoPageTop();
2087 width: (result.r-result.l)*reduce + 'px',
2088 height: (result.b-result.t)*reduce + 'px',
2089 left: pageL+(result.l)*reduce + 'px',
2090 top: pageT+(result.t)*reduce +'px'
2094 //console.log(key + ' not displayed');
2095 if (null != this.searchResults[key].div) {
2096 //console.log('removing ' + key);
2097 $(this.searchResults[key].div).remove();
2099 this.searchResults[key].div=null;
2104 // removeSearchHilites()
2105 //______________________________________________________________________________
2106 GnuBook.prototype.removeSearchHilites = function() {
2107 for (var key in this.searchResults) {
2108 if (null != this.searchResults[key].div) {
2109 $(this.searchResults[key].div).remove();
2110 this.searchResults[key].div=null;
2116 //______________________________________________________________________________
2117 GnuBook.prototype.showEmbedCode = function() {
2118 if (null != this.embedPopup) { // check if already showing
2122 this.embedPopup = document.createElement("div");
2123 $(this.embedPopup).css({
2124 position: 'absolute',
2126 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2129 border: "3px double #999999",
2131 backgroundColor: "#fff"
2132 }).appendTo('#GnuBook');
2134 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2135 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>';
2136 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2137 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2139 this.embedPopup.innerHTML = htmlStr;
2140 $(this.embedPopup).find('input').bind('click', function() {
2146 //______________________________________________________________________________
2147 GnuBook.prototype.autoToggle = function() {
2149 var bComingFrom1up = false;
2150 if (2 != this.mode) {
2151 bComingFrom1up = true;
2155 // Change to autofit if book is too large
2156 if (this.reduce < this.twoPageGetAutofitReduce()) {
2161 if (null == this.autoTimer) {
2162 this.flipSpeed = 2000;
2164 // $$$ Draw events currently cause layout problems when they occur during animation.
2165 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2166 // we workaround for now by not triggering immediate animation in that case.
2167 // See https://bugs.launchpad.net/gnubook/+bug/328327
2168 if (('rl' == this.pageProgression) && bComingFrom1up) {
2169 // don't flip immediately -- wait until timer fires
2172 this.flipFwdToIndex();
2175 $('#GBtoolbar .play').hide();
2176 $('#GBtoolbar .pause').show();
2177 this.autoTimer=setInterval(function(){
2178 if (self.animating) {return;}
2180 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2181 self.flipBackToIndex(1); // $$$ really what we want?
2183 self.flipFwdToIndex();
2192 //______________________________________________________________________________
2193 // Stop autoplay mode, allowing animations to finish
2194 GnuBook.prototype.autoStop = function() {
2195 if (null != this.autoTimer) {
2196 clearInterval(this.autoTimer);
2197 this.flipSpeed = 'fast';
2198 $('#GBtoolbar .pause').hide();
2199 $('#GBtoolbar .play').show();
2200 this.autoTimer = null;
2204 // stopFlipAnimations
2205 //______________________________________________________________________________
2206 // Immediately stop flip animations. Callbacks are triggered.
2207 GnuBook.prototype.stopFlipAnimations = function() {
2209 this.autoStop(); // Clear timers
2211 // Stop animation, clear queue, trigger callbacks
2212 if (this.leafEdgeTmp) {
2213 $(this.leafEdgeTmp).stop(false, true);
2215 jQuery.each(this.prefetchedImgs, function() {
2216 $(this).stop(false, true);
2219 // And again since animations also queued in callbacks
2220 if (this.leafEdgeTmp) {
2221 $(this.leafEdgeTmp).stop(false, true);
2223 jQuery.each(this.prefetchedImgs, function() {
2224 $(this).stop(false, true);
2229 // keyboardNavigationIsDisabled(event)
2230 // - returns true if keyboard navigation should be disabled for the event
2231 //______________________________________________________________________________
2232 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2233 if (event.target.tagName == "INPUT") {
2239 // gutterOffsetForIndex
2240 //______________________________________________________________________________
2242 // Returns the gutter offset for the spread containing the given index.
2243 // This function supports RTL
2244 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2246 // To find the offset of the gutter from the middle we calculate our percentage distance
2247 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2248 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2250 // But then again for RTL it's the opposite
2251 if ('rl' == this.pageProgression) {
2259 //______________________________________________________________________________
2260 // Returns the width of the leaf edge div for the page with index given
2261 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2262 // $$$ could there be single pixel rounding errors for L vs R?
2263 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2264 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2266 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2270 // jumpIndexForLeftEdgePageX
2271 //______________________________________________________________________________
2272 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2273 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2274 if ('rl' != this.pageProgression) {
2275 // LTR - flipping backward
2276 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2278 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2279 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2283 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2284 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2289 // jumpIndexForRightEdgePageX
2290 //______________________________________________________________________________
2291 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2292 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2293 if ('rl' != this.pageProgression) {
2295 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2296 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2299 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2300 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2305 GnuBook.prototype.initToolbar = function(mode, ui) {
2307 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2308 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2309 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2310 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2311 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2312 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2313 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2314 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2317 this.updateToolbarZoom(this.reduce); // Pretty format
2319 if (ui == "embed") {
2320 $("#GnuBook a.logo").attr("target","_blank");
2323 // $$$ turn this into a member variable
2324 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2326 // We build in mode 2
2327 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2328 + "<button class='GBicon rollover embed' />"
2329 + "<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>"
2330 + "<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>"
2331 + "<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>"
2332 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2334 this.bindToolbarNavHandlers(jToolbar);
2336 // Setup tooltips -- later we could load these from a file for i18n
2337 var titles = { '.logo': 'Go to Archive.org',
2338 '.zoom_in': 'Zoom in',
2339 '.zoom_out': 'Zoom out',
2340 '.one_page_mode': 'One-page view',
2341 '.two_page_mode': 'Two-page view',
2342 '.embed': 'Embed bookreader',
2343 '.book_left': 'Flip left',
2344 '.book_right': 'Flip right',
2345 '.book_up': 'Page up',
2346 '.book_down': 'Page down',
2349 '.book_top': 'First page',
2350 '.book_bottom': 'Last page'
2352 if ('rl' == this.pageProgression) {
2353 titles['.book_leftmost'] = 'Last page';
2354 titles['.book_rightmost'] = 'First page';
2356 titles['.book_leftmost'] = 'First page';
2357 titles['.book_rightmost'] = 'Last page';
2360 for (var icon in titles) {
2361 jToolbar.find(icon).attr('title', titles[icon]);
2364 // Hide mode buttons and autoplay if 2up is not available
2365 // $$$ if we end up with more than two modes we should show the applicable buttons
2366 if ( !this.canSwitchToMode(this.constMode2up) ) {
2367 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2370 // Switch to requested mode -- binds other click handlers
2371 this.switchToolbarMode(mode);
2376 // switchToolbarMode
2377 //______________________________________________________________________________
2378 // Update the toolbar for the given mode (changes navigation buttons)
2379 // $$$ we should soon split the toolbar out into its own module
2380 GnuBook.prototype.switchToolbarMode = function(mode) {
2383 $('#GBtoolbar .GBtoolbarmode2').hide();
2384 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2387 $('#GBtoolbar .GBtoolbarmode1').hide();
2388 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2392 // bindToolbarNavHandlers
2393 //______________________________________________________________________________
2394 // Binds the toolbar handlers
2395 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2397 jToolbar.find('.book_left').bind('click', function(e) {
2402 jToolbar.find('.book_right').bind('click', function(e) {
2407 jToolbar.find('.book_up').bind('click', function(e) {
2412 jToolbar.find('.book_down').bind('click', function(e) {
2417 jToolbar.find('.embed').bind('click', function(e) {
2422 jToolbar.find('.play').bind('click', function(e) {
2427 jToolbar.find('.pause').bind('click', function(e) {
2432 jToolbar.find('.book_top').bind('click', function(e) {
2437 jToolbar.find('.book_bottom').bind('click', function(e) {
2442 jToolbar.find('.book_leftmost').bind('click', function(e) {
2447 jToolbar.find('.book_rightmost').bind('click', function(e) {
2453 // updateToolbarZoom(reduce)
2454 //______________________________________________________________________________
2455 // Update the displayed zoom factor based on reduction factor
2456 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2458 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2461 value = (100 / reduce).toFixed(2);
2462 // Strip trailing zeroes and decimal if all zeroes
2463 value = value.replace(/0+$/,'');
2464 value = value.replace(/\.$/,'');
2467 $('#GBzoom').text(value);
2470 // firstDisplayableIndex
2471 //______________________________________________________________________________
2472 // Returns the index of the first visible page, dependent on the mode.
2473 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2474 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2475 GnuBook.prototype.firstDisplayableIndex = function() {
2476 if (this.mode == 0) {
2479 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2483 // lastDisplayableIndex
2484 //______________________________________________________________________________
2485 // Returns the index of the last visible page, dependent on the mode.
2486 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2487 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2488 GnuBook.prototype.lastDisplayableIndex = function() {
2489 if (this.mode == 2) {
2490 if (this.lastDisplayableIndex2up === null) {
2491 // Calculate and cache
2492 var candidate = this.numLeafs - 1;
2493 for ( ; candidate >= 0; candidate--) {
2494 var spreadIndices = this.getSpreadIndices(candidate);
2495 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2499 this.lastDisplayableIndex2up = candidate;
2501 return this.lastDisplayableIndex2up;
2503 return this.numLeafs - 1;
2507 // shortTitle(maximumCharacters)
2509 // Returns a shortened version of the title with the maximum number of characters
2510 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2511 if (this.bookTitle.length < maximumCharacters) {
2512 return this.bookTitle;
2515 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2522 // Parameter related functions
2524 // updateFromParams(params)
2526 // Update ourselves from the params object.
2528 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2529 GnuBook.prototype.updateFromParams = function(params) {
2530 if ('undefined' != typeof(params.mode)) {
2531 this.switchMode(params.mode);
2534 // $$$ process /search
2535 // $$$ process /zoom
2537 // We only respect page if index is not set
2538 if ('undefined' != typeof(params.index)) {
2539 if (params.index != this.currentIndex()) {
2540 this.jumpToIndex(params.index);
2542 } else if ('undefined' != typeof(params.page)) {
2543 // $$$ this assumes page numbers are unique
2544 if (params.page != this.getPageNum(this.currentIndex())) {
2545 this.jumpToPage(params.page);
2549 // $$$ process /region
2550 // $$$ process /highlight
2553 // paramsFromFragment(urlFragment)
2555 // Returns a object with configuration parametes from a URL fragment.
2557 // E.g paramsFromFragment(window.location.hash)
2558 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2559 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2563 // For convenience we allow an initial # character (as from window.location.hash)
2564 // but don't require it
2565 if (urlFragment.substr(0,1) == '#') {
2566 urlFragment = urlFragment.substr(1);
2569 // Simple #nn syntax
2570 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2571 if ( !isNaN(oldStyleLeafNum) ) {
2572 params.index = oldStyleLeafNum;
2574 // Done processing if using old-style syntax
2578 // Split into key-value pairs
2579 var urlArray = urlFragment.split('/');
2581 for (var i = 0; i < urlArray.length; i += 2) {
2582 urlHash[urlArray[i]] = urlArray[i+1];
2586 if ('1up' == urlHash['mode']) {
2587 params.mode = this.constMode1up;
2588 } else if ('2up' == urlHash['mode']) {
2589 params.mode = this.constMode2up;
2593 if ('undefined' != typeof(urlHash['page'])) {
2594 // page was set -- may not be int
2595 params.page = urlHash['page'];
2598 // $$$ process /region
2599 // $$$ process /search
2600 // $$$ process /highlight
2605 // paramsFromCurrent()
2607 // Create a params object from the current parameters.
2608 GnuBook.prototype.paramsFromCurrent = function() {
2612 var pageNum = this.getPageNum(this.currentIndex());
2613 if ((pageNum === 0) || pageNum) {
2614 params.page = pageNum;
2617 params.index = this.currentIndex();
2618 params.mode = this.mode;
2627 // fragmentFromParams(params)
2629 // Create a fragment string from the params object.
2630 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2631 GnuBook.prototype.fragmentFromParams = function(params) {
2632 var separator = '/';
2636 if ('undefined' != typeof(params.page)) {
2637 fragments.push('page', params.page);
2639 // Don't have page numbering -- use index instead
2640 fragments.push('page', 'n' + params.index);
2648 if ('undefined' != typeof(params.mode)) {
2649 if (params.mode == this.constMode1up) {
2650 fragments.push('mode', '1up');
2651 } else if (params.mode == this.constMode2up) {
2652 fragments.push('mode', '2up');
2654 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2658 return fragments.join(separator);
2661 // getPageIndex(pageNum)
2663 // Returns the *highest* index the given page number, or undefined
2664 GnuBook.prototype.getPageIndex = function(pageNum) {
2665 var pageIndices = this.getPageIndices(pageNum);
2667 if (pageIndices.length > 0) {
2668 return pageIndices[pageIndices.length - 1];
2674 // getPageIndices(pageNum)
2676 // Returns an array (possibly empty) of the indices with the given page number
2677 GnuBook.prototype.getPageIndices = function(pageNum) {
2680 // Check for special "nXX" page number
2681 if (pageNum.slice(0,1) == 'n') {
2683 var pageIntStr = pageNum.slice(1, pageNum.length);
2684 var pageIndex = parseInt(pageIntStr);
2685 indices.append(pageIndex);
2688 // Do nothing... will run through page names and see if one matches
2693 for (i=0; i<this.numLeafs; i++) {
2694 if (this.getPageNum(i) == pageNum) {
2702 // getPageName(index)
2704 // Returns the name of the page as it should be displayed in the user interface
2705 GnuBook.prototype.getPageName = function(index) {
2706 return 'Page ' + this.getPageNum(index);
2709 // updateLocationHash
2711 // Update the location hash from the current parameters. Call this instead of manually
2712 // using window.location.replace
2713 GnuBook.prototype.updateLocationHash = function() {
2714 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2715 window.location.replace(newHash);
2717 // This is the variable checked in the timer. Only user-generated changes
2718 // to the URL will trigger the event.
2719 this.oldLocationHash = newHash;
2722 // startLocationPolling
2724 // Starts polling of window.location to see hash fragment changes
2725 GnuBook.prototype.startLocationPolling = function() {
2726 var self = this; // remember who I am
2727 self.oldLocationHash = window.location.hash;
2729 if (this.locationPollId) {
2730 clearInterval(this.locationPollID);
2731 this.locationPollId = null;
2734 this.locationPollId = setInterval(function() {
2735 var newHash = window.location.hash;
2736 if (newHash != self.oldLocationHash) {
2737 if (newHash != self.oldUserHash) { // Only process new user hash once
2738 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2740 // Queue change if animating
2741 if (self.animating) {
2743 self.animationFinishedCallback = function() {
2744 self.updateFromParams(self.paramsFromFragment(newHash));
2746 } else { // update immediately
2747 self.updateFromParams(self.paramsFromFragment(newHash));
2749 self.oldUserHash = newHash;
2757 // Returns a URL for an embedded version of the current book
2758 GnuBook.prototype.getEmbedURL = function() {
2759 // We could generate a URL hash fragment here but for now we just leave at defaults
2760 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2765 // Returns the embed code HTML fragment suitable for copy and paste
2766 GnuBook.prototype.getEmbedCode = function() {
2767 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2772 // Returns true if we can switch to the requested mode
2773 GnuBook.prototype.canSwitchToMode = function(mode) {
2774 if (mode == this.constMode2up) {
2775 // check there are enough pages to display
2776 // $$$ this is a workaround for the mis-feature that we can't display
2777 // short books in 2up mode
2778 if (this.numLeafs < 6) {
2786 // Library functions
2788 clamp: function(value, min, max) {
2789 return Math.min(Math.max(value, min), max);