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 //console.log('mousedown!');
170 if (1 == this.mode) {
171 this.resizePageView();
172 this.firstIndex = startIndex;
173 this.jumpToIndex(startIndex);
175 //this.resizePageView();
177 this.displayedIndices=[0];
178 this.firstIndex = startIndex;
179 this.displayedIndices = [this.firstIndex];
180 //console.log('titleLeaf: %d', this.titleLeaf);
181 //console.log('displayedIndices: %s', this.displayedIndices);
182 this.prepareTwoPageView();
185 // Enact other parts of initial params
186 this.updateFromParams(params);
189 GnuBook.prototype.setupKeyListeners = function() {
202 // We use document here instead of window to avoid a bug in jQuery on IE7
203 $(document).keydown(function(e) {
205 // Keyboard navigation
209 // In 1up mode page scrolling is handled by browser
210 if (2 == self.mode) {
216 if (2 == self.mode) {
227 if (self.keyboardNavigationIsDisabled(e)) {
230 if (2 == self.mode) {
235 if (self.keyboardNavigationIsDisabled(e)) {
238 if (2 == self.mode) {
247 //______________________________________________________________________________
248 GnuBook.prototype.drawLeafs = function() {
249 if (1 == this.mode) {
250 this.drawLeafsOnePage();
252 this.drawLeafsTwoPage();
256 // setDragHandler1up()
257 //______________________________________________________________________________
258 GnuBook.prototype.setDragHandler1up = function(div) {
259 div.dragging = false;
261 $(div).bind('mousedown', function(e) {
262 //console.log('mousedown at ' + e.pageY);
264 this.dragging = true;
265 this.prevMouseX = e.pageX;
266 this.prevMouseY = e.pageY;
268 var startX = e.pageX;
269 var startY = e.pageY;
270 var startTop = $('#GBcontainer').attr('scrollTop');
271 var startLeft = $('#GBcontainer').attr('scrollLeft');
276 $(div).bind('mousemove', function(ee) {
277 //console.log('mousemove ' + startY);
279 var offsetX = ee.pageX - this.prevMouseX;
280 var offsetY = ee.pageY - this.prevMouseY;
283 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
284 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
287 this.prevMouseX = ee.pageX;
288 this.prevMouseY = ee.pageY;
293 $(div).bind('mouseup', function(ee) {
294 //console.log('mouseup');
296 this.dragging = false;
300 $(div).bind('mouseleave', function(e) {
301 //console.log('mouseleave');
303 //$(this).unbind('mousemove mouseup');
304 this.dragging = false;
309 // drawLeafsOnePage()
310 //______________________________________________________________________________
311 GnuBook.prototype.drawLeafsOnePage = function() {
312 //alert('drawing leafs!');
316 var scrollTop = $('#GBcontainer').attr('scrollTop');
317 var scrollBottom = scrollTop + $('#GBcontainer').height();
318 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
320 var indicesToDisplay = [];
325 for (i=0; i<this.numLeafs; i++) {
326 var height = parseInt(this.getPageHeight(i)/this.reduce);
328 leafBottom += height;
329 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
330 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
331 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
332 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
333 if (topInView | bottomInView | middleInView) {
334 //console.log('displayed: ' + this.displayedIndices);
335 //console.log('to display: ' + i);
336 indicesToDisplay.push(i);
338 leafTop += height +10;
342 var firstIndexToDraw = indicesToDisplay[0];
343 this.firstIndex = firstIndexToDraw;
345 // Update hash, but only if we're currently displaying a leaf
346 // Hack that fixes #365790
347 if (this.displayedIndices.length > 0) {
348 this.updateLocationHash();
351 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
353 indicesToDisplay.unshift(firstIndexToDraw);
356 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
357 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
358 indicesToDisplay.push(lastIndexToDraw+1);
363 for (i=0; i<firstIndexToDraw; i++) {
364 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
367 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
368 var viewWidth = $('#GBcontainer').attr('scrollWidth');
371 for (i=0; i<indicesToDisplay.length; i++) {
372 var index = indicesToDisplay[i];
373 var height = parseInt(this.getPageHeight(index)/this.reduce);
375 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
376 var width = parseInt(this.getPageWidth(index)/this.reduce);
377 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
378 var div = document.createElement("div");
379 div.className = 'GBpagediv1up';
380 div.id = 'pagediv'+index;
381 div.style.position = "absolute";
382 $(div).css('top', leafTop + 'px');
383 var left = (viewWidth-width)>>1;
384 if (left<0) left = 0;
385 $(div).css('left', left+'px');
386 $(div).css('width', width+'px');
387 $(div).css('height', height+'px');
388 //$(div).text('loading...');
390 this.setDragHandler1up(div);
392 $('#GBpageview').append(div);
394 var img = document.createElement("img");
395 img.src = this.getPageURI(index);
396 $(img).css('width', width+'px');
397 $(img).css('height', height+'px');
401 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
404 leafTop += height +10;
408 for (i=0; i<this.displayedIndices.length; i++) {
409 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
410 var index = this.displayedIndices[i];
411 //console.log('Removing leaf ' + index);
412 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
413 $('#pagediv'+index).remove();
415 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
419 this.displayedIndices = indicesToDisplay.slice();
420 this.updateSearchHilites();
422 if (null != this.getPageNum(firstIndexToDraw)) {
423 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
425 $("#GBpagenum").val('');
428 this.updateToolbarZoom(this.reduce);
432 // drawLeafsTwoPage()
433 //______________________________________________________________________________
434 GnuBook.prototype.drawLeafsTwoPage = function() {
435 var scrollTop = $('#GBtwopageview').attr('scrollTop');
436 var scrollBottom = scrollTop + $('#GBtwopageview').height();
438 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
440 var indexL = this.twoPage.currentIndexL;
441 var heightL = this.getPageHeight(indexL);
442 var widthL = this.getPageWidth(indexL);
444 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
445 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
446 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
447 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
448 //console.log(leafEdgeWidthL);
450 var middle = this.twoPage.middle; // $$$ getter instead?
451 var top = this.twoPageTop();
452 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
454 var scaledWL = this.getPageWidth2UP(indexL);
455 var gutter = this.twoPageGutter();
457 this.prefetchImg(indexL);
458 $(this.prefetchedImgs[indexL]).css({
459 position: 'absolute',
460 left: gutter-scaledWL+'px',
463 backgroundColor: 'rgb(234, 226, 205)',
464 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
465 width: scaledWL + 'px',
466 borderRight: '1px solid black',
468 }).appendTo('#GBtwopageview');
471 var indexR = this.twoPage.currentIndexR;
472 var heightR = this.getPageHeight(indexR);
473 var widthR = this.getPageWidth(indexR);
475 // $$$ should use getwidth2up?
476 //var scaledWR = this.twoPage.height*widthR/heightR;
477 var scaledWR = this.getPageWidth2UP(indexR);
478 this.prefetchImg(indexR);
479 $(this.prefetchedImgs[indexR]).css({
480 position: 'absolute',
484 backgroundColor: 'rgb(234, 226, 205)',
485 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
486 width: scaledWR + 'px',
487 borderLeft: '1px solid black',
489 }).appendTo('#GBtwopageview');
492 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
493 this.setClickHandlers();
495 this.updatePageNumBox2UP();
496 this.updateToolbarZoom(this.reduce);
499 // updatePageNumBox2UP
500 //______________________________________________________________________________
501 GnuBook.prototype.updatePageNumBox2UP = function() {
502 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
503 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
505 $("#GBpagenum").val('');
507 this.updateLocationHash();
511 //______________________________________________________________________________
512 GnuBook.prototype.loadLeafs = function() {
516 if (null == this.timer) {
517 this.timer=setTimeout(function(){self.drawLeafs()},250);
519 clearTimeout(this.timer);
520 this.timer=setTimeout(function(){self.drawLeafs()},250);
526 // Pass 1 to zoom in, anything else to zoom out
527 //______________________________________________________________________________
528 GnuBook.prototype.zoom = function(direction) {
530 case this.constMode1up:
531 return this.zoom1up(direction);
532 case this.constMode2up:
533 return this.zoom2up(direction);
538 //______________________________________________________________________________
539 GnuBook.prototype.zoom1up = function(dir) {
540 if (2 == this.mode) { //can only zoom in 1-page mode
545 // $$$ with flexible zoom we could "snap" to /2 page reductions
546 // for better scaling
548 if (this.reduce <= 0.5) return;
549 this.reduce*=0.5; //zoom in
551 if (this.reduce >= 8) return;
552 this.reduce*=2; //zoom out
555 this.resizePageView();
557 $('#GBpageview').empty()
558 this.displayedIndices = [];
561 this.updateToolbarZoom(this.reduce);
565 //______________________________________________________________________________
566 GnuBook.prototype.resizePageView = function() {
569 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
570 var viewWidth = $('#GBcontainer').attr('clientWidth');
572 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
573 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
574 var oldPageViewHeight = $('#GBpageview').height();
575 var oldPageViewWidth = $('#GBpageview').width();
577 var oldCenterY = this.centerY1up();
578 var oldCenterX = this.centerX1up();
580 if (0 != oldPageViewHeight) {
581 var scrollRatio = oldCenterY / oldPageViewHeight;
586 for (i=0; i<this.numLeafs; i++) {
587 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
588 var width = parseInt(this.getPageWidth(i)/this.reduce);
589 if (width>viewWidth) viewWidth=width;
591 $('#GBpageview').height(viewHeight);
592 $('#GBpageview').width(viewWidth);
594 var newCenterY = scrollRatio*viewHeight;
595 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
596 $('#GBcontainer').attr('scrollTop', newTop);
598 // We use clientWidth here to avoid miscalculating due to scroll bar
599 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
600 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
601 newLeft = Math.max(newLeft, 0);
602 $('#GBcontainer').attr('scrollLeft', newLeft);
603 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
605 //this.centerPageView();
611 //______________________________________________________________________________
612 // Returns the current offset of the viewport center in scaled document coordinates.
613 GnuBook.prototype.centerX1up = function() {
615 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
616 centerX = $('#GBpageview').width();
618 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
620 centerX = Math.floor(centerX);
625 //______________________________________________________________________________
626 // Returns the current offset of the viewport center in scaled document coordinates.
627 GnuBook.prototype.centerY1up = function() {
628 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
629 return Math.floor(centerY);
633 //______________________________________________________________________________
634 GnuBook.prototype.centerPageView = function() {
636 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
637 var clientWidth = $('#GBcontainer').attr('clientWidth');
638 //console.log('sW='+scrollWidth+' cW='+clientWidth);
639 if (scrollWidth > clientWidth) {
640 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
645 // zoom2up(direction)
646 //______________________________________________________________________________
647 GnuBook.prototype.zoom2up = function(direction) {
649 // Hard stop autoplay
650 this.stopFlipAnimations();
652 // Get new zoom state
653 var newZoom = this.twoPageNextReduce(this.reduce, direction);
654 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
657 this.twoPage.autofit = newZoom.autofit;
658 this.reduce = newZoom.reduce;
660 // Preserve view center position
661 var oldCenter = this.twoPageGetViewCenter();
663 // Prepare view with new center to minimize visual glitches
664 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
668 // quantizeReduce(reduce)
669 //______________________________________________________________________________
670 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
671 GnuBook.prototype.quantizeReduce = function(reduce) {
672 var quantized = this.reductionFactors[0];
673 var distance = Math.abs(reduce - quantized);
674 for (var i = 1; i < this.reductionFactors.length; i++) {
675 newDistance = Math.abs(reduce - reductionFactors[i]);
676 if (newDistance < distance) {
677 distance = newDistance;
678 quantized = reductionFactors[i];
685 // twoPageNextReduce()
686 //______________________________________________________________________________
687 // Returns the next reduction level
688 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
690 var autofitReduce = this.twoPageGetAutofitReduce();
692 if (0 == direction) { // autofit
693 result.autofit = true;
694 result.reduce = autofitReduce;
696 } else if (1 == direction) { // zoom in
697 var newReduce = this.reductionFactors[0];
699 for (var i = 1; i < this.reductionFactors.length; i++) {
700 if (this.reductionFactors[i] < reduce) {
701 newReduce = this.reductionFactors[i];
705 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
707 result.autofit = true;
708 result.reduce = autofitReduce;
710 result.autofit = false;
711 result.reduce = newReduce;
715 var lastIndex = this.reductionFactors.length - 1;
716 var newReduce = this.reductionFactors[lastIndex];
718 for (var i = lastIndex; i >= 0; i--) {
719 if (this.reductionFactors[i] > reduce) {
720 newReduce = this.reductionFactors[i];
724 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
726 result.autofit = true;
727 result.reduce = autofitReduce;
729 result.autofit = false;
730 result.reduce = newReduce;
738 //______________________________________________________________________________
739 // Attempts to jump to page. Returns true if page could be found, false otherwise.
740 GnuBook.prototype.jumpToPage = function(pageNum) {
742 var pageIndex = this.getPageIndex(pageNum);
744 if ('undefined' != typeof(pageIndex)) {
747 this.jumpToIndex(pageIndex);
748 $('#GBcontainer').attr('scrollTop', leafTop);
757 //______________________________________________________________________________
758 GnuBook.prototype.jumpToIndex = function(index) {
760 if (2 == this.mode) {
763 // By checking against min/max we do nothing if requested index
765 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
766 this.flipBackToIndex(index);
767 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
768 this.flipFwdToIndex(index);
775 for (i=0; i<index; i++) {
776 h = parseInt(this.getPageHeight(i)/this.reduce);
777 leafTop += h + this.padding;
779 //$('#GBcontainer').attr('scrollTop', leafTop);
780 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
787 //______________________________________________________________________________
788 GnuBook.prototype.switchMode = function(mode) {
790 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
792 if (mode == this.mode) return;
794 if (!this.canSwitchToMode(mode)) {
799 this.removeSearchHilites();
803 this.switchToolbarMode(mode);
806 this.reduce = this.twoPageQuantizeReduce(this.reduce);
807 this.prepareOnePageView();
809 this.prepareTwoPageView();
810 this.twoPageCenterView(0.5, 0.5);
815 //prepareOnePageView()
816 //______________________________________________________________________________
817 GnuBook.prototype.prepareOnePageView = function() {
819 // var startLeaf = this.displayedIndices[0];
820 var startLeaf = this.currentIndex();
822 $('#GBcontainer').empty();
823 $('#GBcontainer').css({
828 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
830 this.resizePageView();
832 this.jumpToIndex(startLeaf);
833 this.displayedIndices = [];
835 this.drawLeafsOnePage();
837 // Bind mouse handlers
838 // Disable mouse click to avoid selected/highlighted page images - bug 354239
839 gbPageView.bind('mousedown', function(e) {
842 // Special hack for IE7
843 gbPageView[0].onselectstart = function(e) { return false; };
846 // prepareTwoPageView()
847 //______________________________________________________________________________
848 // Some decisions about two page view:
850 // Both pages will be displayed at the same height, even if they were different physical/scanned
851 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
852 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
853 // aspect ratio to determine the height.
855 // The two page view div is resized to keep the middle of the book in the middle of the div
856 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
857 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
858 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
859 $('#GBcontainer').empty();
860 $('#GBcontainer').css('overflow', 'auto');
862 // We want to display two facing pages. We may be missing
863 // one side of the spread because it is the first/last leaf,
864 // foldouts, missing pages, etc
866 //var targetLeaf = this.displayedIndices[0];
867 var targetLeaf = this.firstIndex;
869 if (targetLeaf < this.firstDisplayableIndex()) {
870 targetLeaf = this.firstDisplayableIndex();
873 if (targetLeaf > this.lastDisplayableIndex()) {
874 targetLeaf = this.lastDisplayableIndex();
877 this.twoPage.currentIndexL = null;
878 this.twoPage.currentIndexR = null;
879 this.pruneUnusedImgs();
881 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
882 this.twoPage.currentIndexL = currentSpreadIndices[0];
883 this.twoPage.currentIndexR = currentSpreadIndices[1];
884 this.firstIndex = this.twoPage.currentIndexL;
886 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
888 //console.dir(this.twoPage);
890 // Add the two page view
891 // $$$ Can we get everything set up and then append?
892 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
894 // $$$ calculate first then set
895 $('#GBtwopageview').css( {
896 height: this.twoPage.totalHeight + 'px',
897 width: this.twoPage.totalWidth + 'px',
901 // If there will not be scrollbars (e.g. when zooming out) we center the book
902 // since otherwise the book will be stuck off-center
903 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
904 centerPercentageX = 0.5;
906 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
907 centerPercentageY = 0.5;
910 this.twoPageCenterView(centerPercentageX, centerPercentageY);
912 this.twoPage.coverDiv = document.createElement('div');
913 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
914 border: '1px solid rgb(68, 25, 17)',
915 width: this.twoPage.bookCoverDivWidth + 'px',
916 height: this.twoPage.bookCoverDivHeight+'px',
917 visibility: 'visible',
918 position: 'absolute',
919 backgroundColor: '#663929',
920 left: this.twoPage.bookCoverDivLeft + 'px',
921 top: this.twoPage.bookCoverDivTop+'px',
922 MozBorderRadiusTopleft: '7px',
923 MozBorderRadiusTopright: '7px',
924 MozBorderRadiusBottomright: '7px',
925 MozBorderRadiusBottomleft: '7px'
926 }).appendTo('#GBtwopageview');
928 this.leafEdgeR = document.createElement('div');
929 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
930 $(this.leafEdgeR).css({
931 borderStyle: 'solid solid solid none',
932 borderColor: 'rgb(51, 51, 34)',
933 borderWidth: '1px 1px 1px 0px',
934 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
935 width: this.twoPage.leafEdgeWidthR + 'px',
936 height: this.twoPage.height-1 + 'px',
938 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
939 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
941 }).appendTo('#GBtwopageview');
943 this.leafEdgeL = document.createElement('div');
944 this.leafEdgeL.className = 'leafEdgeL';
945 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
946 borderStyle: 'solid none solid solid',
947 borderColor: 'rgb(51, 51, 34)',
948 borderWidth: '1px 0px 1px 1px',
949 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
950 width: this.twoPage.leafEdgeWidthL + 'px',
951 height: this.twoPage.height-1 + 'px',
952 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
953 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
955 }).appendTo('#GBtwopageview');
957 div = document.createElement('div');
958 $(div).attr('id', 'GBbookspine').css({
959 border: '1px solid rgb(68, 25, 17)',
960 width: this.twoPage.bookSpineDivWidth+'px',
961 height: this.twoPage.bookSpineDivHeight+'px',
962 position: 'absolute',
963 backgroundColor: 'rgb(68, 25, 17)',
964 left: this.twoPage.bookSpineDivLeft+'px',
965 top: this.twoPage.bookSpineDivTop+'px'
966 }).appendTo('#GBtwopageview');
968 this.prepareTwoPagePopUp();
970 this.displayedIndices = [];
972 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
973 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
975 this.drawLeafsTwoPage();
976 this.updateSearchHilites2UP();
977 this.updateToolbarZoom(this.reduce);
982 // prepareTwoPagePopUp()
984 // This function prepares the "View Page n" popup that shows while the mouse is
985 // over the left/right "stack of sheets" edges. It also binds the mouse
986 // events for these divs.
987 //______________________________________________________________________________
988 GnuBook.prototype.prepareTwoPagePopUp = function() {
990 this.twoPagePopUp = document.createElement('div');
991 $(this.twoPagePopUp).css({
992 border: '1px solid black',
994 position: 'absolute',
995 fontFamily: 'sans-serif',
998 backgroundColor: 'rgb(255, 255, 238)',
1000 }).appendTo('#GBcontainer');
1001 $(this.twoPagePopUp).hide();
1003 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1004 $(e.data.twoPagePopUp).show();
1007 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1008 $(e.data.twoPagePopUp).hide();
1011 $(this.leafEdgeL).bind('click', this, function(e) {
1013 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1014 e.data.jumpToIndex(jumpIndex);
1017 $(this.leafEdgeR).bind('click', this, function(e) {
1019 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1020 e.data.jumpToIndex(jumpIndex);
1023 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1025 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1026 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1028 // $$$ TODO: Make sure popup is positioned so that it is in view
1029 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1030 $(e.data.twoPagePopUp).css({
1031 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1032 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1036 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1038 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(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() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1045 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1050 // calculateSpreadSize()
1051 //______________________________________________________________________________
1052 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1053 // this.twoPage.currentIndexR
1054 // This function sets this.twoPage.height, twoPage.width
1056 GnuBook.prototype.calculateSpreadSize = function() {
1058 // $$$ TODO Calculate the spread size based on the reduction factor. If we are using
1059 // fit mode we recalculate the reduction factor based on the current page sizes
1060 // and display size first.
1062 var firstIndex = this.twoPage.currentIndexL;
1063 var secondIndex = this.twoPage.currentIndexR;
1064 //console.log('first page is ' + firstIndex);
1066 // Calculate page sizes and total leaf width
1068 if ( this.twoPage.autofit) {
1069 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1071 // set based on reduction factor
1072 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1075 // Both pages together
1076 this.twoPage.height = spreadSize.height;
1077 this.twoPage.width = spreadSize.width;
1080 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1081 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1084 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1085 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1086 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1090 // The width of the book cover div. The combined width of both pages, twice the width
1091 // of the book cover internal padding (2*10) and the page edges
1092 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1093 // The height of the book cover div
1094 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1097 // We calculate the total width and height for the div so that we can make the book
1099 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1100 var leftWidthFromCenter = this.twoPage.scaledWL + leftGutterOffset + this.twoPage.leafEdgeWidthL;
1101 var rightWidthFromCenter = this.twoPage.scaledWR - leftGutterOffset + this.twoPage.leafEdgeWidthR;
1102 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1103 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1104 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1106 // We want to minimize the unused space in two-up mode (maximize the amount of page
1107 // shown). We give width to the leaf edges and these widths change (though the sum
1108 // of the two remains constant) as we flip through the book. With the book
1109 // cover centered and fixed in the GBcontainer div the page images will meet
1110 // at the "gutter" which is generally offset from the center.
1111 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1112 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1114 // The left edge of the book cover moves depending on the width of the pages
1115 // $$$ change to getter
1116 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1117 // The top edge of the book cover stays a fixed distance from the top
1118 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1121 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1122 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1123 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1126 this.reduce = spreadSize.reduce; // $$$ really set this here?
1129 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1132 // We check which page is closest to a "normal" page and use that to set the height
1133 // for both pages. This means that foldouts and other odd size pages will be displayed
1134 // smaller than the nominal zoom amount.
1135 var canon5Dratio = 1.5;
1138 height: this.getPageHeight(firstIndex),
1139 width: this.getPageWidth(firstIndex)
1143 height: this.getPageHeight(secondIndex),
1144 width: this.getPageWidth(secondIndex)
1147 var firstIndexRatio = first.height / first.width;
1148 var secondIndexRatio = second.height / second.width;
1149 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1152 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1153 ratio = firstIndexRatio;
1154 //console.log('using firstIndexRatio ' + ratio);
1156 ratio = secondIndexRatio;
1157 //console.log('using secondIndexRatio ' + ratio);
1160 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1161 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1162 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1164 ideal.width = ($('#GBcontainer').attr('clientWidth') - 30 - ideal.totalLeafEdgeWidth)>>1;
1165 ideal.height = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1166 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1168 if (ideal.height/ratio <= ideal.width) {
1170 ideal.width = parseInt(ideal.height/ratio);
1173 ideal.height = parseInt(ideal.width*ratio);
1176 // $$$ check this logic with large spreads
1177 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1182 // getSpreadSizeFromReduce()
1183 //______________________________________________________________________________
1184 // Returns the spread size calculated from the reduction factor for the given pages
1185 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1186 var spreadSize = {};
1187 // $$$ Scale this based on reduce?
1188 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1189 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1190 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1192 // $$$ Possibly incorrect -- we should make height "dominant"
1193 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1194 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1195 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1196 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1197 spreadSize.reduce = reduce;
1202 // twoPageGetAutofitReduce()
1203 //______________________________________________________________________________
1204 // Returns the current ideal reduction factor
1205 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1206 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1207 return spreadSize.reduce;
1211 //______________________________________________________________________________
1212 // Returns the currently active index.
1213 GnuBook.prototype.currentIndex = function() {
1214 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1215 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1216 return this.firstIndex;
1218 throw 'currentIndex called for unimplemented mode ' + this.mode;
1223 //______________________________________________________________________________
1224 // Flip the right page over onto the left
1225 GnuBook.prototype.right = function() {
1226 if ('rl' != this.pageProgression) {
1236 //______________________________________________________________________________
1237 // Flip to the rightmost page
1238 GnuBook.prototype.rightmost = function() {
1239 if ('rl' != this.pageProgression) {
1247 //______________________________________________________________________________
1248 // Flip the left page over onto the right.
1249 GnuBook.prototype.left = function() {
1250 if ('rl' != this.pageProgression) {
1260 //______________________________________________________________________________
1261 // Flip to the leftmost page
1262 GnuBook.prototype.leftmost = function() {
1263 if ('rl' != this.pageProgression) {
1271 //______________________________________________________________________________
1272 GnuBook.prototype.next = function() {
1273 if (2 == this.mode) {
1275 this.flipFwdToIndex(null);
1277 if (this.firstIndex < this.lastDisplayableIndex()) {
1278 this.jumpToIndex(this.firstIndex+1);
1284 //______________________________________________________________________________
1285 GnuBook.prototype.prev = function() {
1286 if (2 == this.mode) {
1288 this.flipBackToIndex(null);
1290 if (this.firstIndex >= 1) {
1291 this.jumpToIndex(this.firstIndex-1);
1296 GnuBook.prototype.first = function() {
1297 if (2 == this.mode) {
1298 this.jumpToIndex(2);
1301 this.jumpToIndex(0);
1305 GnuBook.prototype.last = function() {
1306 if (2 == this.mode) {
1307 this.jumpToIndex(this.lastDisplayableIndex());
1310 this.jumpToIndex(this.lastDisplayableIndex());
1314 // flipBackToIndex()
1315 //______________________________________________________________________________
1316 // to flip back one spread, pass index=null
1317 GnuBook.prototype.flipBackToIndex = function(index) {
1318 if (1 == this.mode) return;
1320 var leftIndex = this.twoPage.currentIndexL;
1322 // $$$ Need to change this to be able to see first spread.
1323 // See https://bugs.launchpad.net/gnubook/+bug/296788
1324 if (leftIndex <= 2) return;
1325 if (this.animating) return;
1327 if (null != this.leafEdgeTmp) {
1328 alert('error: leafEdgeTmp should be null!');
1332 if (null == index) {
1333 index = leftIndex-2;
1335 //if (index<0) return;
1337 var previousIndices = this.getSpreadIndices(index);
1339 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1343 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1345 this.animating = true;
1347 if ('rl' != this.pageProgression) {
1348 // Assume LTR and we are going backward
1349 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1350 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1352 // RTL and going backward
1353 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1354 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1358 // flipLeftToRight()
1359 //______________________________________________________________________________
1360 // Flips the page on the left towards the page on the right
1361 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1363 var leftLeaf = this.twoPage.currentIndexL;
1365 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1366 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1367 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1369 var currWidthL = this.getPageWidth2UP(leftLeaf);
1370 var newWidthL = this.getPageWidth2UP(newIndexL);
1371 var newWidthR = this.getPageWidth2UP(newIndexR);
1373 var top = this.twoPageTop();
1374 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1376 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1377 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1379 //animation strategy:
1380 // 0. remove search highlight, if any.
1381 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1382 // of the left leaf and where the user clicked in the leaf edge.
1383 // Note that if this function was triggered by left() and not a
1384 // mouse click, the width of leafEdgeTmp is very small (zero px).
1385 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1386 // leftLeaf to width=0.
1387 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1388 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1389 // its new full width.
1390 // 4. After step 3 is finished, do the following:
1391 // - remove leafEdgeTmp from the dom.
1392 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1393 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1394 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1395 // and width=newLeafEdgeWidthL.
1396 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1397 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1398 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1399 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1400 // - prefetch new adjacent leafs.
1401 // - set up click handlers for both new left and right leafs.
1402 // - redraw the search highlight.
1403 // - update the pagenum box and the url.
1406 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1408 this.leafEdgeTmp = document.createElement('div');
1409 $(this.leafEdgeTmp).css({
1410 borderStyle: 'solid none solid solid',
1411 borderColor: 'rgb(51, 51, 34)',
1412 borderWidth: '1px 0px 1px 1px',
1413 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1414 width: leafEdgeTmpW + 'px',
1415 height: this.twoPage.height-1 + 'px',
1416 left: leftEdgeTmpLeft + 'px',
1418 position: 'absolute',
1420 }).appendTo('#GBtwopageview');
1422 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1423 $(this.leafEdgeL).css({
1424 width: newLeafEdgeWidthL+'px',
1425 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1428 // Left gets the offset of the current left leaf from the document
1429 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1430 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1431 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1433 // We change the left leaf to right positioning
1434 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1435 $(this.prefetchedImgs[leftLeaf]).css({
1440 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1441 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1445 this.removeSearchHilites();
1447 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1448 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1450 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1451 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1453 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1454 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1455 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1457 $(self.leafEdgeR).css({
1458 // Moves the right leaf edge
1459 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1460 left: gutter+newWidthR+'px'
1463 $(self.leafEdgeL).css({
1464 // Moves and resizes the left leaf edge
1465 width: newLeafEdgeWidthL+'px',
1466 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1469 // Resizes the brown border div
1470 $(self.twoPage.coverDiv).css({
1471 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1472 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1475 $(self.leafEdgeTmp).remove();
1476 self.leafEdgeTmp = null;
1478 self.twoPage.currentIndexL = newIndexL;
1479 self.twoPage.currentIndexR = newIndexR;
1480 self.firstIndex = self.twoPage.currentIndexL;
1481 self.displayedIndices = [newIndexL, newIndexR];
1482 self.setClickHandlers();
1483 self.pruneUnusedImgs();
1485 self.animating = false;
1487 self.updateSearchHilites2UP();
1488 self.updatePageNumBox2UP();
1490 if (self.animationFinishedCallback) {
1491 self.animationFinishedCallback();
1492 self.animationFinishedCallback = null;
1500 //______________________________________________________________________________
1501 // Whether we flip left or right is dependent on the page progression
1502 // to flip forward one spread, pass index=null
1503 GnuBook.prototype.flipFwdToIndex = function(index) {
1505 if (this.animating) return;
1507 if (null != this.leafEdgeTmp) {
1508 alert('error: leafEdgeTmp should be null!');
1512 if (null == index) {
1513 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1515 if (index > this.lastDisplayableIndex()) return;
1517 this.animating = true;
1519 var nextIndices = this.getSpreadIndices(index);
1521 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1523 if ('rl' != this.pageProgression) {
1524 // We did not specify RTL
1525 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1526 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1529 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1530 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1534 // flipRightToLeft(nextL, nextR, gutter)
1535 // $$$ better not to have to pass gutter in
1536 //______________________________________________________________________________
1537 // Flip from left to right and show the nextL and nextR indices on those sides
1538 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1539 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1540 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1541 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1542 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1544 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1546 var top = this.twoPageTop();
1547 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1549 var middle = this.twoPage.middle;
1550 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1552 this.leafEdgeTmp = document.createElement('div');
1553 $(this.leafEdgeTmp).css({
1554 borderStyle: 'solid none solid solid',
1555 borderColor: 'rgb(51, 51, 34)',
1556 borderWidth: '1px 0px 1px 1px',
1557 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1558 width: leafEdgeTmpW + 'px',
1559 height: this.twoPage.height-1 + 'px',
1560 left: gutter+scaledW+'px',
1562 position: 'absolute',
1564 }).appendTo('#GBtwopageview');
1566 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1567 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1569 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1570 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1571 var newWidthL = this.getPageWidth2UP(newIndexL);
1572 var newWidthR = this.getPageWidth2UP(newIndexR);
1574 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1576 var self = this; // closure-tastic!
1578 var speed = this.flipSpeed;
1580 this.removeSearchHilites();
1582 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1583 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1584 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1585 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1586 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1588 $(self.leafEdgeL).css({
1589 width: newLeafEdgeWidthL+'px',
1590 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1593 // Resizes the book cover
1594 $(self.twoPage.coverDiv).css({
1595 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1596 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1599 $(self.leafEdgeTmp).remove();
1600 self.leafEdgeTmp = null;
1602 self.twoPage.currentIndexL = newIndexL;
1603 self.twoPage.currentIndexR = newIndexR;
1604 self.firstIndex = self.twoPage.currentIndexL;
1605 self.displayedIndices = [newIndexL, newIndexR];
1606 self.setClickHandlers();
1607 self.pruneUnusedImgs();
1609 self.animating = false;
1612 self.updateSearchHilites2UP();
1613 self.updatePageNumBox2UP();
1615 if (self.animationFinishedCallback) {
1616 self.animationFinishedCallback();
1617 self.animationFinishedCallback = null;
1624 //______________________________________________________________________________
1625 GnuBook.prototype.setClickHandlers = function() {
1627 // $$$ TODO don't set again if already set
1628 $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
1633 $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
1641 //______________________________________________________________________________
1642 GnuBook.prototype.prefetchImg = function(index) {
1643 if (undefined == this.prefetchedImgs[index]) {
1644 //console.log('prefetching ' + index);
1645 var img = document.createElement("img");
1646 img.src = this.getPageURI(index);
1647 this.prefetchedImgs[index] = img;
1652 // prepareFlipLeftToRight()
1654 //______________________________________________________________________________
1656 // Prepare to flip the left page towards the right. This corresponds to moving
1657 // backward when the page progression is left to right.
1658 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1660 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1662 this.prefetchImg(prevL);
1663 this.prefetchImg(prevR);
1665 var height = this.getPageHeight(prevL);
1666 var width = this.getPageWidth(prevL);
1667 var middle = this.twoPage.middle;
1668 var top = this.twoPageTop();
1669 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1671 // The gutter is the dividing line between the left and right pages.
1672 // It is offset from the middle to create the illusion of thickness to the pages
1673 var gutter = middle + this.gutterOffsetForIndex(prevL);
1675 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1676 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1677 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1679 $(this.prefetchedImgs[prevL]).css({
1680 position: 'absolute',
1681 left: gutter-scaledW+'px',
1682 right: '', // clear right property
1684 backgroundColor: 'rgb(234, 226, 205)',
1685 height: this.twoPage.height,
1686 width: scaledW+'px',
1687 borderRight: '1px solid black',
1691 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1693 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1695 $(this.prefetchedImgs[prevR]).css({
1696 position: 'absolute',
1700 backgroundColor: 'rgb(234, 226, 205)',
1701 height: this.twoPage.height,
1703 borderLeft: '1px solid black',
1707 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1711 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1712 // prepareFlipRightToLeft()
1713 //______________________________________________________________________________
1714 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1716 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1719 this.prefetchImg(nextL);
1720 this.prefetchImg(nextR);
1722 var height = this.getPageHeight(nextR);
1723 var width = this.getPageWidth(nextR);
1724 var middle = this.twoPage.middle;
1725 var top = this.twoPageTop();
1726 var scaledW = this.twoPage.height*width/height;
1728 var gutter = middle + this.gutterOffsetForIndex(nextL);
1730 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1731 $(this.prefetchedImgs[nextR]).css({
1732 position: 'absolute',
1735 backgroundColor: 'rgb(234, 226, 205)',
1736 height: this.twoPage.height,
1737 width: scaledW+'px',
1738 borderLeft: '1px solid black',
1742 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1744 height = this.getPageHeight(nextL);
1745 width = this.getPageWidth(nextL);
1746 scaledW = this.twoPage.height*width/height;
1748 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1749 $(this.prefetchedImgs[nextL]).css({
1750 position: 'absolute',
1751 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1753 backgroundColor: 'rgb(234, 226, 205)',
1754 height: this.twoPage.height,
1755 width: 0+'px', // Start at 0 width, then grow to the left
1756 borderRight: '1px solid black',
1760 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1764 // getNextLeafs() -- NOT RTL AWARE
1765 //______________________________________________________________________________
1766 // GnuBook.prototype.getNextLeafs = function(o) {
1767 // //TODO: we might have two left or two right leafs in a row (damaged book)
1768 // //For now, assume that leafs are contiguous.
1770 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1771 // o.L = this.twoPage.currentIndexL+2;
1772 // o.R = this.twoPage.currentIndexL+3;
1775 // getprevLeafs() -- NOT RTL AWARE
1776 //______________________________________________________________________________
1777 // GnuBook.prototype.getPrevLeafs = function(o) {
1778 // //TODO: we might have two left or two right leafs in a row (damaged book)
1779 // //For now, assume that leafs are contiguous.
1781 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1782 // o.L = this.twoPage.currentIndexL-2;
1783 // o.R = this.twoPage.currentIndexL-1;
1786 // pruneUnusedImgs()
1787 //______________________________________________________________________________
1788 GnuBook.prototype.pruneUnusedImgs = function() {
1789 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1790 for (var key in this.prefetchedImgs) {
1791 //console.log('key is ' + key);
1792 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1793 //console.log('removing key '+ key);
1794 $(this.prefetchedImgs[key]).remove();
1796 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1797 //console.log('deleting key '+ key);
1798 delete this.prefetchedImgs[key];
1804 //______________________________________________________________________________
1805 GnuBook.prototype.prefetch = function() {
1807 var lim = this.twoPage.currentIndexL-4;
1809 lim = Math.max(lim, 0);
1810 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1811 this.prefetchImg(i);
1814 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1815 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1816 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1817 this.prefetchImg(i);
1822 // getPageWidth2UP()
1823 //______________________________________________________________________________
1824 GnuBook.prototype.getPageWidth2UP = function(index) {
1825 // We return the width based on the dominant height
1826 var height = this.getPageHeight(index);
1827 var width = this.getPageWidth(index);
1828 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1832 //______________________________________________________________________________
1833 GnuBook.prototype.search = function(term) {
1834 $('#GnuBookSearchScript').remove();
1835 var script = document.createElement("script");
1836 script.setAttribute('id', 'GnuBookSearchScript');
1837 script.setAttribute("type", "text/javascript");
1838 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1839 document.getElementsByTagName('head')[0].appendChild(script);
1840 $('#GnuBookSearchResults').html('Searching...');
1843 // GBSearchCallback()
1844 //______________________________________________________________________________
1845 GnuBook.prototype.GBSearchCallback = function(txt) {
1847 if (jQuery.browser.msie) {
1848 var dom=new ActiveXObject("Microsoft.XMLDOM");
1852 var parser = new DOMParser();
1853 var dom = parser.parseFromString(txt, "text/xml");
1856 $('#GnuBookSearchResults').empty();
1857 $('#GnuBookSearchResults').append('<ul>');
1859 for (var key in this.searchResults) {
1860 if (null != this.searchResults[key].div) {
1861 $(this.searchResults[key].div).remove();
1863 delete this.searchResults[key];
1866 var pages = dom.getElementsByTagName('PAGE');
1868 if (0 == pages.length) {
1869 // $$$ it would be nice to echo the (sanitized) search result here
1870 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1872 for (var i = 0; i < pages.length; i++){
1873 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1876 var re = new RegExp (/_(\d{4})/);
1877 var reMatch = re.exec(pages[i].getAttribute('file'));
1878 var index = parseInt(reMatch[1], 10);
1879 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1881 var children = pages[i].childNodes;
1883 for (var j=0; j<children.length; j++) {
1884 //console.log(j + ' - ' + children[j].nodeName);
1885 //console.log(children[j].firstChild.nodeValue);
1886 if ('CONTEXT' == children[j].nodeName) {
1887 context += children[j].firstChild.nodeValue;
1888 } else if ('WORD' == children[j].nodeName) {
1889 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1891 var index = this.leafNumToIndex(index);
1892 if (null != index) {
1893 //coordinates are [left, bottom, right, top, [baseline]]
1894 //we'll skip baseline for now...
1895 var coords = children[j].getAttribute('coords').split(',',4);
1896 if (4 == coords.length) {
1897 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1902 var pageName = this.getPageName(index);
1903 //TODO: remove hardcoded instance name
1904 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1907 $('#GnuBookSearchResults').append('</ul>');
1909 this.updateSearchHilites();
1912 // updateSearchHilites()
1913 //______________________________________________________________________________
1914 GnuBook.prototype.updateSearchHilites = function() {
1915 if (2 == this.mode) {
1916 this.updateSearchHilites2UP();
1918 this.updateSearchHilites1UP();
1922 // showSearchHilites1UP()
1923 //______________________________________________________________________________
1924 GnuBook.prototype.updateSearchHilites1UP = function() {
1926 for (var key in this.searchResults) {
1928 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1929 var result = this.searchResults[key];
1930 if(null == result.div) {
1931 result.div = document.createElement('div');
1932 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1933 //console.log('appending ' + key);
1936 width: (result.r-result.l)/this.reduce + 'px',
1937 height: (result.b-result.t)/this.reduce + 'px',
1938 left: (result.l)/this.reduce + 'px',
1939 top: (result.t)/this.reduce +'px'
1943 //console.log(key + ' not displayed');
1944 this.searchResults[key].div=null;
1950 //______________________________________________________________________________
1951 // Returns the position of the gutter (line between the page images)
1952 GnuBook.prototype.twoPageGutter = function() {
1953 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1957 //______________________________________________________________________________
1958 // Returns the offset for the top of the page images
1959 GnuBook.prototype.twoPageTop = function() {
1960 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
1963 // twoPageCoverWidth()
1964 //______________________________________________________________________________
1965 // Returns the width of the cover div given the total page width
1966 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
1967 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
1970 // twoPageGetViewCenter()
1971 //______________________________________________________________________________
1972 // Returns the percentage offset into twopageview div at the center of container div
1973 // { percentageX: float, percentageY: float }
1974 GnuBook.prototype.twoPageGetViewCenter = function() {
1977 var containerOffset = $('#GBcontainer').offset();
1978 var viewOffset = $('#GBtwopageview').offset();
1979 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
1980 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
1985 // twoPageCenterView(percentageX, percentageY)
1986 //______________________________________________________________________________
1987 // Centers the point given by percentage from left,top of twopageview
1988 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
1989 if ('undefined' == typeof(percentageX)) {
1992 if ('undefined' == typeof(percentageY)) {
1996 var viewWidth = $('#GBtwopageview').width();
1997 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
1998 var intoViewX = percentageX * viewWidth;
2000 var viewHeight = $('#GBtwopageview').height();
2001 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2002 var intoViewY = percentageY * viewHeight;
2004 if (viewWidth < containerClientWidth) {
2005 // Can fit width without scrollbars - center by adjusting offset
2006 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2008 // Need to scroll to center
2009 $('#GBtwopageview').css('left', 0);
2010 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2013 if (viewHeight < containerClientHeight) {
2014 // Fits with scrollbars - add offset
2015 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2017 $('#GBtwopageview').css('top', 0);
2018 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2022 // showSearchHilites2UP()
2023 //______________________________________________________________________________
2024 GnuBook.prototype.updateSearchHilites2UP = function() {
2026 for (var key in this.searchResults) {
2027 key = parseInt(key, 10);
2028 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2029 var result = this.searchResults[key];
2030 if(null == result.div) {
2031 result.div = document.createElement('div');
2032 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2033 //console.log('appending ' + key);
2036 // We calculate the reduction factor for the specific page because it can be different
2037 // for each page in the spread
2038 var height = this.getPageHeight(key);
2039 var width = this.getPageWidth(key)
2040 var reduce = this.twoPage.height/height;
2041 var scaledW = parseInt(width*reduce);
2043 var gutter = this.twoPageGutter();
2045 if ('L' == this.getPageSide(key)) {
2046 pageL = gutter-scaledW;
2050 var pageT = this.twoPageTop();
2053 width: (result.r-result.l)*reduce + 'px',
2054 height: (result.b-result.t)*reduce + 'px',
2055 left: pageL+(result.l)*reduce + 'px',
2056 top: pageT+(result.t)*reduce +'px'
2060 //console.log(key + ' not displayed');
2061 if (null != this.searchResults[key].div) {
2062 //console.log('removing ' + key);
2063 $(this.searchResults[key].div).remove();
2065 this.searchResults[key].div=null;
2070 // removeSearchHilites()
2071 //______________________________________________________________________________
2072 GnuBook.prototype.removeSearchHilites = function() {
2073 for (var key in this.searchResults) {
2074 if (null != this.searchResults[key].div) {
2075 $(this.searchResults[key].div).remove();
2076 this.searchResults[key].div=null;
2082 //______________________________________________________________________________
2083 GnuBook.prototype.showEmbedCode = function() {
2084 if (null != this.embedPopup) { // check if already showing
2088 this.embedPopup = document.createElement("div");
2089 $(this.embedPopup).css({
2090 position: 'absolute',
2092 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2095 border: "3px double #999999",
2097 backgroundColor: "#fff"
2098 }).appendTo('#GnuBook');
2100 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2101 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>';
2102 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2103 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2105 this.embedPopup.innerHTML = htmlStr;
2106 $(this.embedPopup).find('input').bind('click', function() {
2112 //______________________________________________________________________________
2113 GnuBook.prototype.autoToggle = function() {
2115 var bComingFrom1up = false;
2116 if (2 != this.mode) {
2117 bComingFrom1up = true;
2121 // Change to autofit if book is too large
2122 if (this.reduce < this.twoPageGetAutofitReduce()) {
2127 if (null == this.autoTimer) {
2128 this.flipSpeed = 2000;
2130 // $$$ Draw events currently cause layout problems when they occur during animation.
2131 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2132 // we workaround for now by not triggering immediate animation in that case.
2133 // See https://bugs.launchpad.net/gnubook/+bug/328327
2134 if (('rl' == this.pageProgression) && bComingFrom1up) {
2135 // don't flip immediately -- wait until timer fires
2138 this.flipFwdToIndex();
2141 $('#GBtoolbar .play').hide();
2142 $('#GBtoolbar .pause').show();
2143 this.autoTimer=setInterval(function(){
2144 if (self.animating) {return;}
2146 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2147 self.flipBackToIndex(1); // $$$ really what we want?
2149 self.flipFwdToIndex();
2158 //______________________________________________________________________________
2159 // Stop autoplay mode, allowing animations to finish
2160 GnuBook.prototype.autoStop = function() {
2161 if (null != this.autoTimer) {
2162 clearInterval(this.autoTimer);
2163 this.flipSpeed = 'fast';
2164 $('#GBtoolbar .pause').hide();
2165 $('#GBtoolbar .play').show();
2166 this.autoTimer = null;
2170 // stopFlipAnimations
2171 //______________________________________________________________________________
2172 // Immediately stop flip animations. Callbacks are triggered.
2173 GnuBook.prototype.stopFlipAnimations = function() {
2175 this.autoStop(); // Clear timers
2177 // Stop animation, clear queue, trigger callbacks
2178 if (this.leafEdgeTmp) {
2179 $(this.leafEdgeTmp).stop(false, true);
2181 jQuery.each(this.prefetchedImgs, function() {
2182 $(this).stop(false, true);
2185 // And again since animations also queued in callbacks
2186 if (this.leafEdgeTmp) {
2187 $(this.leafEdgeTmp).stop(false, true);
2189 jQuery.each(this.prefetchedImgs, function() {
2190 $(this).stop(false, true);
2195 // keyboardNavigationIsDisabled(event)
2196 // - returns true if keyboard navigation should be disabled for the event
2197 //______________________________________________________________________________
2198 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2199 if (event.target.tagName == "INPUT") {
2205 // gutterOffsetForIndex
2206 //______________________________________________________________________________
2208 // Returns the gutter offset for the spread containing the given index.
2209 // This function supports RTL
2210 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2212 // To find the offset of the gutter from the middle we calculate our percentage distance
2213 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2214 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2216 // But then again for RTL it's the opposite
2217 if ('rl' == this.pageProgression) {
2225 //______________________________________________________________________________
2226 // Returns the width of the leaf edge div for the page with index given
2227 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2228 // $$$ could there be single pixel rounding errors for L vs R?
2229 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2230 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2232 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2236 // jumpIndexForLeftEdgePageX
2237 //______________________________________________________________________________
2238 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2239 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2240 if ('rl' != this.pageProgression) {
2241 // LTR - flipping backward
2242 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2244 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2245 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2249 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2250 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2255 // jumpIndexForRightEdgePageX
2256 //______________________________________________________________________________
2257 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2258 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2259 if ('rl' != this.pageProgression) {
2261 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2262 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2265 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2266 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2271 GnuBook.prototype.initToolbar = function(mode, ui) {
2273 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2274 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2275 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2276 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2277 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span>%</span>"
2278 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2279 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2280 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2283 if (ui == "embed") {
2284 $("#GnuBook a.logo").attr("target","_blank");
2287 // $$$ turn this into a member variable
2288 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2290 // We build in mode 2
2291 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2292 + "<button class='GBicon rollover embed' />"
2293 + "<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>"
2294 + "<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>"
2295 + "<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>"
2296 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2298 this.bindToolbarNavHandlers(jToolbar);
2300 // Setup tooltips -- later we could load these from a file for i18n
2301 var titles = { '.logo': 'Go to Archive.org',
2302 '.zoom_in': 'Zoom in',
2303 '.zoom_out': 'Zoom out',
2304 '.one_page_mode': 'One-page view',
2305 '.two_page_mode': 'Two-page view',
2306 '.embed': 'Embed bookreader',
2307 '.book_left': 'Flip left',
2308 '.book_right': 'Flip right',
2309 '.book_up': 'Page up',
2310 '.book_down': 'Page down',
2313 '.book_top': 'First page',
2314 '.book_bottom': 'Last page'
2316 if ('rl' == this.pageProgression) {
2317 titles['.book_leftmost'] = 'Last page';
2318 titles['.book_rightmost'] = 'First page';
2320 titles['.book_leftmost'] = 'First page';
2321 titles['.book_rightmost'] = 'Last page';
2324 for (var icon in titles) {
2325 jToolbar.find(icon).attr('title', titles[icon]);
2328 // Hide mode buttons and autoplay if 2up is not available
2329 // $$$ if we end up with more than two modes we should show the applicable buttons
2330 if ( !this.canSwitchToMode(this.constMode2up) ) {
2331 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2334 // Switch to requested mode -- binds other click handlers
2335 this.switchToolbarMode(mode);
2340 // switchToolbarMode
2341 //______________________________________________________________________________
2342 // Update the toolbar for the given mode (changes navigation buttons)
2343 // $$$ we should soon split the toolbar out into its own module
2344 GnuBook.prototype.switchToolbarMode = function(mode) {
2347 $('#GBtoolbar .GBtoolbarmode2').hide();
2348 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2351 $('#GBtoolbar .GBtoolbarmode1').hide();
2352 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2356 // bindToolbarNavHandlers
2357 //______________________________________________________________________________
2358 // Binds the toolbar handlers
2359 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2361 jToolbar.find('.book_left').bind('click', function(e) {
2366 jToolbar.find('.book_right').bind('click', function(e) {
2371 jToolbar.find('.book_up').bind('click', function(e) {
2376 jToolbar.find('.book_down').bind('click', function(e) {
2381 jToolbar.find('.embed').bind('click', function(e) {
2386 jToolbar.find('.play').bind('click', function(e) {
2391 jToolbar.find('.pause').bind('click', function(e) {
2396 jToolbar.find('.book_top').bind('click', function(e) {
2401 jToolbar.find('.book_bottom').bind('click', function(e) {
2406 jToolbar.find('.book_leftmost').bind('click', function(e) {
2411 jToolbar.find('.book_rightmost').bind('click', function(e) {
2417 // updateToolbarZoom(reduce)
2418 //______________________________________________________________________________
2419 // Update the displayed zoom factor based on reduction factor
2420 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2421 // $$$ TODO: Move toolbar to it's own object/plugin
2422 $('#GBzoom').text(parseInt(100/reduce));
2425 // firstDisplayableIndex
2426 //______________________________________________________________________________
2427 // Returns the index of the first visible page, dependent on the mode.
2428 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2429 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2430 GnuBook.prototype.firstDisplayableIndex = function() {
2431 if (this.mode == 0) {
2434 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2438 // lastDisplayableIndex
2439 //______________________________________________________________________________
2440 // Returns the index of the last visible page, dependent on the mode.
2441 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2442 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2443 GnuBook.prototype.lastDisplayableIndex = function() {
2444 if (this.mode == 2) {
2445 if (this.lastDisplayableIndex2up === null) {
2446 // Calculate and cache
2447 var candidate = this.numLeafs - 1;
2448 for ( ; candidate >= 0; candidate--) {
2449 var spreadIndices = this.getSpreadIndices(candidate);
2450 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2454 this.lastDisplayableIndex2up = candidate;
2456 return this.lastDisplayableIndex2up;
2458 return this.numLeafs - 1;
2462 // shortTitle(maximumCharacters)
2464 // Returns a shortened version of the title with the maximum number of characters
2465 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2466 if (this.bookTitle.length < maximumCharacters) {
2467 return this.bookTitle;
2470 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2477 // Parameter related functions
2479 // updateFromParams(params)
2481 // Update ourselves from the params object.
2483 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2484 GnuBook.prototype.updateFromParams = function(params) {
2485 if ('undefined' != typeof(params.mode)) {
2486 this.switchMode(params.mode);
2489 // $$$ process /search
2490 // $$$ process /zoom
2492 // We only respect page if index is not set
2493 if ('undefined' != typeof(params.index)) {
2494 if (params.index != this.currentIndex()) {
2495 this.jumpToIndex(params.index);
2497 } else if ('undefined' != typeof(params.page)) {
2498 // $$$ this assumes page numbers are unique
2499 if (params.page != this.getPageNum(this.currentIndex())) {
2500 this.jumpToPage(params.page);
2504 // $$$ process /region
2505 // $$$ process /highlight
2508 // paramsFromFragment(urlFragment)
2510 // Returns a object with configuration parametes from a URL fragment.
2512 // E.g paramsFromFragment(window.location.hash)
2513 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2514 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2518 // For convenience we allow an initial # character (as from window.location.hash)
2519 // but don't require it
2520 if (urlFragment.substr(0,1) == '#') {
2521 urlFragment = urlFragment.substr(1);
2524 // Simple #nn syntax
2525 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2526 if ( !isNaN(oldStyleLeafNum) ) {
2527 params.index = oldStyleLeafNum;
2529 // Done processing if using old-style syntax
2533 // Split into key-value pairs
2534 var urlArray = urlFragment.split('/');
2536 for (var i = 0; i < urlArray.length; i += 2) {
2537 urlHash[urlArray[i]] = urlArray[i+1];
2541 if ('1up' == urlHash['mode']) {
2542 params.mode = this.constMode1up;
2543 } else if ('2up' == urlHash['mode']) {
2544 params.mode = this.constMode2up;
2548 if ('undefined' != typeof(urlHash['page'])) {
2549 // page was set -- may not be int
2550 params.page = urlHash['page'];
2553 // $$$ process /region
2554 // $$$ process /search
2555 // $$$ process /highlight
2560 // paramsFromCurrent()
2562 // Create a params object from the current parameters.
2563 GnuBook.prototype.paramsFromCurrent = function() {
2567 var pageNum = this.getPageNum(this.currentIndex());
2568 if ((pageNum === 0) || pageNum) {
2569 params.page = pageNum;
2572 params.index = this.currentIndex();
2573 params.mode = this.mode;
2582 // fragmentFromParams(params)
2584 // Create a fragment string from the params object.
2585 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2586 GnuBook.prototype.fragmentFromParams = function(params) {
2587 var separator = '/';
2591 if ('undefined' != typeof(params.page)) {
2592 fragments.push('page', params.page);
2594 // Don't have page numbering -- use index instead
2595 fragments.push('page', 'n' + params.index);
2603 if ('undefined' != typeof(params.mode)) {
2604 if (params.mode == this.constMode1up) {
2605 fragments.push('mode', '1up');
2606 } else if (params.mode == this.constMode2up) {
2607 fragments.push('mode', '2up');
2609 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2613 return fragments.join(separator);
2616 // getPageIndex(pageNum)
2618 // Returns the *highest* index the given page number, or undefined
2619 GnuBook.prototype.getPageIndex = function(pageNum) {
2620 var pageIndices = this.getPageIndices(pageNum);
2622 if (pageIndices.length > 0) {
2623 return pageIndices[pageIndices.length - 1];
2629 // getPageIndices(pageNum)
2631 // Returns an array (possibly empty) of the indices with the given page number
2632 GnuBook.prototype.getPageIndices = function(pageNum) {
2635 // Check for special "nXX" page number
2636 if (pageNum.slice(0,1) == 'n') {
2638 var pageIntStr = pageNum.slice(1, pageNum.length);
2639 var pageIndex = parseInt(pageIntStr);
2640 indices.append(pageIndex);
2643 // Do nothing... will run through page names and see if one matches
2648 for (i=0; i<this.numLeafs; i++) {
2649 if (this.getPageNum(i) == pageNum) {
2657 // getPageName(index)
2659 // Returns the name of the page as it should be displayed in the user interface
2660 GnuBook.prototype.getPageName = function(index) {
2661 return 'Page ' + this.getPageNum(index);
2664 // updateLocationHash
2666 // Update the location hash from the current parameters. Call this instead of manually
2667 // using window.location.replace
2668 GnuBook.prototype.updateLocationHash = function() {
2669 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2670 window.location.replace(newHash);
2672 // This is the variable checked in the timer. Only user-generated changes
2673 // to the URL will trigger the event.
2674 this.oldLocationHash = newHash;
2677 // startLocationPolling
2679 // Starts polling of window.location to see hash fragment changes
2680 GnuBook.prototype.startLocationPolling = function() {
2681 var self = this; // remember who I am
2682 self.oldLocationHash = window.location.hash;
2684 if (this.locationPollId) {
2685 clearInterval(this.locationPollID);
2686 this.locationPollId = null;
2689 this.locationPollId = setInterval(function() {
2690 var newHash = window.location.hash;
2691 if (newHash != self.oldLocationHash) {
2692 if (newHash != self.oldUserHash) { // Only process new user hash once
2693 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2695 // Queue change if animating
2696 if (self.animating) {
2698 self.animationFinishedCallback = function() {
2699 self.updateFromParams(self.paramsFromFragment(newHash));
2701 } else { // update immediately
2702 self.updateFromParams(self.paramsFromFragment(newHash));
2704 self.oldUserHash = newHash;
2712 // Returns a URL for an embedded version of the current book
2713 GnuBook.prototype.getEmbedURL = function() {
2714 // We could generate a URL hash fragment here but for now we just leave at defaults
2715 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2720 // Returns the embed code HTML fragment suitable for copy and paste
2721 GnuBook.prototype.getEmbedCode = function() {
2722 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2727 // Returns true if we can switch to the requested mode
2728 GnuBook.prototype.canSwitchToMode = function(mode) {
2729 if (mode == this.constMode2up) {
2730 // check there are enough pages to display
2731 // $$$ this is a workaround for the mis-feature that we can't display
2732 // short books in 2up mode
2733 if (this.numLeafs < 6) {
2741 // Library functions
2743 clamp: function(value, min, max) {
2744 return Math.min(Math.max(value, min), max);