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).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).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).bind('mouseup', function(ee) {
295 //console.log('mouseup');
297 this.dragging = false;
301 $(div).bind('mouseleave', function(e) {
302 //console.log('mouseleave');
304 //$(this).unbind('mousemove mouseup');
305 this.dragging = false;
309 $(div).bind('mouseenter', function(e) {
310 // On FF/OSX we don't always receive the mouseleave event
311 this.dragging = false;
315 // drawLeafsOnePage()
316 //______________________________________________________________________________
317 GnuBook.prototype.drawLeafsOnePage = function() {
318 //alert('drawing leafs!');
322 var scrollTop = $('#GBcontainer').attr('scrollTop');
323 var scrollBottom = scrollTop + $('#GBcontainer').height();
324 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
326 var indicesToDisplay = [];
331 for (i=0; i<this.numLeafs; i++) {
332 var height = parseInt(this.getPageHeight(i)/this.reduce);
334 leafBottom += height;
335 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
336 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
337 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
338 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
339 if (topInView | bottomInView | middleInView) {
340 //console.log('displayed: ' + this.displayedIndices);
341 //console.log('to display: ' + i);
342 indicesToDisplay.push(i);
344 leafTop += height +10;
348 var firstIndexToDraw = indicesToDisplay[0];
349 this.firstIndex = firstIndexToDraw;
351 // Update hash, but only if we're currently displaying a leaf
352 // Hack that fixes #365790
353 if (this.displayedIndices.length > 0) {
354 this.updateLocationHash();
357 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
359 indicesToDisplay.unshift(firstIndexToDraw);
362 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
363 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
364 indicesToDisplay.push(lastIndexToDraw+1);
369 for (i=0; i<firstIndexToDraw; i++) {
370 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
373 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
374 var viewWidth = $('#GBcontainer').attr('scrollWidth');
377 for (i=0; i<indicesToDisplay.length; i++) {
378 var index = indicesToDisplay[i];
379 var height = parseInt(this.getPageHeight(index)/this.reduce);
381 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
382 var width = parseInt(this.getPageWidth(index)/this.reduce);
383 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
384 var div = document.createElement("div");
385 div.className = 'GBpagediv1up';
386 div.id = 'pagediv'+index;
387 div.style.position = "absolute";
388 $(div).css('top', leafTop + 'px');
389 var left = (viewWidth-width)>>1;
390 if (left<0) left = 0;
391 $(div).css('left', left+'px');
392 $(div).css('width', width+'px');
393 $(div).css('height', height+'px');
394 //$(div).text('loading...');
396 this.setDragHandler(div);
398 $('#GBpageview').append(div);
400 var img = document.createElement("img");
401 img.src = this.getPageURI(index);
402 $(img).css('width', width+'px');
403 $(img).css('height', height+'px');
407 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
410 leafTop += height +10;
414 for (i=0; i<this.displayedIndices.length; i++) {
415 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
416 var index = this.displayedIndices[i];
417 //console.log('Removing leaf ' + index);
418 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
419 $('#pagediv'+index).remove();
421 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
425 this.displayedIndices = indicesToDisplay.slice();
426 this.updateSearchHilites();
428 if (null != this.getPageNum(firstIndexToDraw)) {
429 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
431 $("#GBpagenum").val('');
434 this.updateToolbarZoom(this.reduce);
438 // drawLeafsTwoPage()
439 //______________________________________________________________________________
440 GnuBook.prototype.drawLeafsTwoPage = function() {
441 var scrollTop = $('#GBtwopageview').attr('scrollTop');
442 var scrollBottom = scrollTop + $('#GBtwopageview').height();
444 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
446 var indexL = this.twoPage.currentIndexL;
447 var heightL = this.getPageHeight(indexL);
448 var widthL = this.getPageWidth(indexL);
450 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
451 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
452 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
453 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
454 //console.log(leafEdgeWidthL);
456 var middle = this.twoPage.middle; // $$$ getter instead?
457 var top = this.twoPageTop();
458 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
460 var scaledWL = this.getPageWidth2UP(indexL);
461 var gutter = this.twoPageGutter();
463 this.prefetchImg(indexL);
464 $(this.prefetchedImgs[indexL]).css({
465 position: 'absolute',
466 left: gutter-scaledWL+'px',
469 backgroundColor: 'rgb(234, 226, 205)',
470 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
471 width: scaledWL + 'px',
472 borderRight: '1px solid black',
474 }).appendTo('#GBtwopageview');
477 var indexR = this.twoPage.currentIndexR;
478 var heightR = this.getPageHeight(indexR);
479 var widthR = this.getPageWidth(indexR);
481 // $$$ should use getwidth2up?
482 //var scaledWR = this.twoPage.height*widthR/heightR;
483 var scaledWR = this.getPageWidth2UP(indexR);
484 this.prefetchImg(indexR);
485 $(this.prefetchedImgs[indexR]).css({
486 position: 'absolute',
490 backgroundColor: 'rgb(234, 226, 205)',
491 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
492 width: scaledWR + 'px',
493 borderLeft: '1px solid black',
495 }).appendTo('#GBtwopageview');
498 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
499 this.setClickHandlers();
500 this.twoPageSetCursor();
502 this.updatePageNumBox2UP();
503 this.updateToolbarZoom(this.reduce);
506 // updatePageNumBox2UP
507 //______________________________________________________________________________
508 GnuBook.prototype.updatePageNumBox2UP = function() {
509 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
510 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
512 $("#GBpagenum").val('');
514 this.updateLocationHash();
518 //______________________________________________________________________________
519 GnuBook.prototype.loadLeafs = function() {
523 if (null == this.timer) {
524 this.timer=setTimeout(function(){self.drawLeafs()},250);
526 clearTimeout(this.timer);
527 this.timer=setTimeout(function(){self.drawLeafs()},250);
533 // Pass 1 to zoom in, anything else to zoom out
534 //______________________________________________________________________________
535 GnuBook.prototype.zoom = function(direction) {
537 case this.constMode1up:
538 return this.zoom1up(direction);
539 case this.constMode2up:
540 return this.zoom2up(direction);
545 //______________________________________________________________________________
546 GnuBook.prototype.zoom1up = function(dir) {
547 if (2 == this.mode) { //can only zoom in 1-page mode
552 // $$$ with flexible zoom we could "snap" to /2 page reductions
553 // for better scaling
555 if (this.reduce <= 0.5) return;
556 this.reduce*=0.5; //zoom in
558 if (this.reduce >= 8) return;
559 this.reduce*=2; //zoom out
562 this.resizePageView();
564 $('#GBpageview').empty()
565 this.displayedIndices = [];
568 this.updateToolbarZoom(this.reduce);
572 //______________________________________________________________________________
573 GnuBook.prototype.resizePageView = function() {
576 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
577 var viewWidth = $('#GBcontainer').attr('clientWidth');
579 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
580 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
581 var oldPageViewHeight = $('#GBpageview').height();
582 var oldPageViewWidth = $('#GBpageview').width();
584 var oldCenterY = this.centerY1up();
585 var oldCenterX = this.centerX1up();
587 if (0 != oldPageViewHeight) {
588 var scrollRatio = oldCenterY / oldPageViewHeight;
593 for (i=0; i<this.numLeafs; i++) {
594 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
595 var width = parseInt(this.getPageWidth(i)/this.reduce);
596 if (width>viewWidth) viewWidth=width;
598 $('#GBpageview').height(viewHeight);
599 $('#GBpageview').width(viewWidth);
601 var newCenterY = scrollRatio*viewHeight;
602 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
603 $('#GBcontainer').attr('scrollTop', newTop);
605 // We use clientWidth here to avoid miscalculating due to scroll bar
606 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
607 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
608 newLeft = Math.max(newLeft, 0);
609 $('#GBcontainer').attr('scrollLeft', newLeft);
610 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
612 //this.centerPageView();
618 //______________________________________________________________________________
619 // Returns the current offset of the viewport center in scaled document coordinates.
620 GnuBook.prototype.centerX1up = function() {
622 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
623 centerX = $('#GBpageview').width();
625 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
627 centerX = Math.floor(centerX);
632 //______________________________________________________________________________
633 // Returns the current offset of the viewport center in scaled document coordinates.
634 GnuBook.prototype.centerY1up = function() {
635 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
636 return Math.floor(centerY);
640 //______________________________________________________________________________
641 GnuBook.prototype.centerPageView = function() {
643 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
644 var clientWidth = $('#GBcontainer').attr('clientWidth');
645 //console.log('sW='+scrollWidth+' cW='+clientWidth);
646 if (scrollWidth > clientWidth) {
647 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
652 // zoom2up(direction)
653 //______________________________________________________________________________
654 GnuBook.prototype.zoom2up = function(direction) {
656 // Hard stop autoplay
657 this.stopFlipAnimations();
659 // Get new zoom state
660 var newZoom = this.twoPageNextReduce(this.reduce, direction);
661 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
664 this.twoPage.autofit = newZoom.autofit;
665 this.reduce = newZoom.reduce;
667 // Preserve view center position
668 var oldCenter = this.twoPageGetViewCenter();
670 // Prepare view with new center to minimize visual glitches
671 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
675 // quantizeReduce(reduce)
676 //______________________________________________________________________________
677 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
678 GnuBook.prototype.quantizeReduce = function(reduce) {
679 var quantized = this.reductionFactors[0];
680 var distance = Math.abs(reduce - quantized);
681 for (var i = 1; i < this.reductionFactors.length; i++) {
682 newDistance = Math.abs(reduce - this.reductionFactors[i]);
683 if (newDistance < distance) {
684 distance = newDistance;
685 quantized = this.reductionFactors[i];
692 // twoPageNextReduce()
693 //______________________________________________________________________________
694 // Returns the next reduction level
695 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
697 var autofitReduce = this.twoPageGetAutofitReduce();
699 if (0 == direction) { // autofit
700 result.autofit = true;
701 result.reduce = autofitReduce;
703 } else if (1 == direction) { // zoom in
704 var newReduce = this.reductionFactors[0];
706 for (var i = 1; i < this.reductionFactors.length; i++) {
707 if (this.reductionFactors[i] < reduce) {
708 newReduce = this.reductionFactors[i];
712 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
714 result.autofit = true;
715 result.reduce = autofitReduce;
717 result.autofit = false;
718 result.reduce = newReduce;
722 var lastIndex = this.reductionFactors.length - 1;
723 var newReduce = this.reductionFactors[lastIndex];
725 for (var i = lastIndex; i >= 0; i--) {
726 if (this.reductionFactors[i] > reduce) {
727 newReduce = this.reductionFactors[i];
731 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
733 result.autofit = true;
734 result.reduce = autofitReduce;
736 result.autofit = false;
737 result.reduce = newReduce;
745 //______________________________________________________________________________
746 // Attempts to jump to page. Returns true if page could be found, false otherwise.
747 GnuBook.prototype.jumpToPage = function(pageNum) {
749 var pageIndex = this.getPageIndex(pageNum);
751 if ('undefined' != typeof(pageIndex)) {
754 this.jumpToIndex(pageIndex);
755 $('#GBcontainer').attr('scrollTop', leafTop);
764 //______________________________________________________________________________
765 GnuBook.prototype.jumpToIndex = function(index) {
767 if (2 == this.mode) {
770 // By checking against min/max we do nothing if requested index
772 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
773 this.flipBackToIndex(index);
774 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
775 this.flipFwdToIndex(index);
782 for (i=0; i<index; i++) {
783 h = parseInt(this.getPageHeight(i)/this.reduce);
784 leafTop += h + this.padding;
786 //$('#GBcontainer').attr('scrollTop', leafTop);
787 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
794 //______________________________________________________________________________
795 GnuBook.prototype.switchMode = function(mode) {
797 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
799 if (mode == this.mode) return;
801 if (!this.canSwitchToMode(mode)) {
806 this.removeSearchHilites();
810 this.switchToolbarMode(mode);
813 this.reduce = this.quantizeReduce(this.reduce);
814 this.prepareOnePageView();
816 this.prepareTwoPageView();
817 this.twoPageCenterView(0.5, 0.5);
822 //prepareOnePageView()
823 //______________________________________________________________________________
824 GnuBook.prototype.prepareOnePageView = function() {
826 // var startLeaf = this.displayedIndices[0];
827 var startLeaf = this.currentIndex();
829 $('#GBcontainer').empty();
830 $('#GBcontainer').css({
835 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
837 this.resizePageView();
839 this.jumpToIndex(startLeaf);
840 this.displayedIndices = [];
842 this.drawLeafsOnePage();
844 // Bind mouse handlers
845 // Disable mouse click to avoid selected/highlighted page images - bug 354239
846 gbPageView.bind('mousedown', function(e) {
847 // $$$ check here for right-click and don't disable. Also use jQuery style
848 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
851 // Special hack for IE7
852 gbPageView[0].onselectstart = function(e) { return false; };
855 // prepareTwoPageView()
856 //______________________________________________________________________________
857 // Some decisions about two page view:
859 // Both pages will be displayed at the same height, even if they were different physical/scanned
860 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
861 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
862 // aspect ratio to determine the height.
864 // The two page view div is resized to keep the middle of the book in the middle of the div
865 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
866 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
867 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
868 $('#GBcontainer').empty();
869 $('#GBcontainer').css('overflow', 'auto');
871 // We want to display two facing pages. We may be missing
872 // one side of the spread because it is the first/last leaf,
873 // foldouts, missing pages, etc
875 //var targetLeaf = this.displayedIndices[0];
876 var targetLeaf = this.firstIndex;
878 if (targetLeaf < this.firstDisplayableIndex()) {
879 targetLeaf = this.firstDisplayableIndex();
882 if (targetLeaf > this.lastDisplayableIndex()) {
883 targetLeaf = this.lastDisplayableIndex();
886 this.twoPage.currentIndexL = null;
887 this.twoPage.currentIndexR = null;
888 this.pruneUnusedImgs();
890 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
891 this.twoPage.currentIndexL = currentSpreadIndices[0];
892 this.twoPage.currentIndexR = currentSpreadIndices[1];
893 this.firstIndex = this.twoPage.currentIndexL;
895 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
897 //console.dir(this.twoPage);
899 // Add the two page view
900 // $$$ Can we get everything set up and then append?
901 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
903 // $$$ calculate first then set
904 $('#GBtwopageview').css( {
905 height: this.twoPage.totalHeight + 'px',
906 width: this.twoPage.totalWidth + 'px',
910 // If there will not be scrollbars (e.g. when zooming out) we center the book
911 // since otherwise the book will be stuck off-center
912 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
913 centerPercentageX = 0.5;
915 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
916 centerPercentageY = 0.5;
919 this.twoPageCenterView(centerPercentageX, centerPercentageY);
921 this.twoPage.coverDiv = document.createElement('div');
922 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
923 border: '1px solid rgb(68, 25, 17)',
924 width: this.twoPage.bookCoverDivWidth + 'px',
925 height: this.twoPage.bookCoverDivHeight+'px',
926 visibility: 'visible',
927 position: 'absolute',
928 backgroundColor: '#663929',
929 left: this.twoPage.bookCoverDivLeft + 'px',
930 top: this.twoPage.bookCoverDivTop+'px',
931 MozBorderRadiusTopleft: '7px',
932 MozBorderRadiusTopright: '7px',
933 MozBorderRadiusBottomright: '7px',
934 MozBorderRadiusBottomleft: '7px'
935 }).appendTo('#GBtwopageview');
937 this.leafEdgeR = document.createElement('div');
938 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
939 $(this.leafEdgeR).css({
940 borderStyle: 'solid solid solid none',
941 borderColor: 'rgb(51, 51, 34)',
942 borderWidth: '1px 1px 1px 0px',
943 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
944 width: this.twoPage.leafEdgeWidthR + 'px',
945 height: this.twoPage.height-1 + 'px',
947 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
948 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
950 }).appendTo('#GBtwopageview');
952 this.leafEdgeL = document.createElement('div');
953 this.leafEdgeL.className = 'leafEdgeL';
954 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
955 borderStyle: 'solid none solid solid',
956 borderColor: 'rgb(51, 51, 34)',
957 borderWidth: '1px 0px 1px 1px',
958 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
959 width: this.twoPage.leafEdgeWidthL + 'px',
960 height: this.twoPage.height-1 + 'px',
961 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
962 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
964 }).appendTo('#GBtwopageview');
966 div = document.createElement('div');
967 $(div).attr('id', 'GBbookspine').css({
968 border: '1px solid rgb(68, 25, 17)',
969 width: this.twoPage.bookSpineDivWidth+'px',
970 height: this.twoPage.bookSpineDivHeight+'px',
971 position: 'absolute',
972 backgroundColor: 'rgb(68, 25, 17)',
973 left: this.twoPage.bookSpineDivLeft+'px',
974 top: this.twoPage.bookSpineDivTop+'px'
975 }).appendTo('#GBtwopageview');
977 this.prepareTwoPagePopUp();
979 this.displayedIndices = [];
981 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
982 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
984 this.drawLeafsTwoPage();
985 this.updateSearchHilites2UP();
986 this.updateToolbarZoom(this.reduce);
991 // prepareTwoPagePopUp()
993 // This function prepares the "View Page n" popup that shows while the mouse is
994 // over the left/right "stack of sheets" edges. It also binds the mouse
995 // events for these divs.
996 //______________________________________________________________________________
997 GnuBook.prototype.prepareTwoPagePopUp = function() {
999 this.twoPagePopUp = document.createElement('div');
1000 $(this.twoPagePopUp).css({
1001 border: '1px solid black',
1003 position: 'absolute',
1004 fontFamily: 'sans-serif',
1007 backgroundColor: 'rgb(255, 255, 238)',
1009 }).appendTo('#GBcontainer');
1010 $(this.twoPagePopUp).hide();
1012 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1013 $(e.data.twoPagePopUp).show();
1016 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1017 $(e.data.twoPagePopUp).hide();
1020 $(this.leafEdgeL).bind('click', this, function(e) {
1022 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1023 e.data.jumpToIndex(jumpIndex);
1026 $(this.leafEdgeR).bind('click', this, function(e) {
1028 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1029 e.data.jumpToIndex(jumpIndex);
1032 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1034 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1035 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1037 // $$$ TODO: Make sure popup is positioned so that it is in view
1038 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1039 $(e.data.twoPagePopUp).css({
1040 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1041 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1045 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1047 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1048 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1050 // $$$ TODO: Make sure popup is positioned so that it is in view
1051 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1052 $(e.data.twoPagePopUp).css({
1053 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1054 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1059 // calculateSpreadSize()
1060 //______________________________________________________________________________
1061 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1062 // this.twoPage.currentIndexR
1063 // This function sets this.twoPage.height, twoPage.width
1065 GnuBook.prototype.calculateSpreadSize = function() {
1067 var firstIndex = this.twoPage.currentIndexL;
1068 var secondIndex = this.twoPage.currentIndexR;
1069 //console.log('first page is ' + firstIndex);
1071 // Calculate page sizes and total leaf width
1073 if ( this.twoPage.autofit) {
1074 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1076 // set based on reduction factor
1077 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1080 // Both pages together
1081 this.twoPage.height = spreadSize.height;
1082 this.twoPage.width = spreadSize.width;
1085 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1086 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1089 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1090 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1091 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1095 // The width of the book cover div. The combined width of both pages, twice the width
1096 // of the book cover internal padding (2*10) and the page edges
1097 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1098 // The height of the book cover div
1099 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1102 // We calculate the total width and height for the div so that we can make the book
1104 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1105 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1106 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1107 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1108 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1109 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1111 // We want to minimize the unused space in two-up mode (maximize the amount of page
1112 // shown). We give width to the leaf edges and these widths change (though the sum
1113 // of the two remains constant) as we flip through the book. With the book
1114 // cover centered and fixed in the GBcontainer div the page images will meet
1115 // at the "gutter" which is generally offset from the center.
1116 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1117 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1119 // The left edge of the book cover moves depending on the width of the pages
1120 // $$$ change to getter
1121 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1122 // The top edge of the book cover stays a fixed distance from the top
1123 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1126 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1127 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1128 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1131 this.reduce = spreadSize.reduce; // $$$ really set this here?
1134 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1137 // We check which page is closest to a "normal" page and use that to set the height
1138 // for both pages. This means that foldouts and other odd size pages will be displayed
1139 // smaller than the nominal zoom amount.
1140 var canon5Dratio = 1.5;
1143 height: this.getPageHeight(firstIndex),
1144 width: this.getPageWidth(firstIndex)
1148 height: this.getPageHeight(secondIndex),
1149 width: this.getPageWidth(secondIndex)
1152 var firstIndexRatio = first.height / first.width;
1153 var secondIndexRatio = second.height / second.width;
1154 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1157 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1158 ratio = firstIndexRatio;
1159 //console.log('using firstIndexRatio ' + ratio);
1161 ratio = secondIndexRatio;
1162 //console.log('using secondIndexRatio ' + ratio);
1165 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1166 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1167 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1169 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1170 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1172 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1173 ideal.width -= 10; // $$$ fudge factor
1174 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1175 ideal.height -= 20; // fudge factor
1176 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1178 if (ideal.height/ratio <= ideal.width) {
1180 ideal.width = parseInt(ideal.height/ratio);
1183 ideal.height = parseInt(ideal.width*ratio);
1186 // $$$ check this logic with large spreads
1187 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1192 // getSpreadSizeFromReduce()
1193 //______________________________________________________________________________
1194 // Returns the spread size calculated from the reduction factor for the given pages
1195 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1196 var spreadSize = {};
1197 // $$$ Scale this based on reduce?
1198 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1199 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1200 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1202 // $$$ Possibly incorrect -- we should make height "dominant"
1203 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1204 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1205 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1206 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1207 spreadSize.reduce = reduce;
1212 // twoPageGetAutofitReduce()
1213 //______________________________________________________________________________
1214 // Returns the current ideal reduction factor
1215 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1216 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1217 return spreadSize.reduce;
1220 // twoPageSetCursor()
1221 //______________________________________________________________________________
1222 // Set the cursor for two page view
1223 GnuBook.prototype.twoPageSetCursor = function() {
1224 // console.log('setting cursor');
1225 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1226 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1227 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1228 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1230 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1231 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1236 //______________________________________________________________________________
1237 // Returns the currently active index.
1238 GnuBook.prototype.currentIndex = function() {
1239 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1240 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1241 return this.firstIndex;
1243 throw 'currentIndex called for unimplemented mode ' + this.mode;
1248 //______________________________________________________________________________
1249 // Flip the right page over onto the left
1250 GnuBook.prototype.right = function() {
1251 if ('rl' != this.pageProgression) {
1261 //______________________________________________________________________________
1262 // Flip to the rightmost page
1263 GnuBook.prototype.rightmost = function() {
1264 if ('rl' != this.pageProgression) {
1272 //______________________________________________________________________________
1273 // Flip the left page over onto the right.
1274 GnuBook.prototype.left = function() {
1275 if ('rl' != this.pageProgression) {
1285 //______________________________________________________________________________
1286 // Flip to the leftmost page
1287 GnuBook.prototype.leftmost = function() {
1288 if ('rl' != this.pageProgression) {
1296 //______________________________________________________________________________
1297 GnuBook.prototype.next = function() {
1298 if (2 == this.mode) {
1300 this.flipFwdToIndex(null);
1302 if (this.firstIndex < this.lastDisplayableIndex()) {
1303 this.jumpToIndex(this.firstIndex+1);
1309 //______________________________________________________________________________
1310 GnuBook.prototype.prev = function() {
1311 if (2 == this.mode) {
1313 this.flipBackToIndex(null);
1315 if (this.firstIndex >= 1) {
1316 this.jumpToIndex(this.firstIndex-1);
1321 GnuBook.prototype.first = function() {
1322 if (2 == this.mode) {
1323 this.jumpToIndex(2);
1326 this.jumpToIndex(0);
1330 GnuBook.prototype.last = function() {
1331 if (2 == this.mode) {
1332 this.jumpToIndex(this.lastDisplayableIndex());
1335 this.jumpToIndex(this.lastDisplayableIndex());
1339 // flipBackToIndex()
1340 //______________________________________________________________________________
1341 // to flip back one spread, pass index=null
1342 GnuBook.prototype.flipBackToIndex = function(index) {
1343 if (1 == this.mode) return;
1345 var leftIndex = this.twoPage.currentIndexL;
1347 // $$$ Need to change this to be able to see first spread.
1348 // See https://bugs.launchpad.net/gnubook/+bug/296788
1349 if (leftIndex <= 2) return;
1350 if (this.animating) return;
1352 if (null != this.leafEdgeTmp) {
1353 alert('error: leafEdgeTmp should be null!');
1357 if (null == index) {
1358 index = leftIndex-2;
1360 //if (index<0) return;
1362 var previousIndices = this.getSpreadIndices(index);
1364 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1368 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1370 this.animating = true;
1372 if ('rl' != this.pageProgression) {
1373 // Assume LTR and we are going backward
1374 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1375 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1377 // RTL and going backward
1378 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1379 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1383 // flipLeftToRight()
1384 //______________________________________________________________________________
1385 // Flips the page on the left towards the page on the right
1386 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1388 var leftLeaf = this.twoPage.currentIndexL;
1390 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1391 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1392 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1394 var currWidthL = this.getPageWidth2UP(leftLeaf);
1395 var newWidthL = this.getPageWidth2UP(newIndexL);
1396 var newWidthR = this.getPageWidth2UP(newIndexR);
1398 var top = this.twoPageTop();
1399 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1401 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1402 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1404 //animation strategy:
1405 // 0. remove search highlight, if any.
1406 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1407 // of the left leaf and where the user clicked in the leaf edge.
1408 // Note that if this function was triggered by left() and not a
1409 // mouse click, the width of leafEdgeTmp is very small (zero px).
1410 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1411 // leftLeaf to width=0.
1412 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1413 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1414 // its new full width.
1415 // 4. After step 3 is finished, do the following:
1416 // - remove leafEdgeTmp from the dom.
1417 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1418 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1419 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1420 // and width=newLeafEdgeWidthL.
1421 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1422 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1423 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1424 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1425 // - prefetch new adjacent leafs.
1426 // - set up click handlers for both new left and right leafs.
1427 // - redraw the search highlight.
1428 // - update the pagenum box and the url.
1431 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1433 this.leafEdgeTmp = document.createElement('div');
1434 $(this.leafEdgeTmp).css({
1435 borderStyle: 'solid none solid solid',
1436 borderColor: 'rgb(51, 51, 34)',
1437 borderWidth: '1px 0px 1px 1px',
1438 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1439 width: leafEdgeTmpW + 'px',
1440 height: this.twoPage.height-1 + 'px',
1441 left: leftEdgeTmpLeft + 'px',
1443 position: 'absolute',
1445 }).appendTo('#GBtwopageview');
1447 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1448 $(this.leafEdgeL).css({
1449 width: newLeafEdgeWidthL+'px',
1450 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1453 // Left gets the offset of the current left leaf from the document
1454 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1455 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1456 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1458 // We change the left leaf to right positioning
1459 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1460 $(this.prefetchedImgs[leftLeaf]).css({
1465 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1466 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1470 this.removeSearchHilites();
1472 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1473 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1475 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1476 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1478 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1479 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1480 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1482 $(self.leafEdgeR).css({
1483 // Moves the right leaf edge
1484 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1485 left: gutter+newWidthR+'px'
1488 $(self.leafEdgeL).css({
1489 // Moves and resizes the left leaf edge
1490 width: newLeafEdgeWidthL+'px',
1491 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1494 // Resizes the brown border div
1495 $(self.twoPage.coverDiv).css({
1496 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1497 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1500 $(self.leafEdgeTmp).remove();
1501 self.leafEdgeTmp = null;
1503 self.twoPage.currentIndexL = newIndexL;
1504 self.twoPage.currentIndexR = newIndexR;
1505 self.firstIndex = self.twoPage.currentIndexL;
1506 self.displayedIndices = [newIndexL, newIndexR];
1507 self.setClickHandlers();
1508 self.twoPageSetCursor();
1509 self.pruneUnusedImgs();
1511 self.animating = false;
1513 self.updateSearchHilites2UP();
1514 self.updatePageNumBox2UP();
1516 if (self.animationFinishedCallback) {
1517 self.animationFinishedCallback();
1518 self.animationFinishedCallback = null;
1526 //______________________________________________________________________________
1527 // Whether we flip left or right is dependent on the page progression
1528 // to flip forward one spread, pass index=null
1529 GnuBook.prototype.flipFwdToIndex = function(index) {
1531 if (this.animating) return;
1533 if (null != this.leafEdgeTmp) {
1534 alert('error: leafEdgeTmp should be null!');
1538 if (null == index) {
1539 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1541 if (index > this.lastDisplayableIndex()) return;
1543 this.animating = true;
1545 var nextIndices = this.getSpreadIndices(index);
1547 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1549 if ('rl' != this.pageProgression) {
1550 // We did not specify RTL
1551 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1552 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1555 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1556 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1560 // flipRightToLeft(nextL, nextR, gutter)
1561 // $$$ better not to have to pass gutter in
1562 //______________________________________________________________________________
1563 // Flip from left to right and show the nextL and nextR indices on those sides
1564 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1565 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1566 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1567 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1568 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1570 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1572 var top = this.twoPageTop();
1573 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1575 var middle = this.twoPage.middle;
1576 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1578 this.leafEdgeTmp = document.createElement('div');
1579 $(this.leafEdgeTmp).css({
1580 borderStyle: 'solid none solid solid',
1581 borderColor: 'rgb(51, 51, 34)',
1582 borderWidth: '1px 0px 1px 1px',
1583 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1584 width: leafEdgeTmpW + 'px',
1585 height: this.twoPage.height-1 + 'px',
1586 left: gutter+scaledW+'px',
1588 position: 'absolute',
1590 }).appendTo('#GBtwopageview');
1592 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1593 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1595 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1596 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1597 var newWidthL = this.getPageWidth2UP(newIndexL);
1598 var newWidthR = this.getPageWidth2UP(newIndexR);
1600 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1602 var self = this; // closure-tastic!
1604 var speed = this.flipSpeed;
1606 this.removeSearchHilites();
1608 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1609 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1610 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1611 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1612 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1614 $(self.leafEdgeL).css({
1615 width: newLeafEdgeWidthL+'px',
1616 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1619 // Resizes the book cover
1620 $(self.twoPage.coverDiv).css({
1621 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1622 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1625 $(self.leafEdgeTmp).remove();
1626 self.leafEdgeTmp = null;
1628 self.twoPage.currentIndexL = newIndexL;
1629 self.twoPage.currentIndexR = newIndexR;
1630 self.firstIndex = self.twoPage.currentIndexL;
1631 self.displayedIndices = [newIndexL, newIndexR];
1632 self.setClickHandlers();
1633 self.twoPageSetCursor();
1634 self.pruneUnusedImgs();
1636 self.animating = false;
1639 self.updateSearchHilites2UP();
1640 self.updatePageNumBox2UP();
1642 if (self.animationFinishedCallback) {
1643 self.animationFinishedCallback();
1644 self.animationFinishedCallback = null;
1651 //______________________________________________________________________________
1652 GnuBook.prototype.setClickHandlers = function() {
1654 // $$$ TODO don't set again if already set
1655 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1660 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1666 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1667 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1671 //______________________________________________________________________________
1672 GnuBook.prototype.prefetchImg = function(index) {
1673 if (undefined == this.prefetchedImgs[index]) {
1674 //console.log('prefetching ' + index);
1675 var img = document.createElement("img");
1676 img.src = this.getPageURI(index);
1677 this.prefetchedImgs[index] = img;
1682 // prepareFlipLeftToRight()
1684 //______________________________________________________________________________
1686 // Prepare to flip the left page towards the right. This corresponds to moving
1687 // backward when the page progression is left to right.
1688 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1690 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1692 this.prefetchImg(prevL);
1693 this.prefetchImg(prevR);
1695 var height = this.getPageHeight(prevL);
1696 var width = this.getPageWidth(prevL);
1697 var middle = this.twoPage.middle;
1698 var top = this.twoPageTop();
1699 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1701 // The gutter is the dividing line between the left and right pages.
1702 // It is offset from the middle to create the illusion of thickness to the pages
1703 var gutter = middle + this.gutterOffsetForIndex(prevL);
1705 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1706 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1707 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1709 $(this.prefetchedImgs[prevL]).css({
1710 position: 'absolute',
1711 left: gutter-scaledW+'px',
1712 right: '', // clear right property
1714 backgroundColor: 'rgb(234, 226, 205)',
1715 height: this.twoPage.height,
1716 width: scaledW+'px',
1717 borderRight: '1px solid black',
1721 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1723 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1725 $(this.prefetchedImgs[prevR]).css({
1726 position: 'absolute',
1730 backgroundColor: 'rgb(234, 226, 205)',
1731 height: this.twoPage.height,
1733 borderLeft: '1px solid black',
1737 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1741 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1742 // prepareFlipRightToLeft()
1743 //______________________________________________________________________________
1744 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1746 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1749 this.prefetchImg(nextL);
1750 this.prefetchImg(nextR);
1752 var height = this.getPageHeight(nextR);
1753 var width = this.getPageWidth(nextR);
1754 var middle = this.twoPage.middle;
1755 var top = this.twoPageTop();
1756 var scaledW = this.twoPage.height*width/height;
1758 var gutter = middle + this.gutterOffsetForIndex(nextL);
1760 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1761 $(this.prefetchedImgs[nextR]).css({
1762 position: 'absolute',
1765 backgroundColor: 'rgb(234, 226, 205)',
1766 height: this.twoPage.height,
1767 width: scaledW+'px',
1768 borderLeft: '1px solid black',
1772 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1774 height = this.getPageHeight(nextL);
1775 width = this.getPageWidth(nextL);
1776 scaledW = this.twoPage.height*width/height;
1778 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1779 $(this.prefetchedImgs[nextL]).css({
1780 position: 'absolute',
1781 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1783 backgroundColor: 'rgb(234, 226, 205)',
1784 height: this.twoPage.height,
1785 width: 0+'px', // Start at 0 width, then grow to the left
1786 borderRight: '1px solid black',
1790 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1794 // getNextLeafs() -- NOT RTL AWARE
1795 //______________________________________________________________________________
1796 // GnuBook.prototype.getNextLeafs = function(o) {
1797 // //TODO: we might have two left or two right leafs in a row (damaged book)
1798 // //For now, assume that leafs are contiguous.
1800 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1801 // o.L = this.twoPage.currentIndexL+2;
1802 // o.R = this.twoPage.currentIndexL+3;
1805 // getprevLeafs() -- NOT RTL AWARE
1806 //______________________________________________________________________________
1807 // GnuBook.prototype.getPrevLeafs = function(o) {
1808 // //TODO: we might have two left or two right leafs in a row (damaged book)
1809 // //For now, assume that leafs are contiguous.
1811 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1812 // o.L = this.twoPage.currentIndexL-2;
1813 // o.R = this.twoPage.currentIndexL-1;
1816 // pruneUnusedImgs()
1817 //______________________________________________________________________________
1818 GnuBook.prototype.pruneUnusedImgs = function() {
1819 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1820 for (var key in this.prefetchedImgs) {
1821 //console.log('key is ' + key);
1822 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1823 //console.log('removing key '+ key);
1824 $(this.prefetchedImgs[key]).remove();
1826 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1827 //console.log('deleting key '+ key);
1828 delete this.prefetchedImgs[key];
1834 //______________________________________________________________________________
1835 GnuBook.prototype.prefetch = function() {
1837 var lim = this.twoPage.currentIndexL-4;
1839 lim = Math.max(lim, 0);
1840 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1841 this.prefetchImg(i);
1844 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1845 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1846 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1847 this.prefetchImg(i);
1852 // getPageWidth2UP()
1853 //______________________________________________________________________________
1854 GnuBook.prototype.getPageWidth2UP = function(index) {
1855 // We return the width based on the dominant height
1856 var height = this.getPageHeight(index);
1857 var width = this.getPageWidth(index);
1858 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1862 //______________________________________________________________________________
1863 GnuBook.prototype.search = function(term) {
1864 $('#GnuBookSearchScript').remove();
1865 var script = document.createElement("script");
1866 script.setAttribute('id', 'GnuBookSearchScript');
1867 script.setAttribute("type", "text/javascript");
1868 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1869 document.getElementsByTagName('head')[0].appendChild(script);
1870 $('#GnuBookSearchResults').html('Searching...');
1873 // GBSearchCallback()
1874 //______________________________________________________________________________
1875 GnuBook.prototype.GBSearchCallback = function(txt) {
1877 if (jQuery.browser.msie) {
1878 var dom=new ActiveXObject("Microsoft.XMLDOM");
1882 var parser = new DOMParser();
1883 var dom = parser.parseFromString(txt, "text/xml");
1886 $('#GnuBookSearchResults').empty();
1887 $('#GnuBookSearchResults').append('<ul>');
1889 for (var key in this.searchResults) {
1890 if (null != this.searchResults[key].div) {
1891 $(this.searchResults[key].div).remove();
1893 delete this.searchResults[key];
1896 var pages = dom.getElementsByTagName('PAGE');
1898 if (0 == pages.length) {
1899 // $$$ it would be nice to echo the (sanitized) search result here
1900 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1902 for (var i = 0; i < pages.length; i++){
1903 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1906 var re = new RegExp (/_(\d{4})/);
1907 var reMatch = re.exec(pages[i].getAttribute('file'));
1908 var index = parseInt(reMatch[1], 10);
1909 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1911 var children = pages[i].childNodes;
1913 for (var j=0; j<children.length; j++) {
1914 //console.log(j + ' - ' + children[j].nodeName);
1915 //console.log(children[j].firstChild.nodeValue);
1916 if ('CONTEXT' == children[j].nodeName) {
1917 context += children[j].firstChild.nodeValue;
1918 } else if ('WORD' == children[j].nodeName) {
1919 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1921 var index = this.leafNumToIndex(index);
1922 if (null != index) {
1923 //coordinates are [left, bottom, right, top, [baseline]]
1924 //we'll skip baseline for now...
1925 var coords = children[j].getAttribute('coords').split(',',4);
1926 if (4 == coords.length) {
1927 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1932 var pageName = this.getPageName(index);
1933 //TODO: remove hardcoded instance name
1934 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1937 $('#GnuBookSearchResults').append('</ul>');
1939 this.updateSearchHilites();
1942 // updateSearchHilites()
1943 //______________________________________________________________________________
1944 GnuBook.prototype.updateSearchHilites = function() {
1945 if (2 == this.mode) {
1946 this.updateSearchHilites2UP();
1948 this.updateSearchHilites1UP();
1952 // showSearchHilites1UP()
1953 //______________________________________________________________________________
1954 GnuBook.prototype.updateSearchHilites1UP = function() {
1956 for (var key in this.searchResults) {
1958 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1959 var result = this.searchResults[key];
1960 if(null == result.div) {
1961 result.div = document.createElement('div');
1962 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1963 //console.log('appending ' + key);
1966 width: (result.r-result.l)/this.reduce + 'px',
1967 height: (result.b-result.t)/this.reduce + 'px',
1968 left: (result.l)/this.reduce + 'px',
1969 top: (result.t)/this.reduce +'px'
1973 //console.log(key + ' not displayed');
1974 this.searchResults[key].div=null;
1980 //______________________________________________________________________________
1981 // Returns the position of the gutter (line between the page images)
1982 GnuBook.prototype.twoPageGutter = function() {
1983 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1987 //______________________________________________________________________________
1988 // Returns the offset for the top of the page images
1989 GnuBook.prototype.twoPageTop = function() {
1990 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1993 // twoPageCoverWidth()
1994 //______________________________________________________________________________
1995 // Returns the width of the cover div given the total page width
1996 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
1997 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2000 // twoPageGetViewCenter()
2001 //______________________________________________________________________________
2002 // Returns the percentage offset into twopageview div at the center of container div
2003 // { percentageX: float, percentageY: float }
2004 GnuBook.prototype.twoPageGetViewCenter = function() {
2007 var containerOffset = $('#GBcontainer').offset();
2008 var viewOffset = $('#GBtwopageview').offset();
2009 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2010 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2015 // twoPageCenterView(percentageX, percentageY)
2016 //______________________________________________________________________________
2017 // Centers the point given by percentage from left,top of twopageview
2018 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2019 if ('undefined' == typeof(percentageX)) {
2022 if ('undefined' == typeof(percentageY)) {
2026 var viewWidth = $('#GBtwopageview').width();
2027 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2028 var intoViewX = percentageX * viewWidth;
2030 var viewHeight = $('#GBtwopageview').height();
2031 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2032 var intoViewY = percentageY * viewHeight;
2034 if (viewWidth < containerClientWidth) {
2035 // Can fit width without scrollbars - center by adjusting offset
2036 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2038 // Need to scroll to center
2039 $('#GBtwopageview').css('left', 0);
2040 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2043 if (viewHeight < containerClientHeight) {
2044 // Fits with scrollbars - add offset
2045 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2047 $('#GBtwopageview').css('top', 0);
2048 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2052 // showSearchHilites2UP()
2053 //______________________________________________________________________________
2054 GnuBook.prototype.updateSearchHilites2UP = function() {
2056 for (var key in this.searchResults) {
2057 key = parseInt(key, 10);
2058 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2059 var result = this.searchResults[key];
2060 if(null == result.div) {
2061 result.div = document.createElement('div');
2062 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2063 //console.log('appending ' + key);
2066 // We calculate the reduction factor for the specific page because it can be different
2067 // for each page in the spread
2068 var height = this.getPageHeight(key);
2069 var width = this.getPageWidth(key)
2070 var reduce = this.twoPage.height/height;
2071 var scaledW = parseInt(width*reduce);
2073 var gutter = this.twoPageGutter();
2075 if ('L' == this.getPageSide(key)) {
2076 pageL = gutter-scaledW;
2080 var pageT = this.twoPageTop();
2083 width: (result.r-result.l)*reduce + 'px',
2084 height: (result.b-result.t)*reduce + 'px',
2085 left: pageL+(result.l)*reduce + 'px',
2086 top: pageT+(result.t)*reduce +'px'
2090 //console.log(key + ' not displayed');
2091 if (null != this.searchResults[key].div) {
2092 //console.log('removing ' + key);
2093 $(this.searchResults[key].div).remove();
2095 this.searchResults[key].div=null;
2100 // removeSearchHilites()
2101 //______________________________________________________________________________
2102 GnuBook.prototype.removeSearchHilites = function() {
2103 for (var key in this.searchResults) {
2104 if (null != this.searchResults[key].div) {
2105 $(this.searchResults[key].div).remove();
2106 this.searchResults[key].div=null;
2112 //______________________________________________________________________________
2113 GnuBook.prototype.showEmbedCode = function() {
2114 if (null != this.embedPopup) { // check if already showing
2118 this.embedPopup = document.createElement("div");
2119 $(this.embedPopup).css({
2120 position: 'absolute',
2122 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2125 border: "3px double #999999",
2127 backgroundColor: "#fff"
2128 }).appendTo('#GnuBook');
2130 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2131 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>';
2132 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2133 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2135 this.embedPopup.innerHTML = htmlStr;
2136 $(this.embedPopup).find('input').bind('click', function() {
2142 //______________________________________________________________________________
2143 GnuBook.prototype.autoToggle = function() {
2145 var bComingFrom1up = false;
2146 if (2 != this.mode) {
2147 bComingFrom1up = true;
2151 // Change to autofit if book is too large
2152 if (this.reduce < this.twoPageGetAutofitReduce()) {
2157 if (null == this.autoTimer) {
2158 this.flipSpeed = 2000;
2160 // $$$ Draw events currently cause layout problems when they occur during animation.
2161 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2162 // we workaround for now by not triggering immediate animation in that case.
2163 // See https://bugs.launchpad.net/gnubook/+bug/328327
2164 if (('rl' == this.pageProgression) && bComingFrom1up) {
2165 // don't flip immediately -- wait until timer fires
2168 this.flipFwdToIndex();
2171 $('#GBtoolbar .play').hide();
2172 $('#GBtoolbar .pause').show();
2173 this.autoTimer=setInterval(function(){
2174 if (self.animating) {return;}
2176 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2177 self.flipBackToIndex(1); // $$$ really what we want?
2179 self.flipFwdToIndex();
2188 //______________________________________________________________________________
2189 // Stop autoplay mode, allowing animations to finish
2190 GnuBook.prototype.autoStop = function() {
2191 if (null != this.autoTimer) {
2192 clearInterval(this.autoTimer);
2193 this.flipSpeed = 'fast';
2194 $('#GBtoolbar .pause').hide();
2195 $('#GBtoolbar .play').show();
2196 this.autoTimer = null;
2200 // stopFlipAnimations
2201 //______________________________________________________________________________
2202 // Immediately stop flip animations. Callbacks are triggered.
2203 GnuBook.prototype.stopFlipAnimations = function() {
2205 this.autoStop(); // Clear timers
2207 // Stop animation, clear queue, trigger callbacks
2208 if (this.leafEdgeTmp) {
2209 $(this.leafEdgeTmp).stop(false, true);
2211 jQuery.each(this.prefetchedImgs, function() {
2212 $(this).stop(false, true);
2215 // And again since animations also queued in callbacks
2216 if (this.leafEdgeTmp) {
2217 $(this.leafEdgeTmp).stop(false, true);
2219 jQuery.each(this.prefetchedImgs, function() {
2220 $(this).stop(false, true);
2225 // keyboardNavigationIsDisabled(event)
2226 // - returns true if keyboard navigation should be disabled for the event
2227 //______________________________________________________________________________
2228 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2229 if (event.target.tagName == "INPUT") {
2235 // gutterOffsetForIndex
2236 //______________________________________________________________________________
2238 // Returns the gutter offset for the spread containing the given index.
2239 // This function supports RTL
2240 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2242 // To find the offset of the gutter from the middle we calculate our percentage distance
2243 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2244 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2246 // But then again for RTL it's the opposite
2247 if ('rl' == this.pageProgression) {
2255 //______________________________________________________________________________
2256 // Returns the width of the leaf edge div for the page with index given
2257 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2258 // $$$ could there be single pixel rounding errors for L vs R?
2259 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2260 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2262 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2266 // jumpIndexForLeftEdgePageX
2267 //______________________________________________________________________________
2268 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2269 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2270 if ('rl' != this.pageProgression) {
2271 // LTR - flipping backward
2272 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2274 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2275 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2279 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2280 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2285 // jumpIndexForRightEdgePageX
2286 //______________________________________________________________________________
2287 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2288 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2289 if ('rl' != this.pageProgression) {
2291 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2292 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2295 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2296 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2301 GnuBook.prototype.initToolbar = function(mode, ui) {
2303 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2304 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2305 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2306 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2307 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2308 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2309 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2310 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2313 this.updateToolbarZoom(); // Pretty format
2315 if (ui == "embed") {
2316 $("#GnuBook a.logo").attr("target","_blank");
2319 // $$$ turn this into a member variable
2320 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2322 // We build in mode 2
2323 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2324 + "<button class='GBicon rollover embed' />"
2325 + "<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>"
2326 + "<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>"
2327 + "<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>"
2328 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2330 this.bindToolbarNavHandlers(jToolbar);
2332 // Setup tooltips -- later we could load these from a file for i18n
2333 var titles = { '.logo': 'Go to Archive.org',
2334 '.zoom_in': 'Zoom in',
2335 '.zoom_out': 'Zoom out',
2336 '.one_page_mode': 'One-page view',
2337 '.two_page_mode': 'Two-page view',
2338 '.embed': 'Embed bookreader',
2339 '.book_left': 'Flip left',
2340 '.book_right': 'Flip right',
2341 '.book_up': 'Page up',
2342 '.book_down': 'Page down',
2345 '.book_top': 'First page',
2346 '.book_bottom': 'Last page'
2348 if ('rl' == this.pageProgression) {
2349 titles['.book_leftmost'] = 'Last page';
2350 titles['.book_rightmost'] = 'First page';
2352 titles['.book_leftmost'] = 'First page';
2353 titles['.book_rightmost'] = 'Last page';
2356 for (var icon in titles) {
2357 jToolbar.find(icon).attr('title', titles[icon]);
2360 // Hide mode buttons and autoplay if 2up is not available
2361 // $$$ if we end up with more than two modes we should show the applicable buttons
2362 if ( !this.canSwitchToMode(this.constMode2up) ) {
2363 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2366 // Switch to requested mode -- binds other click handlers
2367 this.switchToolbarMode(mode);
2372 // switchToolbarMode
2373 //______________________________________________________________________________
2374 // Update the toolbar for the given mode (changes navigation buttons)
2375 // $$$ we should soon split the toolbar out into its own module
2376 GnuBook.prototype.switchToolbarMode = function(mode) {
2379 $('#GBtoolbar .GBtoolbarmode2').hide();
2380 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2383 $('#GBtoolbar .GBtoolbarmode1').hide();
2384 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2388 // bindToolbarNavHandlers
2389 //______________________________________________________________________________
2390 // Binds the toolbar handlers
2391 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2393 jToolbar.find('.book_left').bind('click', function(e) {
2398 jToolbar.find('.book_right').bind('click', function(e) {
2403 jToolbar.find('.book_up').bind('click', function(e) {
2408 jToolbar.find('.book_down').bind('click', function(e) {
2413 jToolbar.find('.embed').bind('click', function(e) {
2418 jToolbar.find('.play').bind('click', function(e) {
2423 jToolbar.find('.pause').bind('click', function(e) {
2428 jToolbar.find('.book_top').bind('click', function(e) {
2433 jToolbar.find('.book_bottom').bind('click', function(e) {
2438 jToolbar.find('.book_leftmost').bind('click', function(e) {
2443 jToolbar.find('.book_rightmost').bind('click', function(e) {
2449 // updateToolbarZoom(reduce)
2450 //______________________________________________________________________________
2451 // Update the displayed zoom factor based on reduction factor
2452 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2454 if (this.twoPage.autofit) {
2457 value = (100 / reduce).toFixed(2);
2458 // Strip trailing zeroes and decimal if all zeroes
2459 value = value.replace(/0+$/,'');
2460 value = value.replace(/\.$/,'');
2463 $('#GBzoom').text(value);
2466 // firstDisplayableIndex
2467 //______________________________________________________________________________
2468 // Returns the index of the first visible page, dependent on the mode.
2469 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2470 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2471 GnuBook.prototype.firstDisplayableIndex = function() {
2472 if (this.mode == 0) {
2475 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2479 // lastDisplayableIndex
2480 //______________________________________________________________________________
2481 // Returns the index of the last visible page, dependent on the mode.
2482 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2483 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2484 GnuBook.prototype.lastDisplayableIndex = function() {
2485 if (this.mode == 2) {
2486 if (this.lastDisplayableIndex2up === null) {
2487 // Calculate and cache
2488 var candidate = this.numLeafs - 1;
2489 for ( ; candidate >= 0; candidate--) {
2490 var spreadIndices = this.getSpreadIndices(candidate);
2491 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2495 this.lastDisplayableIndex2up = candidate;
2497 return this.lastDisplayableIndex2up;
2499 return this.numLeafs - 1;
2503 // shortTitle(maximumCharacters)
2505 // Returns a shortened version of the title with the maximum number of characters
2506 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2507 if (this.bookTitle.length < maximumCharacters) {
2508 return this.bookTitle;
2511 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2518 // Parameter related functions
2520 // updateFromParams(params)
2522 // Update ourselves from the params object.
2524 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2525 GnuBook.prototype.updateFromParams = function(params) {
2526 if ('undefined' != typeof(params.mode)) {
2527 this.switchMode(params.mode);
2530 // $$$ process /search
2531 // $$$ process /zoom
2533 // We only respect page if index is not set
2534 if ('undefined' != typeof(params.index)) {
2535 if (params.index != this.currentIndex()) {
2536 this.jumpToIndex(params.index);
2538 } else if ('undefined' != typeof(params.page)) {
2539 // $$$ this assumes page numbers are unique
2540 if (params.page != this.getPageNum(this.currentIndex())) {
2541 this.jumpToPage(params.page);
2545 // $$$ process /region
2546 // $$$ process /highlight
2549 // paramsFromFragment(urlFragment)
2551 // Returns a object with configuration parametes from a URL fragment.
2553 // E.g paramsFromFragment(window.location.hash)
2554 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2555 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2559 // For convenience we allow an initial # character (as from window.location.hash)
2560 // but don't require it
2561 if (urlFragment.substr(0,1) == '#') {
2562 urlFragment = urlFragment.substr(1);
2565 // Simple #nn syntax
2566 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2567 if ( !isNaN(oldStyleLeafNum) ) {
2568 params.index = oldStyleLeafNum;
2570 // Done processing if using old-style syntax
2574 // Split into key-value pairs
2575 var urlArray = urlFragment.split('/');
2577 for (var i = 0; i < urlArray.length; i += 2) {
2578 urlHash[urlArray[i]] = urlArray[i+1];
2582 if ('1up' == urlHash['mode']) {
2583 params.mode = this.constMode1up;
2584 } else if ('2up' == urlHash['mode']) {
2585 params.mode = this.constMode2up;
2589 if ('undefined' != typeof(urlHash['page'])) {
2590 // page was set -- may not be int
2591 params.page = urlHash['page'];
2594 // $$$ process /region
2595 // $$$ process /search
2596 // $$$ process /highlight
2601 // paramsFromCurrent()
2603 // Create a params object from the current parameters.
2604 GnuBook.prototype.paramsFromCurrent = function() {
2608 var pageNum = this.getPageNum(this.currentIndex());
2609 if ((pageNum === 0) || pageNum) {
2610 params.page = pageNum;
2613 params.index = this.currentIndex();
2614 params.mode = this.mode;
2623 // fragmentFromParams(params)
2625 // Create a fragment string from the params object.
2626 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2627 GnuBook.prototype.fragmentFromParams = function(params) {
2628 var separator = '/';
2632 if ('undefined' != typeof(params.page)) {
2633 fragments.push('page', params.page);
2635 // Don't have page numbering -- use index instead
2636 fragments.push('page', 'n' + params.index);
2644 if ('undefined' != typeof(params.mode)) {
2645 if (params.mode == this.constMode1up) {
2646 fragments.push('mode', '1up');
2647 } else if (params.mode == this.constMode2up) {
2648 fragments.push('mode', '2up');
2650 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2654 return fragments.join(separator);
2657 // getPageIndex(pageNum)
2659 // Returns the *highest* index the given page number, or undefined
2660 GnuBook.prototype.getPageIndex = function(pageNum) {
2661 var pageIndices = this.getPageIndices(pageNum);
2663 if (pageIndices.length > 0) {
2664 return pageIndices[pageIndices.length - 1];
2670 // getPageIndices(pageNum)
2672 // Returns an array (possibly empty) of the indices with the given page number
2673 GnuBook.prototype.getPageIndices = function(pageNum) {
2676 // Check for special "nXX" page number
2677 if (pageNum.slice(0,1) == 'n') {
2679 var pageIntStr = pageNum.slice(1, pageNum.length);
2680 var pageIndex = parseInt(pageIntStr);
2681 indices.append(pageIndex);
2684 // Do nothing... will run through page names and see if one matches
2689 for (i=0; i<this.numLeafs; i++) {
2690 if (this.getPageNum(i) == pageNum) {
2698 // getPageName(index)
2700 // Returns the name of the page as it should be displayed in the user interface
2701 GnuBook.prototype.getPageName = function(index) {
2702 return 'Page ' + this.getPageNum(index);
2705 // updateLocationHash
2707 // Update the location hash from the current parameters. Call this instead of manually
2708 // using window.location.replace
2709 GnuBook.prototype.updateLocationHash = function() {
2710 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2711 window.location.replace(newHash);
2713 // This is the variable checked in the timer. Only user-generated changes
2714 // to the URL will trigger the event.
2715 this.oldLocationHash = newHash;
2718 // startLocationPolling
2720 // Starts polling of window.location to see hash fragment changes
2721 GnuBook.prototype.startLocationPolling = function() {
2722 var self = this; // remember who I am
2723 self.oldLocationHash = window.location.hash;
2725 if (this.locationPollId) {
2726 clearInterval(this.locationPollID);
2727 this.locationPollId = null;
2730 this.locationPollId = setInterval(function() {
2731 var newHash = window.location.hash;
2732 if (newHash != self.oldLocationHash) {
2733 if (newHash != self.oldUserHash) { // Only process new user hash once
2734 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2736 // Queue change if animating
2737 if (self.animating) {
2739 self.animationFinishedCallback = function() {
2740 self.updateFromParams(self.paramsFromFragment(newHash));
2742 } else { // update immediately
2743 self.updateFromParams(self.paramsFromFragment(newHash));
2745 self.oldUserHash = newHash;
2753 // Returns a URL for an embedded version of the current book
2754 GnuBook.prototype.getEmbedURL = function() {
2755 // We could generate a URL hash fragment here but for now we just leave at defaults
2756 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2761 // Returns the embed code HTML fragment suitable for copy and paste
2762 GnuBook.prototype.getEmbedCode = function() {
2763 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2768 // Returns true if we can switch to the requested mode
2769 GnuBook.prototype.canSwitchToMode = function(mode) {
2770 if (mode == this.constMode2up) {
2771 // check there are enough pages to display
2772 // $$$ this is a workaround for the mis-feature that we can't display
2773 // short books in 2up mode
2774 if (this.numLeafs < 6) {
2782 // Library functions
2784 clamp: function(value, min, max) {
2785 return Math.min(Math.max(value, min), max);