2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GnuBook is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
31 // You must also add a numLeafs property before calling init().
36 this.mode = 1; //1 or 2
37 this.ui = 'full'; // UI mode
39 this.displayedIndices = [];
40 //this.indicesToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
45 this.animating = false;
47 this.autoTimer = null;
48 this.flipSpeed = 'fast';
50 this.twoPagePopUp = null;
51 this.leafEdgeTmp = null;
52 this.embedPopup = null;
54 this.searchResults = {};
56 this.firstIndex = null;
58 this.lastDisplayableIndex2up = null;
60 // We link to index.php to avoid redirect which breaks back button
61 this.logoURL = 'http://www.archive.org/index.php';
63 // Base URL for images
64 this.imagesBaseURL = '/bookreader/images/';
67 this.constMode1up = 1;
68 this.constMode2up = 2;
71 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
73 // Object to hold parameters related to 2up mode
75 coverInternalPadding: 10, // Width of cover
76 coverExternalPadding: 10, // Padding outside of cover
77 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
86 var startIndex = undefined;
88 // Find start index and mode if set in location hash
89 var params = this.paramsFromFragment(window.location.hash);
91 if ('undefined' != typeof(params.index)) {
92 startIndex = params.index;
93 } else if ('undefined' != typeof(params.page)) {
94 startIndex = this.getPageIndex(params.page);
97 if ('undefined' == typeof(startIndex)) {
98 if ('undefined' != typeof(this.titleLeaf)) {
99 startIndex = this.leafNumToIndex(this.titleLeaf);
103 if ('undefined' == typeof(startIndex)) {
107 if ('undefined' != typeof(params.mode)) {
108 this.mode = params.mode;
111 // Set document title -- may have already been set in enclosing html for
112 // search engine visibility
113 document.title = this.shortTitle(50);
115 // Sanitize parameters
116 if ( !this.canSwitchToMode( this.mode ) ) {
117 this.mode = this.constMode1up;
120 $("#GnuBook").empty();
121 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122 $("#GnuBook").append("<div id='GBcontainer'></div>");
123 $("#GBcontainer").append("<div id='GBpageview'></div>");
125 $("#GBcontainer").bind('scroll', this, function(e) {
129 this.setupKeyListeners();
130 this.startLocationPolling();
132 $(window).bind('resize', this, function(e) {
133 //console.log('resize!');
134 if (1 == e.data.mode) {
135 //console.log('centering 1page view');
136 e.data.centerPageView();
137 $('#GBpageview').empty()
138 e.data.displayedIndices = [];
139 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
142 //console.log('drawing 2 page view');
144 // We only need to prepare again in autofit (size of spread changes)
145 if (e.data.twoPage.autofit) {
146 e.data.prepareTwoPageView();
148 // Re-center if the scrollbars have disappeared
149 var center = e.data.twoPageGetViewCenter();
150 var doRecenter = false;
151 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
152 center.percentageX = 0.5;
155 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
156 center.percentageY = 0.5;
160 e.data.twoPageCenterView(center.percentageX, center.percentageY);
166 $('.GBpagediv1up').bind('mousedown', this, function(e) {
167 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
168 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
171 if (1 == this.mode) {
172 this.resizePageView();
173 this.firstIndex = startIndex;
174 this.jumpToIndex(startIndex);
176 //this.resizePageView();
178 this.displayedIndices=[0];
179 this.firstIndex = startIndex;
180 this.displayedIndices = [this.firstIndex];
181 //console.log('titleLeaf: %d', this.titleLeaf);
182 //console.log('displayedIndices: %s', this.displayedIndices);
183 this.prepareTwoPageView();
186 // Enact other parts of initial params
187 this.updateFromParams(params);
190 GnuBook.prototype.setupKeyListeners = function() {
203 // We use document here instead of window to avoid a bug in jQuery on IE7
204 $(document).keydown(function(e) {
206 // Keyboard navigation
210 // In 1up mode page scrolling is handled by browser
211 if (2 == self.mode) {
217 if (2 == self.mode) {
228 if (self.keyboardNavigationIsDisabled(e)) {
231 if (2 == self.mode) {
236 if (self.keyboardNavigationIsDisabled(e)) {
239 if (2 == self.mode) {
248 //______________________________________________________________________________
249 GnuBook.prototype.drawLeafs = function() {
250 if (1 == this.mode) {
251 this.drawLeafsOnePage();
253 this.drawLeafsTwoPage();
258 //______________________________________________________________________________
259 GnuBook.prototype.setDragHandler = function(div) {
260 div.dragging = false;
262 $(div).unbind('mousedown').bind('mousedown', function(e) {
265 //console.log('mousedown at ' + e.pageY);
267 this.dragging = true;
268 this.prevMouseX = e.pageX;
269 this.prevMouseY = e.pageY;
271 var startX = e.pageX;
272 var startY = e.pageY;
273 var startTop = $('#GBcontainer').attr('scrollTop');
274 var startLeft = $('#GBcontainer').attr('scrollLeft');
278 $(div).unbind('mousemove').bind('mousemove', function(ee) {
281 //console.log('mousemove ' + startY);
283 var offsetX = ee.pageX - this.prevMouseX;
284 var offsetY = ee.pageY - this.prevMouseY;
287 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
288 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
291 this.prevMouseX = ee.pageX;
292 this.prevMouseY = ee.pageY;
296 $(div).unbind('mouseup').bind('mouseup', function(ee) {
298 //console.log('mouseup');
300 this.dragging = false;
303 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
305 //console.log('mouseleave');
307 this.dragging = false;
310 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
312 //console.log('mouseenter');
314 this.dragging = false;
318 // drawLeafsOnePage()
319 //______________________________________________________________________________
320 GnuBook.prototype.drawLeafsOnePage = function() {
321 //alert('drawing leafs!');
325 var scrollTop = $('#GBcontainer').attr('scrollTop');
326 var scrollBottom = scrollTop + $('#GBcontainer').height();
327 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
329 var indicesToDisplay = [];
334 for (i=0; i<this.numLeafs; i++) {
335 var height = parseInt(this.getPageHeight(i)/this.reduce);
337 leafBottom += height;
338 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
339 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
340 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
341 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
342 if (topInView | bottomInView | middleInView) {
343 //console.log('displayed: ' + this.displayedIndices);
344 //console.log('to display: ' + i);
345 indicesToDisplay.push(i);
347 leafTop += height +10;
351 var firstIndexToDraw = indicesToDisplay[0];
352 this.firstIndex = firstIndexToDraw;
354 // Update hash, but only if we're currently displaying a leaf
355 // Hack that fixes #365790
356 if (this.displayedIndices.length > 0) {
357 this.updateLocationHash();
360 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
362 indicesToDisplay.unshift(firstIndexToDraw);
365 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
366 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
367 indicesToDisplay.push(lastIndexToDraw+1);
372 for (i=0; i<firstIndexToDraw; i++) {
373 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
376 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
377 var viewWidth = $('#GBcontainer').attr('scrollWidth');
380 for (i=0; i<indicesToDisplay.length; i++) {
381 var index = indicesToDisplay[i];
382 var height = parseInt(this.getPageHeight(index)/this.reduce);
384 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
385 var width = parseInt(this.getPageWidth(index)/this.reduce);
386 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
387 var div = document.createElement("div");
388 div.className = 'GBpagediv1up';
389 div.id = 'pagediv'+index;
390 div.style.position = "absolute";
391 $(div).css('top', leafTop + 'px');
392 var left = (viewWidth-width)>>1;
393 if (left<0) left = 0;
394 $(div).css('left', left+'px');
395 $(div).css('width', width+'px');
396 $(div).css('height', height+'px');
397 //$(div).text('loading...');
399 this.setDragHandler(div);
401 $('#GBpageview').append(div);
403 var img = document.createElement("img");
404 img.src = this.getPageURI(index);
405 $(img).css('width', width+'px');
406 $(img).css('height', height+'px');
410 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
413 leafTop += height +10;
417 for (i=0; i<this.displayedIndices.length; i++) {
418 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
419 var index = this.displayedIndices[i];
420 //console.log('Removing leaf ' + index);
421 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
422 $('#pagediv'+index).remove();
424 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
428 this.displayedIndices = indicesToDisplay.slice();
429 this.updateSearchHilites();
431 if (null != this.getPageNum(firstIndexToDraw)) {
432 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
434 $("#GBpagenum").val('');
437 this.updateToolbarZoom(this.reduce);
441 // drawLeafsTwoPage()
442 //______________________________________________________________________________
443 GnuBook.prototype.drawLeafsTwoPage = function() {
444 var scrollTop = $('#GBtwopageview').attr('scrollTop');
445 var scrollBottom = scrollTop + $('#GBtwopageview').height();
447 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
449 var indexL = this.twoPage.currentIndexL;
450 var heightL = this.getPageHeight(indexL);
451 var widthL = this.getPageWidth(indexL);
453 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
454 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
455 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
456 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
457 //console.log(leafEdgeWidthL);
459 var middle = this.twoPage.middle; // $$$ getter instead?
460 var top = this.twoPageTop();
461 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
463 var scaledWL = this.getPageWidth2UP(indexL);
464 var gutter = this.twoPageGutter();
466 this.prefetchImg(indexL);
467 $(this.prefetchedImgs[indexL]).css({
468 position: 'absolute',
469 left: gutter-scaledWL+'px',
472 backgroundColor: 'rgb(234, 226, 205)',
473 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
474 width: scaledWL + 'px',
475 borderRight: '1px solid black',
477 }).appendTo('#GBtwopageview');
480 var indexR = this.twoPage.currentIndexR;
481 var heightR = this.getPageHeight(indexR);
482 var widthR = this.getPageWidth(indexR);
484 // $$$ should use getwidth2up?
485 //var scaledWR = this.twoPage.height*widthR/heightR;
486 var scaledWR = this.getPageWidth2UP(indexR);
487 this.prefetchImg(indexR);
488 $(this.prefetchedImgs[indexR]).css({
489 position: 'absolute',
493 backgroundColor: 'rgb(234, 226, 205)',
494 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
495 width: scaledWR + 'px',
496 borderLeft: '1px solid black',
498 }).appendTo('#GBtwopageview');
501 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
502 this.setClickHandlers();
503 this.twoPageSetCursor();
505 this.updatePageNumBox2UP();
506 this.updateToolbarZoom(this.reduce);
509 // updatePageNumBox2UP
510 //______________________________________________________________________________
511 GnuBook.prototype.updatePageNumBox2UP = function() {
512 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
513 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
515 $("#GBpagenum").val('');
517 this.updateLocationHash();
521 //______________________________________________________________________________
522 GnuBook.prototype.loadLeafs = function() {
526 if (null == this.timer) {
527 this.timer=setTimeout(function(){self.drawLeafs()},250);
529 clearTimeout(this.timer);
530 this.timer=setTimeout(function(){self.drawLeafs()},250);
536 // Pass 1 to zoom in, anything else to zoom out
537 //______________________________________________________________________________
538 GnuBook.prototype.zoom = function(direction) {
540 case this.constMode1up:
541 return this.zoom1up(direction);
542 case this.constMode2up:
543 return this.zoom2up(direction);
548 //______________________________________________________________________________
549 GnuBook.prototype.zoom1up = function(dir) {
550 if (2 == this.mode) { //can only zoom in 1-page mode
555 // $$$ with flexible zoom we could "snap" to /2 page reductions
556 // for better scaling
558 if (this.reduce <= 0.5) return;
559 this.reduce*=0.5; //zoom in
561 if (this.reduce >= 8) return;
562 this.reduce*=2; //zoom out
565 this.resizePageView();
567 $('#GBpageview').empty()
568 this.displayedIndices = [];
571 this.updateToolbarZoom(this.reduce);
575 //______________________________________________________________________________
576 GnuBook.prototype.resizePageView = function() {
579 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
580 var viewWidth = $('#GBcontainer').attr('clientWidth');
582 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
583 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
584 var oldPageViewHeight = $('#GBpageview').height();
585 var oldPageViewWidth = $('#GBpageview').width();
587 var oldCenterY = this.centerY1up();
588 var oldCenterX = this.centerX1up();
590 if (0 != oldPageViewHeight) {
591 var scrollRatio = oldCenterY / oldPageViewHeight;
596 for (i=0; i<this.numLeafs; i++) {
597 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
598 var width = parseInt(this.getPageWidth(i)/this.reduce);
599 if (width>viewWidth) viewWidth=width;
601 $('#GBpageview').height(viewHeight);
602 $('#GBpageview').width(viewWidth);
604 var newCenterY = scrollRatio*viewHeight;
605 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
606 $('#GBcontainer').attr('scrollTop', newTop);
608 // We use clientWidth here to avoid miscalculating due to scroll bar
609 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
610 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
611 newLeft = Math.max(newLeft, 0);
612 $('#GBcontainer').attr('scrollLeft', newLeft);
613 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
615 //this.centerPageView();
621 //______________________________________________________________________________
622 // Returns the current offset of the viewport center in scaled document coordinates.
623 GnuBook.prototype.centerX1up = function() {
625 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
626 centerX = $('#GBpageview').width();
628 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
630 centerX = Math.floor(centerX);
635 //______________________________________________________________________________
636 // Returns the current offset of the viewport center in scaled document coordinates.
637 GnuBook.prototype.centerY1up = function() {
638 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
639 return Math.floor(centerY);
643 //______________________________________________________________________________
644 GnuBook.prototype.centerPageView = function() {
646 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
647 var clientWidth = $('#GBcontainer').attr('clientWidth');
648 //console.log('sW='+scrollWidth+' cW='+clientWidth);
649 if (scrollWidth > clientWidth) {
650 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
655 // zoom2up(direction)
656 //______________________________________________________________________________
657 GnuBook.prototype.zoom2up = function(direction) {
659 // Hard stop autoplay
660 this.stopFlipAnimations();
662 // Get new zoom state
663 var newZoom = this.twoPageNextReduce(this.reduce, direction);
664 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
667 this.twoPage.autofit = newZoom.autofit;
668 this.reduce = newZoom.reduce;
670 // Preserve view center position
671 var oldCenter = this.twoPageGetViewCenter();
673 // Prepare view with new center to minimize visual glitches
674 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
678 // quantizeReduce(reduce)
679 //______________________________________________________________________________
680 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
681 GnuBook.prototype.quantizeReduce = function(reduce) {
682 var quantized = this.reductionFactors[0];
683 var distance = Math.abs(reduce - quantized);
684 for (var i = 1; i < this.reductionFactors.length; i++) {
685 newDistance = Math.abs(reduce - this.reductionFactors[i]);
686 if (newDistance < distance) {
687 distance = newDistance;
688 quantized = this.reductionFactors[i];
695 // twoPageNextReduce()
696 //______________________________________________________________________________
697 // Returns the next reduction level
698 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
700 var autofitReduce = this.twoPageGetAutofitReduce();
702 if (0 == direction) { // autofit
703 result.autofit = true;
704 result.reduce = autofitReduce;
706 } else if (1 == direction) { // zoom in
707 var newReduce = this.reductionFactors[0];
709 for (var i = 1; i < this.reductionFactors.length; i++) {
710 if (this.reductionFactors[i] < reduce) {
711 newReduce = this.reductionFactors[i];
715 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
717 result.autofit = true;
718 result.reduce = autofitReduce;
720 result.autofit = false;
721 result.reduce = newReduce;
725 var lastIndex = this.reductionFactors.length - 1;
726 var newReduce = this.reductionFactors[lastIndex];
728 for (var i = lastIndex; i >= 0; i--) {
729 if (this.reductionFactors[i] > reduce) {
730 newReduce = this.reductionFactors[i];
734 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
736 result.autofit = true;
737 result.reduce = autofitReduce;
739 result.autofit = false;
740 result.reduce = newReduce;
748 //______________________________________________________________________________
749 // Attempts to jump to page. Returns true if page could be found, false otherwise.
750 GnuBook.prototype.jumpToPage = function(pageNum) {
752 var pageIndex = this.getPageIndex(pageNum);
754 if ('undefined' != typeof(pageIndex)) {
757 this.jumpToIndex(pageIndex);
758 $('#GBcontainer').attr('scrollTop', leafTop);
767 //______________________________________________________________________________
768 GnuBook.prototype.jumpToIndex = function(index) {
770 if (2 == this.mode) {
773 // By checking against min/max we do nothing if requested index
775 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
776 this.flipBackToIndex(index);
777 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
778 this.flipFwdToIndex(index);
785 for (i=0; i<index; i++) {
786 h = parseInt(this.getPageHeight(i)/this.reduce);
787 leafTop += h + this.padding;
789 //$('#GBcontainer').attr('scrollTop', leafTop);
790 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
797 //______________________________________________________________________________
798 GnuBook.prototype.switchMode = function(mode) {
800 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
802 if (mode == this.mode) return;
804 if (!this.canSwitchToMode(mode)) {
809 this.removeSearchHilites();
813 this.switchToolbarMode(mode);
815 // $$$ TODO preserve center of view when switching between mode
816 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
819 this.reduce = this.quantizeReduce(this.reduce);
820 this.prepareOnePageView();
822 this.twoPage.autofit = false; // Take zoom level from other mode
823 this.reduce = this.quantizeReduce(this.reduce);
824 this.prepareTwoPageView();
825 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
830 //prepareOnePageView()
831 //______________________________________________________________________________
832 GnuBook.prototype.prepareOnePageView = function() {
834 // var startLeaf = this.displayedIndices[0];
835 var startLeaf = this.currentIndex();
837 $('#GBcontainer').empty();
838 $('#GBcontainer').css({
843 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
845 this.resizePageView();
847 this.jumpToIndex(startLeaf);
848 this.displayedIndices = [];
850 this.drawLeafsOnePage();
852 // Bind mouse handlers
853 // Disable mouse click to avoid selected/highlighted page images - bug 354239
854 gbPageView.bind('mousedown', function(e) {
855 // $$$ check here for right-click and don't disable. Also use jQuery style
856 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
859 // Special hack for IE7
860 gbPageView[0].onselectstart = function(e) { return false; };
863 // prepareTwoPageView()
864 //______________________________________________________________________________
865 // Some decisions about two page view:
867 // Both pages will be displayed at the same height, even if they were different physical/scanned
868 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
869 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
870 // aspect ratio to determine the height.
872 // The two page view div is resized to keep the middle of the book in the middle of the div
873 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
874 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
875 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
876 $('#GBcontainer').empty();
877 $('#GBcontainer').css('overflow', 'auto');
879 // We want to display two facing pages. We may be missing
880 // one side of the spread because it is the first/last leaf,
881 // foldouts, missing pages, etc
883 //var targetLeaf = this.displayedIndices[0];
884 var targetLeaf = this.firstIndex;
886 if (targetLeaf < this.firstDisplayableIndex()) {
887 targetLeaf = this.firstDisplayableIndex();
890 if (targetLeaf > this.lastDisplayableIndex()) {
891 targetLeaf = this.lastDisplayableIndex();
894 this.twoPage.currentIndexL = null;
895 this.twoPage.currentIndexR = null;
896 this.pruneUnusedImgs();
898 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
899 this.twoPage.currentIndexL = currentSpreadIndices[0];
900 this.twoPage.currentIndexR = currentSpreadIndices[1];
901 this.firstIndex = this.twoPage.currentIndexL;
903 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height
905 //console.dir(this.twoPage);
907 // Add the two page view
908 // $$$ Can we get everything set up and then append?
909 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
911 // $$$ calculate first then set
912 $('#GBtwopageview').css( {
913 height: this.twoPage.totalHeight + 'px',
914 width: this.twoPage.totalWidth + 'px',
918 // If there will not be scrollbars (e.g. when zooming out) we center the book
919 // since otherwise the book will be stuck off-center
920 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
921 centerPercentageX = 0.5;
923 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
924 centerPercentageY = 0.5;
927 this.twoPageCenterView(centerPercentageX, centerPercentageY);
929 this.twoPage.coverDiv = document.createElement('div');
930 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
931 border: '1px solid rgb(68, 25, 17)',
932 width: this.twoPage.bookCoverDivWidth + 'px',
933 height: this.twoPage.bookCoverDivHeight+'px',
934 visibility: 'visible',
935 position: 'absolute',
936 backgroundColor: '#663929',
937 left: this.twoPage.bookCoverDivLeft + 'px',
938 top: this.twoPage.bookCoverDivTop+'px',
939 MozBorderRadiusTopleft: '7px',
940 MozBorderRadiusTopright: '7px',
941 MozBorderRadiusBottomright: '7px',
942 MozBorderRadiusBottomleft: '7px'
943 }).appendTo('#GBtwopageview');
945 this.leafEdgeR = document.createElement('div');
946 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
947 $(this.leafEdgeR).css({
948 borderStyle: 'solid solid solid none',
949 borderColor: 'rgb(51, 51, 34)',
950 borderWidth: '1px 1px 1px 0px',
951 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
952 width: this.twoPage.leafEdgeWidthR + 'px',
953 height: this.twoPage.height-1 + 'px',
955 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
956 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
958 }).appendTo('#GBtwopageview');
960 this.leafEdgeL = document.createElement('div');
961 this.leafEdgeL.className = 'leafEdgeL';
962 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
963 borderStyle: 'solid none solid solid',
964 borderColor: 'rgb(51, 51, 34)',
965 borderWidth: '1px 0px 1px 1px',
966 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
967 width: this.twoPage.leafEdgeWidthL + 'px',
968 height: this.twoPage.height-1 + 'px',
969 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
970 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
972 }).appendTo('#GBtwopageview');
974 div = document.createElement('div');
975 $(div).attr('id', 'GBbookspine').css({
976 border: '1px solid rgb(68, 25, 17)',
977 width: this.twoPage.bookSpineDivWidth+'px',
978 height: this.twoPage.bookSpineDivHeight+'px',
979 position: 'absolute',
980 backgroundColor: 'rgb(68, 25, 17)',
981 left: this.twoPage.bookSpineDivLeft+'px',
982 top: this.twoPage.bookSpineDivTop+'px'
983 }).appendTo('#GBtwopageview');
985 this.prepareTwoPagePopUp();
987 this.displayedIndices = [];
989 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
990 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
992 this.drawLeafsTwoPage();
993 this.updateSearchHilites2UP();
994 this.updateToolbarZoom(this.reduce);
999 // prepareTwoPagePopUp()
1001 // This function prepares the "View Page n" popup that shows while the mouse is
1002 // over the left/right "stack of sheets" edges. It also binds the mouse
1003 // events for these divs.
1004 //______________________________________________________________________________
1005 GnuBook.prototype.prepareTwoPagePopUp = function() {
1007 this.twoPagePopUp = document.createElement('div');
1008 $(this.twoPagePopUp).css({
1009 border: '1px solid black',
1011 position: 'absolute',
1012 fontFamily: 'sans-serif',
1015 backgroundColor: 'rgb(255, 255, 238)',
1017 }).appendTo('#GBcontainer');
1018 $(this.twoPagePopUp).hide();
1020 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1021 $(e.data.twoPagePopUp).show();
1024 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1025 $(e.data.twoPagePopUp).hide();
1028 $(this.leafEdgeL).bind('click', this, function(e) {
1030 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1031 e.data.jumpToIndex(jumpIndex);
1034 $(this.leafEdgeR).bind('click', this, function(e) {
1036 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1037 e.data.jumpToIndex(jumpIndex);
1040 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1042 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1043 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1045 // $$$ TODO: Make sure popup is positioned so that it is in view
1046 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1047 $(e.data.twoPagePopUp).css({
1048 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1049 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1053 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1055 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1056 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1058 // $$$ TODO: Make sure popup is positioned so that it is in view
1059 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1060 $(e.data.twoPagePopUp).css({
1061 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1062 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1067 // calculateSpreadSize()
1068 //______________________________________________________________________________
1069 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1070 // this.twoPage.currentIndexR
1071 // This function sets this.twoPage.height, twoPage.width
1073 GnuBook.prototype.calculateSpreadSize = function() {
1075 var firstIndex = this.twoPage.currentIndexL;
1076 var secondIndex = this.twoPage.currentIndexR;
1077 //console.log('first page is ' + firstIndex);
1079 // Calculate page sizes and total leaf width
1081 if ( this.twoPage.autofit) {
1082 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1084 // set based on reduction factor
1085 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1088 // Both pages together
1089 this.twoPage.height = spreadSize.height;
1090 this.twoPage.width = spreadSize.width;
1093 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1094 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1097 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1098 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1099 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1103 // The width of the book cover div. The combined width of both pages, twice the width
1104 // of the book cover internal padding (2*10) and the page edges
1105 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1106 // The height of the book cover div
1107 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1110 // We calculate the total width and height for the div so that we can make the book
1112 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1113 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1114 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1115 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1116 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1117 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1119 // We want to minimize the unused space in two-up mode (maximize the amount of page
1120 // shown). We give width to the leaf edges and these widths change (though the sum
1121 // of the two remains constant) as we flip through the book. With the book
1122 // cover centered and fixed in the GBcontainer div the page images will meet
1123 // at the "gutter" which is generally offset from the center.
1124 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1125 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1127 // The left edge of the book cover moves depending on the width of the pages
1128 // $$$ change to getter
1129 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1130 // The top edge of the book cover stays a fixed distance from the top
1131 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1134 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1135 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1136 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1139 this.reduce = spreadSize.reduce; // $$$ really set this here?
1142 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1145 // We check which page is closest to a "normal" page and use that to set the height
1146 // for both pages. This means that foldouts and other odd size pages will be displayed
1147 // smaller than the nominal zoom amount.
1148 var canon5Dratio = 1.5;
1151 height: this.getPageHeight(firstIndex),
1152 width: this.getPageWidth(firstIndex)
1156 height: this.getPageHeight(secondIndex),
1157 width: this.getPageWidth(secondIndex)
1160 var firstIndexRatio = first.height / first.width;
1161 var secondIndexRatio = second.height / second.width;
1162 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1165 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1166 ratio = firstIndexRatio;
1167 //console.log('using firstIndexRatio ' + ratio);
1169 ratio = secondIndexRatio;
1170 //console.log('using secondIndexRatio ' + ratio);
1173 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1174 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1175 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1177 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1178 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1180 ideal.width = ($('#GBcontainer').attr('clientWidth') - widthOutsidePages) >> 1;
1181 ideal.width -= 10; // $$$ fudge factor
1182 ideal.height = $('#GBcontainer').attr('clientHeight') - heightOutsidePages;
1183 ideal.height -= 20; // fudge factor
1184 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1186 if (ideal.height/ratio <= ideal.width) {
1188 ideal.width = parseInt(ideal.height/ratio);
1191 ideal.height = parseInt(ideal.width*ratio);
1194 // $$$ check this logic with large spreads
1195 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1200 // getSpreadSizeFromReduce()
1201 //______________________________________________________________________________
1202 // Returns the spread size calculated from the reduction factor for the given pages
1203 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1204 var spreadSize = {};
1205 // $$$ Scale this based on reduce?
1206 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1207 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1208 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1210 // $$$ Possibly incorrect -- we should make height "dominant"
1211 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1212 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1213 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1214 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1215 spreadSize.reduce = reduce;
1220 // twoPageGetAutofitReduce()
1221 //______________________________________________________________________________
1222 // Returns the current ideal reduction factor
1223 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1224 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1225 return spreadSize.reduce;
1228 // twoPageSetCursor()
1229 //______________________________________________________________________________
1230 // Set the cursor for two page view
1231 GnuBook.prototype.twoPageSetCursor = function() {
1232 // console.log('setting cursor');
1233 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1234 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1235 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1236 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1238 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1239 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1244 //______________________________________________________________________________
1245 // Returns the currently active index.
1246 GnuBook.prototype.currentIndex = function() {
1247 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1248 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1249 return this.firstIndex;
1251 throw 'currentIndex called for unimplemented mode ' + this.mode;
1256 //______________________________________________________________________________
1257 // Flip the right page over onto the left
1258 GnuBook.prototype.right = function() {
1259 if ('rl' != this.pageProgression) {
1269 //______________________________________________________________________________
1270 // Flip to the rightmost page
1271 GnuBook.prototype.rightmost = function() {
1272 if ('rl' != this.pageProgression) {
1280 //______________________________________________________________________________
1281 // Flip the left page over onto the right.
1282 GnuBook.prototype.left = function() {
1283 if ('rl' != this.pageProgression) {
1293 //______________________________________________________________________________
1294 // Flip to the leftmost page
1295 GnuBook.prototype.leftmost = function() {
1296 if ('rl' != this.pageProgression) {
1304 //______________________________________________________________________________
1305 GnuBook.prototype.next = function() {
1306 if (2 == this.mode) {
1308 this.flipFwdToIndex(null);
1310 if (this.firstIndex < this.lastDisplayableIndex()) {
1311 this.jumpToIndex(this.firstIndex+1);
1317 //______________________________________________________________________________
1318 GnuBook.prototype.prev = function() {
1319 if (2 == this.mode) {
1321 this.flipBackToIndex(null);
1323 if (this.firstIndex >= 1) {
1324 this.jumpToIndex(this.firstIndex-1);
1329 GnuBook.prototype.first = function() {
1330 if (2 == this.mode) {
1331 this.jumpToIndex(2);
1334 this.jumpToIndex(0);
1338 GnuBook.prototype.last = function() {
1339 if (2 == this.mode) {
1340 this.jumpToIndex(this.lastDisplayableIndex());
1343 this.jumpToIndex(this.lastDisplayableIndex());
1347 // flipBackToIndex()
1348 //______________________________________________________________________________
1349 // to flip back one spread, pass index=null
1350 GnuBook.prototype.flipBackToIndex = function(index) {
1351 if (1 == this.mode) return;
1353 var leftIndex = this.twoPage.currentIndexL;
1355 // $$$ Need to change this to be able to see first spread.
1356 // See https://bugs.launchpad.net/gnubook/+bug/296788
1357 if (leftIndex <= 2) return;
1358 if (this.animating) return;
1360 if (null != this.leafEdgeTmp) {
1361 alert('error: leafEdgeTmp should be null!');
1365 if (null == index) {
1366 index = leftIndex-2;
1368 //if (index<0) return;
1370 var previousIndices = this.getSpreadIndices(index);
1372 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1376 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1378 this.animating = true;
1380 if ('rl' != this.pageProgression) {
1381 // Assume LTR and we are going backward
1382 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1383 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1385 // RTL and going backward
1386 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1387 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1391 // flipLeftToRight()
1392 //______________________________________________________________________________
1393 // Flips the page on the left towards the page on the right
1394 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1396 var leftLeaf = this.twoPage.currentIndexL;
1398 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1399 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1400 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1402 var currWidthL = this.getPageWidth2UP(leftLeaf);
1403 var newWidthL = this.getPageWidth2UP(newIndexL);
1404 var newWidthR = this.getPageWidth2UP(newIndexR);
1406 var top = this.twoPageTop();
1407 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1409 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1410 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1412 //animation strategy:
1413 // 0. remove search highlight, if any.
1414 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1415 // of the left leaf and where the user clicked in the leaf edge.
1416 // Note that if this function was triggered by left() and not a
1417 // mouse click, the width of leafEdgeTmp is very small (zero px).
1418 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1419 // leftLeaf to width=0.
1420 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1421 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1422 // its new full width.
1423 // 4. After step 3 is finished, do the following:
1424 // - remove leafEdgeTmp from the dom.
1425 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1426 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1427 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1428 // and width=newLeafEdgeWidthL.
1429 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1430 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1431 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1432 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1433 // - prefetch new adjacent leafs.
1434 // - set up click handlers for both new left and right leafs.
1435 // - redraw the search highlight.
1436 // - update the pagenum box and the url.
1439 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1441 this.leafEdgeTmp = document.createElement('div');
1442 $(this.leafEdgeTmp).css({
1443 borderStyle: 'solid none solid solid',
1444 borderColor: 'rgb(51, 51, 34)',
1445 borderWidth: '1px 0px 1px 1px',
1446 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1447 width: leafEdgeTmpW + 'px',
1448 height: this.twoPage.height-1 + 'px',
1449 left: leftEdgeTmpLeft + 'px',
1451 position: 'absolute',
1453 }).appendTo('#GBtwopageview');
1455 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1456 $(this.leafEdgeL).css({
1457 width: newLeafEdgeWidthL+'px',
1458 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1461 // Left gets the offset of the current left leaf from the document
1462 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1463 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1464 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1466 // We change the left leaf to right positioning
1467 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1468 $(this.prefetchedImgs[leftLeaf]).css({
1473 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1474 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1478 this.removeSearchHilites();
1480 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1481 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1483 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1484 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1486 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1487 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1488 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1490 $(self.leafEdgeR).css({
1491 // Moves the right leaf edge
1492 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1493 left: gutter+newWidthR+'px'
1496 $(self.leafEdgeL).css({
1497 // Moves and resizes the left leaf edge
1498 width: newLeafEdgeWidthL+'px',
1499 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1502 // Resizes the brown border div
1503 $(self.twoPage.coverDiv).css({
1504 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1505 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1508 $(self.leafEdgeTmp).remove();
1509 self.leafEdgeTmp = null;
1511 self.twoPage.currentIndexL = newIndexL;
1512 self.twoPage.currentIndexR = newIndexR;
1513 self.firstIndex = self.twoPage.currentIndexL;
1514 self.displayedIndices = [newIndexL, newIndexR];
1515 self.setClickHandlers();
1516 self.twoPageSetCursor();
1517 self.pruneUnusedImgs();
1519 self.animating = false;
1521 self.updateSearchHilites2UP();
1522 self.updatePageNumBox2UP();
1524 if (self.animationFinishedCallback) {
1525 self.animationFinishedCallback();
1526 self.animationFinishedCallback = null;
1534 //______________________________________________________________________________
1535 // Whether we flip left or right is dependent on the page progression
1536 // to flip forward one spread, pass index=null
1537 GnuBook.prototype.flipFwdToIndex = function(index) {
1539 if (this.animating) return;
1541 if (null != this.leafEdgeTmp) {
1542 alert('error: leafEdgeTmp should be null!');
1546 if (null == index) {
1547 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1549 if (index > this.lastDisplayableIndex()) return;
1551 this.animating = true;
1553 var nextIndices = this.getSpreadIndices(index);
1555 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1557 if ('rl' != this.pageProgression) {
1558 // We did not specify RTL
1559 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1560 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1563 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1564 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
1568 // flipRightToLeft(nextL, nextR, gutter)
1569 // $$$ better not to have to pass gutter in
1570 //______________________________________________________________________________
1571 // Flip from left to right and show the nextL and nextR indices on those sides
1572 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
1573 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1574 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1575 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1576 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1578 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1580 var top = this.twoPageTop();
1581 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1583 var middle = this.twoPage.middle;
1584 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
1586 this.leafEdgeTmp = document.createElement('div');
1587 $(this.leafEdgeTmp).css({
1588 borderStyle: 'solid none solid solid',
1589 borderColor: 'rgb(51, 51, 34)',
1590 borderWidth: '1px 0px 1px 1px',
1591 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1592 width: leafEdgeTmpW + 'px',
1593 height: this.twoPage.height-1 + 'px',
1594 left: gutter+scaledW+'px',
1596 position: 'absolute',
1598 }).appendTo('#GBtwopageview');
1600 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1601 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1603 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1604 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1605 var newWidthL = this.getPageWidth2UP(newIndexL);
1606 var newWidthR = this.getPageWidth2UP(newIndexR);
1608 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1610 var self = this; // closure-tastic!
1612 var speed = this.flipSpeed;
1614 this.removeSearchHilites();
1616 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1617 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1618 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1619 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1620 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1622 $(self.leafEdgeL).css({
1623 width: newLeafEdgeWidthL+'px',
1624 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1627 // Resizes the book cover
1628 $(self.twoPage.coverDiv).css({
1629 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1630 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
1633 $(self.leafEdgeTmp).remove();
1634 self.leafEdgeTmp = null;
1636 self.twoPage.currentIndexL = newIndexL;
1637 self.twoPage.currentIndexR = newIndexR;
1638 self.firstIndex = self.twoPage.currentIndexL;
1639 self.displayedIndices = [newIndexL, newIndexR];
1640 self.setClickHandlers();
1641 self.twoPageSetCursor();
1642 self.pruneUnusedImgs();
1644 self.animating = false;
1647 self.updateSearchHilites2UP();
1648 self.updatePageNumBox2UP();
1650 if (self.animationFinishedCallback) {
1651 self.animationFinishedCallback();
1652 self.animationFinishedCallback = null;
1659 //______________________________________________________________________________
1660 GnuBook.prototype.setClickHandlers = function() {
1662 // $$$ TODO don't set again if already set
1663 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
1668 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
1674 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexL]) );
1675 this.setDragHandler( $(this.prefetchedImgs[this.twoPage.currentIndexR]) );
1679 //______________________________________________________________________________
1680 GnuBook.prototype.prefetchImg = function(index) {
1681 if (undefined == this.prefetchedImgs[index]) {
1682 //console.log('prefetching ' + index);
1683 var img = document.createElement("img");
1684 img.src = this.getPageURI(index);
1685 this.prefetchedImgs[index] = img;
1690 // prepareFlipLeftToRight()
1692 //______________________________________________________________________________
1694 // Prepare to flip the left page towards the right. This corresponds to moving
1695 // backward when the page progression is left to right.
1696 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1698 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1700 this.prefetchImg(prevL);
1701 this.prefetchImg(prevR);
1703 var height = this.getPageHeight(prevL);
1704 var width = this.getPageWidth(prevL);
1705 var middle = this.twoPage.middle;
1706 var top = this.twoPageTop();
1707 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
1709 // The gutter is the dividing line between the left and right pages.
1710 // It is offset from the middle to create the illusion of thickness to the pages
1711 var gutter = middle + this.gutterOffsetForIndex(prevL);
1713 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1714 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1715 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1717 $(this.prefetchedImgs[prevL]).css({
1718 position: 'absolute',
1719 left: gutter-scaledW+'px',
1720 right: '', // clear right property
1722 backgroundColor: 'rgb(234, 226, 205)',
1723 height: this.twoPage.height,
1724 width: scaledW+'px',
1725 borderRight: '1px solid black',
1729 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1731 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1733 $(this.prefetchedImgs[prevR]).css({
1734 position: 'absolute',
1738 backgroundColor: 'rgb(234, 226, 205)',
1739 height: this.twoPage.height,
1741 borderLeft: '1px solid black',
1745 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1749 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
1750 // prepareFlipRightToLeft()
1751 //______________________________________________________________________________
1752 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1754 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1757 this.prefetchImg(nextL);
1758 this.prefetchImg(nextR);
1760 var height = this.getPageHeight(nextR);
1761 var width = this.getPageWidth(nextR);
1762 var middle = this.twoPage.middle;
1763 var top = this.twoPageTop();
1764 var scaledW = this.twoPage.height*width/height;
1766 var gutter = middle + this.gutterOffsetForIndex(nextL);
1768 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1769 $(this.prefetchedImgs[nextR]).css({
1770 position: 'absolute',
1773 backgroundColor: 'rgb(234, 226, 205)',
1774 height: this.twoPage.height,
1775 width: scaledW+'px',
1776 borderLeft: '1px solid black',
1780 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1782 height = this.getPageHeight(nextL);
1783 width = this.getPageWidth(nextL);
1784 scaledW = this.twoPage.height*width/height;
1786 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1787 $(this.prefetchedImgs[nextL]).css({
1788 position: 'absolute',
1789 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1791 backgroundColor: 'rgb(234, 226, 205)',
1792 height: this.twoPage.height,
1793 width: 0+'px', // Start at 0 width, then grow to the left
1794 borderRight: '1px solid black',
1798 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1802 // getNextLeafs() -- NOT RTL AWARE
1803 //______________________________________________________________________________
1804 // GnuBook.prototype.getNextLeafs = function(o) {
1805 // //TODO: we might have two left or two right leafs in a row (damaged book)
1806 // //For now, assume that leafs are contiguous.
1808 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1809 // o.L = this.twoPage.currentIndexL+2;
1810 // o.R = this.twoPage.currentIndexL+3;
1813 // getprevLeafs() -- NOT RTL AWARE
1814 //______________________________________________________________________________
1815 // GnuBook.prototype.getPrevLeafs = function(o) {
1816 // //TODO: we might have two left or two right leafs in a row (damaged book)
1817 // //For now, assume that leafs are contiguous.
1819 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1820 // o.L = this.twoPage.currentIndexL-2;
1821 // o.R = this.twoPage.currentIndexL-1;
1824 // pruneUnusedImgs()
1825 //______________________________________________________________________________
1826 GnuBook.prototype.pruneUnusedImgs = function() {
1827 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1828 for (var key in this.prefetchedImgs) {
1829 //console.log('key is ' + key);
1830 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1831 //console.log('removing key '+ key);
1832 $(this.prefetchedImgs[key]).remove();
1834 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1835 //console.log('deleting key '+ key);
1836 delete this.prefetchedImgs[key];
1842 //______________________________________________________________________________
1843 GnuBook.prototype.prefetch = function() {
1845 var lim = this.twoPage.currentIndexL-4;
1847 lim = Math.max(lim, 0);
1848 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1849 this.prefetchImg(i);
1852 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1853 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1854 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1855 this.prefetchImg(i);
1860 // getPageWidth2UP()
1861 //______________________________________________________________________________
1862 GnuBook.prototype.getPageWidth2UP = function(index) {
1863 // We return the width based on the dominant height
1864 var height = this.getPageHeight(index);
1865 var width = this.getPageWidth(index);
1866 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
1870 //______________________________________________________________________________
1871 GnuBook.prototype.search = function(term) {
1872 $('#GnuBookSearchScript').remove();
1873 var script = document.createElement("script");
1874 script.setAttribute('id', 'GnuBookSearchScript');
1875 script.setAttribute("type", "text/javascript");
1876 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1877 document.getElementsByTagName('head')[0].appendChild(script);
1878 $('#GnuBookSearchResults').html('Searching...');
1881 // GBSearchCallback()
1882 //______________________________________________________________________________
1883 GnuBook.prototype.GBSearchCallback = function(txt) {
1885 if (jQuery.browser.msie) {
1886 var dom=new ActiveXObject("Microsoft.XMLDOM");
1890 var parser = new DOMParser();
1891 var dom = parser.parseFromString(txt, "text/xml");
1894 $('#GnuBookSearchResults').empty();
1895 $('#GnuBookSearchResults').append('<ul>');
1897 for (var key in this.searchResults) {
1898 if (null != this.searchResults[key].div) {
1899 $(this.searchResults[key].div).remove();
1901 delete this.searchResults[key];
1904 var pages = dom.getElementsByTagName('PAGE');
1906 if (0 == pages.length) {
1907 // $$$ it would be nice to echo the (sanitized) search result here
1908 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1910 for (var i = 0; i < pages.length; i++){
1911 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1914 var re = new RegExp (/_(\d{4})/);
1915 var reMatch = re.exec(pages[i].getAttribute('file'));
1916 var index = parseInt(reMatch[1], 10);
1917 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1919 var children = pages[i].childNodes;
1921 for (var j=0; j<children.length; j++) {
1922 //console.log(j + ' - ' + children[j].nodeName);
1923 //console.log(children[j].firstChild.nodeValue);
1924 if ('CONTEXT' == children[j].nodeName) {
1925 context += children[j].firstChild.nodeValue;
1926 } else if ('WORD' == children[j].nodeName) {
1927 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1929 var index = this.leafNumToIndex(index);
1930 if (null != index) {
1931 //coordinates are [left, bottom, right, top, [baseline]]
1932 //we'll skip baseline for now...
1933 var coords = children[j].getAttribute('coords').split(',',4);
1934 if (4 == coords.length) {
1935 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1940 var pageName = this.getPageName(index);
1941 //TODO: remove hardcoded instance name
1942 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1945 $('#GnuBookSearchResults').append('</ul>');
1947 this.updateSearchHilites();
1950 // updateSearchHilites()
1951 //______________________________________________________________________________
1952 GnuBook.prototype.updateSearchHilites = function() {
1953 if (2 == this.mode) {
1954 this.updateSearchHilites2UP();
1956 this.updateSearchHilites1UP();
1960 // showSearchHilites1UP()
1961 //______________________________________________________________________________
1962 GnuBook.prototype.updateSearchHilites1UP = function() {
1964 for (var key in this.searchResults) {
1966 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1967 var result = this.searchResults[key];
1968 if(null == result.div) {
1969 result.div = document.createElement('div');
1970 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1971 //console.log('appending ' + key);
1974 width: (result.r-result.l)/this.reduce + 'px',
1975 height: (result.b-result.t)/this.reduce + 'px',
1976 left: (result.l)/this.reduce + 'px',
1977 top: (result.t)/this.reduce +'px'
1981 //console.log(key + ' not displayed');
1982 this.searchResults[key].div=null;
1988 //______________________________________________________________________________
1989 // Returns the position of the gutter (line between the page images)
1990 GnuBook.prototype.twoPageGutter = function() {
1991 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1995 //______________________________________________________________________________
1996 // Returns the offset for the top of the page images
1997 GnuBook.prototype.twoPageTop = function() {
1998 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2001 // twoPageCoverWidth()
2002 //______________________________________________________________________________
2003 // Returns the width of the cover div given the total page width
2004 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2005 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2008 // twoPageGetViewCenter()
2009 //______________________________________________________________________________
2010 // Returns the percentage offset into twopageview div at the center of container div
2011 // { percentageX: float, percentageY: float }
2012 GnuBook.prototype.twoPageGetViewCenter = function() {
2015 var containerOffset = $('#GBcontainer').offset();
2016 var viewOffset = $('#GBtwopageview').offset();
2017 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2018 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2023 // twoPageCenterView(percentageX, percentageY)
2024 //______________________________________________________________________________
2025 // Centers the point given by percentage from left,top of twopageview
2026 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2027 if ('undefined' == typeof(percentageX)) {
2030 if ('undefined' == typeof(percentageY)) {
2034 var viewWidth = $('#GBtwopageview').width();
2035 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2036 var intoViewX = percentageX * viewWidth;
2038 var viewHeight = $('#GBtwopageview').height();
2039 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2040 var intoViewY = percentageY * viewHeight;
2042 if (viewWidth < containerClientWidth) {
2043 // Can fit width without scrollbars - center by adjusting offset
2044 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2046 // Need to scroll to center
2047 $('#GBtwopageview').css('left', 0);
2048 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2051 if (viewHeight < containerClientHeight) {
2052 // Fits with scrollbars - add offset
2053 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2055 $('#GBtwopageview').css('top', 0);
2056 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2060 // showSearchHilites2UP()
2061 //______________________________________________________________________________
2062 GnuBook.prototype.updateSearchHilites2UP = function() {
2064 for (var key in this.searchResults) {
2065 key = parseInt(key, 10);
2066 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2067 var result = this.searchResults[key];
2068 if(null == result.div) {
2069 result.div = document.createElement('div');
2070 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2071 //console.log('appending ' + key);
2074 // We calculate the reduction factor for the specific page because it can be different
2075 // for each page in the spread
2076 var height = this.getPageHeight(key);
2077 var width = this.getPageWidth(key)
2078 var reduce = this.twoPage.height/height;
2079 var scaledW = parseInt(width*reduce);
2081 var gutter = this.twoPageGutter();
2083 if ('L' == this.getPageSide(key)) {
2084 pageL = gutter-scaledW;
2088 var pageT = this.twoPageTop();
2091 width: (result.r-result.l)*reduce + 'px',
2092 height: (result.b-result.t)*reduce + 'px',
2093 left: pageL+(result.l)*reduce + 'px',
2094 top: pageT+(result.t)*reduce +'px'
2098 //console.log(key + ' not displayed');
2099 if (null != this.searchResults[key].div) {
2100 //console.log('removing ' + key);
2101 $(this.searchResults[key].div).remove();
2103 this.searchResults[key].div=null;
2108 // removeSearchHilites()
2109 //______________________________________________________________________________
2110 GnuBook.prototype.removeSearchHilites = function() {
2111 for (var key in this.searchResults) {
2112 if (null != this.searchResults[key].div) {
2113 $(this.searchResults[key].div).remove();
2114 this.searchResults[key].div=null;
2120 //______________________________________________________________________________
2121 GnuBook.prototype.showEmbedCode = function() {
2122 if (null != this.embedPopup) { // check if already showing
2126 this.embedPopup = document.createElement("div");
2127 $(this.embedPopup).css({
2128 position: 'absolute',
2130 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2133 border: "3px double #999999",
2135 backgroundColor: "#fff"
2136 }).appendTo('#GnuBook');
2138 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2139 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>';
2140 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2141 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2143 this.embedPopup.innerHTML = htmlStr;
2144 $(this.embedPopup).find('input').bind('click', function() {
2150 //______________________________________________________________________________
2151 GnuBook.prototype.autoToggle = function() {
2153 var bComingFrom1up = false;
2154 if (2 != this.mode) {
2155 bComingFrom1up = true;
2159 // Change to autofit if book is too large
2160 if (this.reduce < this.twoPageGetAutofitReduce()) {
2165 if (null == this.autoTimer) {
2166 this.flipSpeed = 2000;
2168 // $$$ Draw events currently cause layout problems when they occur during animation.
2169 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2170 // we workaround for now by not triggering immediate animation in that case.
2171 // See https://bugs.launchpad.net/gnubook/+bug/328327
2172 if (('rl' == this.pageProgression) && bComingFrom1up) {
2173 // don't flip immediately -- wait until timer fires
2176 this.flipFwdToIndex();
2179 $('#GBtoolbar .play').hide();
2180 $('#GBtoolbar .pause').show();
2181 this.autoTimer=setInterval(function(){
2182 if (self.animating) {return;}
2184 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2185 self.flipBackToIndex(1); // $$$ really what we want?
2187 self.flipFwdToIndex();
2196 //______________________________________________________________________________
2197 // Stop autoplay mode, allowing animations to finish
2198 GnuBook.prototype.autoStop = function() {
2199 if (null != this.autoTimer) {
2200 clearInterval(this.autoTimer);
2201 this.flipSpeed = 'fast';
2202 $('#GBtoolbar .pause').hide();
2203 $('#GBtoolbar .play').show();
2204 this.autoTimer = null;
2208 // stopFlipAnimations
2209 //______________________________________________________________________________
2210 // Immediately stop flip animations. Callbacks are triggered.
2211 GnuBook.prototype.stopFlipAnimations = function() {
2213 this.autoStop(); // Clear timers
2215 // Stop animation, clear queue, trigger callbacks
2216 if (this.leafEdgeTmp) {
2217 $(this.leafEdgeTmp).stop(false, true);
2219 jQuery.each(this.prefetchedImgs, function() {
2220 $(this).stop(false, true);
2223 // And again since animations also queued in callbacks
2224 if (this.leafEdgeTmp) {
2225 $(this.leafEdgeTmp).stop(false, true);
2227 jQuery.each(this.prefetchedImgs, function() {
2228 $(this).stop(false, true);
2233 // keyboardNavigationIsDisabled(event)
2234 // - returns true if keyboard navigation should be disabled for the event
2235 //______________________________________________________________________________
2236 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2237 if (event.target.tagName == "INPUT") {
2243 // gutterOffsetForIndex
2244 //______________________________________________________________________________
2246 // Returns the gutter offset for the spread containing the given index.
2247 // This function supports RTL
2248 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2250 // To find the offset of the gutter from the middle we calculate our percentage distance
2251 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2252 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2254 // But then again for RTL it's the opposite
2255 if ('rl' == this.pageProgression) {
2263 //______________________________________________________________________________
2264 // Returns the width of the leaf edge div for the page with index given
2265 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2266 // $$$ could there be single pixel rounding errors for L vs R?
2267 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2268 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2270 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2274 // jumpIndexForLeftEdgePageX
2275 //______________________________________________________________________________
2276 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2277 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2278 if ('rl' != this.pageProgression) {
2279 // LTR - flipping backward
2280 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2282 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2283 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2287 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2288 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2293 // jumpIndexForRightEdgePageX
2294 //______________________________________________________________________________
2295 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2296 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2297 if ('rl' != this.pageProgression) {
2299 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2300 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2303 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2304 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2309 GnuBook.prototype.initToolbar = function(mode, ui) {
2311 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2312 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2313 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2314 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2315 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
2316 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2317 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2318 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2321 this.updateToolbarZoom(this.reduce); // Pretty format
2323 if (ui == "embed") {
2324 $("#GnuBook a.logo").attr("target","_blank");
2327 // $$$ turn this into a member variable
2328 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2330 // We build in mode 2
2331 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2332 + "<button class='GBicon rollover embed' />"
2333 + "<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>"
2334 + "<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>"
2335 + "<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>"
2336 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2338 this.bindToolbarNavHandlers(jToolbar);
2340 // Setup tooltips -- later we could load these from a file for i18n
2341 var titles = { '.logo': 'Go to Archive.org',
2342 '.zoom_in': 'Zoom in',
2343 '.zoom_out': 'Zoom out',
2344 '.one_page_mode': 'One-page view',
2345 '.two_page_mode': 'Two-page view',
2346 '.embed': 'Embed bookreader',
2347 '.book_left': 'Flip left',
2348 '.book_right': 'Flip right',
2349 '.book_up': 'Page up',
2350 '.book_down': 'Page down',
2353 '.book_top': 'First page',
2354 '.book_bottom': 'Last page'
2356 if ('rl' == this.pageProgression) {
2357 titles['.book_leftmost'] = 'Last page';
2358 titles['.book_rightmost'] = 'First page';
2360 titles['.book_leftmost'] = 'First page';
2361 titles['.book_rightmost'] = 'Last page';
2364 for (var icon in titles) {
2365 jToolbar.find(icon).attr('title', titles[icon]);
2368 // Hide mode buttons and autoplay if 2up is not available
2369 // $$$ if we end up with more than two modes we should show the applicable buttons
2370 if ( !this.canSwitchToMode(this.constMode2up) ) {
2371 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2374 // Switch to requested mode -- binds other click handlers
2375 this.switchToolbarMode(mode);
2380 // switchToolbarMode
2381 //______________________________________________________________________________
2382 // Update the toolbar for the given mode (changes navigation buttons)
2383 // $$$ we should soon split the toolbar out into its own module
2384 GnuBook.prototype.switchToolbarMode = function(mode) {
2387 $('#GBtoolbar .GBtoolbarmode2').hide();
2388 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2391 $('#GBtoolbar .GBtoolbarmode1').hide();
2392 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2396 // bindToolbarNavHandlers
2397 //______________________________________________________________________________
2398 // Binds the toolbar handlers
2399 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2401 jToolbar.find('.book_left').bind('click', function(e) {
2406 jToolbar.find('.book_right').bind('click', function(e) {
2411 jToolbar.find('.book_up').bind('click', function(e) {
2416 jToolbar.find('.book_down').bind('click', function(e) {
2421 jToolbar.find('.embed').bind('click', function(e) {
2426 jToolbar.find('.play').bind('click', function(e) {
2431 jToolbar.find('.pause').bind('click', function(e) {
2436 jToolbar.find('.book_top').bind('click', function(e) {
2441 jToolbar.find('.book_bottom').bind('click', function(e) {
2446 jToolbar.find('.book_leftmost').bind('click', function(e) {
2451 jToolbar.find('.book_rightmost').bind('click', function(e) {
2457 // updateToolbarZoom(reduce)
2458 //______________________________________________________________________________
2459 // Update the displayed zoom factor based on reduction factor
2460 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2462 if (this.constMode2up == this.mode && this.twoPage.autofit) {
2465 value = (100 / reduce).toFixed(2);
2466 // Strip trailing zeroes and decimal if all zeroes
2467 value = value.replace(/0+$/,'');
2468 value = value.replace(/\.$/,'');
2471 $('#GBzoom').text(value);
2474 // firstDisplayableIndex
2475 //______________________________________________________________________________
2476 // Returns the index of the first visible page, dependent on the mode.
2477 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2478 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2479 GnuBook.prototype.firstDisplayableIndex = function() {
2480 if (this.mode == 0) {
2483 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2487 // lastDisplayableIndex
2488 //______________________________________________________________________________
2489 // Returns the index of the last visible page, dependent on the mode.
2490 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2491 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2492 GnuBook.prototype.lastDisplayableIndex = function() {
2493 if (this.mode == 2) {
2494 if (this.lastDisplayableIndex2up === null) {
2495 // Calculate and cache
2496 var candidate = this.numLeafs - 1;
2497 for ( ; candidate >= 0; candidate--) {
2498 var spreadIndices = this.getSpreadIndices(candidate);
2499 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2503 this.lastDisplayableIndex2up = candidate;
2505 return this.lastDisplayableIndex2up;
2507 return this.numLeafs - 1;
2511 // shortTitle(maximumCharacters)
2513 // Returns a shortened version of the title with the maximum number of characters
2514 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2515 if (this.bookTitle.length < maximumCharacters) {
2516 return this.bookTitle;
2519 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2526 // Parameter related functions
2528 // updateFromParams(params)
2530 // Update ourselves from the params object.
2532 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2533 GnuBook.prototype.updateFromParams = function(params) {
2534 if ('undefined' != typeof(params.mode)) {
2535 this.switchMode(params.mode);
2538 // $$$ process /search
2539 // $$$ process /zoom
2541 // We only respect page if index is not set
2542 if ('undefined' != typeof(params.index)) {
2543 if (params.index != this.currentIndex()) {
2544 this.jumpToIndex(params.index);
2546 } else if ('undefined' != typeof(params.page)) {
2547 // $$$ this assumes page numbers are unique
2548 if (params.page != this.getPageNum(this.currentIndex())) {
2549 this.jumpToPage(params.page);
2553 // $$$ process /region
2554 // $$$ process /highlight
2557 // paramsFromFragment(urlFragment)
2559 // Returns a object with configuration parametes from a URL fragment.
2561 // E.g paramsFromFragment(window.location.hash)
2562 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2563 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2567 // For convenience we allow an initial # character (as from window.location.hash)
2568 // but don't require it
2569 if (urlFragment.substr(0,1) == '#') {
2570 urlFragment = urlFragment.substr(1);
2573 // Simple #nn syntax
2574 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2575 if ( !isNaN(oldStyleLeafNum) ) {
2576 params.index = oldStyleLeafNum;
2578 // Done processing if using old-style syntax
2582 // Split into key-value pairs
2583 var urlArray = urlFragment.split('/');
2585 for (var i = 0; i < urlArray.length; i += 2) {
2586 urlHash[urlArray[i]] = urlArray[i+1];
2590 if ('1up' == urlHash['mode']) {
2591 params.mode = this.constMode1up;
2592 } else if ('2up' == urlHash['mode']) {
2593 params.mode = this.constMode2up;
2597 if ('undefined' != typeof(urlHash['page'])) {
2598 // page was set -- may not be int
2599 params.page = urlHash['page'];
2602 // $$$ process /region
2603 // $$$ process /search
2604 // $$$ process /highlight
2609 // paramsFromCurrent()
2611 // Create a params object from the current parameters.
2612 GnuBook.prototype.paramsFromCurrent = function() {
2616 var pageNum = this.getPageNum(this.currentIndex());
2617 if ((pageNum === 0) || pageNum) {
2618 params.page = pageNum;
2621 params.index = this.currentIndex();
2622 params.mode = this.mode;
2631 // fragmentFromParams(params)
2633 // Create a fragment string from the params object.
2634 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2635 GnuBook.prototype.fragmentFromParams = function(params) {
2636 var separator = '/';
2640 if ('undefined' != typeof(params.page)) {
2641 fragments.push('page', params.page);
2643 // Don't have page numbering -- use index instead
2644 fragments.push('page', 'n' + params.index);
2652 if ('undefined' != typeof(params.mode)) {
2653 if (params.mode == this.constMode1up) {
2654 fragments.push('mode', '1up');
2655 } else if (params.mode == this.constMode2up) {
2656 fragments.push('mode', '2up');
2658 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2662 return fragments.join(separator);
2665 // getPageIndex(pageNum)
2667 // Returns the *highest* index the given page number, or undefined
2668 GnuBook.prototype.getPageIndex = function(pageNum) {
2669 var pageIndices = this.getPageIndices(pageNum);
2671 if (pageIndices.length > 0) {
2672 return pageIndices[pageIndices.length - 1];
2678 // getPageIndices(pageNum)
2680 // Returns an array (possibly empty) of the indices with the given page number
2681 GnuBook.prototype.getPageIndices = function(pageNum) {
2684 // Check for special "nXX" page number
2685 if (pageNum.slice(0,1) == 'n') {
2687 var pageIntStr = pageNum.slice(1, pageNum.length);
2688 var pageIndex = parseInt(pageIntStr);
2689 indices.append(pageIndex);
2692 // Do nothing... will run through page names and see if one matches
2697 for (i=0; i<this.numLeafs; i++) {
2698 if (this.getPageNum(i) == pageNum) {
2706 // getPageName(index)
2708 // Returns the name of the page as it should be displayed in the user interface
2709 GnuBook.prototype.getPageName = function(index) {
2710 return 'Page ' + this.getPageNum(index);
2713 // updateLocationHash
2715 // Update the location hash from the current parameters. Call this instead of manually
2716 // using window.location.replace
2717 GnuBook.prototype.updateLocationHash = function() {
2718 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2719 window.location.replace(newHash);
2721 // This is the variable checked in the timer. Only user-generated changes
2722 // to the URL will trigger the event.
2723 this.oldLocationHash = newHash;
2726 // startLocationPolling
2728 // Starts polling of window.location to see hash fragment changes
2729 GnuBook.prototype.startLocationPolling = function() {
2730 var self = this; // remember who I am
2731 self.oldLocationHash = window.location.hash;
2733 if (this.locationPollId) {
2734 clearInterval(this.locationPollID);
2735 this.locationPollId = null;
2738 this.locationPollId = setInterval(function() {
2739 var newHash = window.location.hash;
2740 if (newHash != self.oldLocationHash) {
2741 if (newHash != self.oldUserHash) { // Only process new user hash once
2742 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2744 // Queue change if animating
2745 if (self.animating) {
2747 self.animationFinishedCallback = function() {
2748 self.updateFromParams(self.paramsFromFragment(newHash));
2750 } else { // update immediately
2751 self.updateFromParams(self.paramsFromFragment(newHash));
2753 self.oldUserHash = newHash;
2761 // Returns a URL for an embedded version of the current book
2762 GnuBook.prototype.getEmbedURL = function() {
2763 // We could generate a URL hash fragment here but for now we just leave at defaults
2764 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2769 // Returns the embed code HTML fragment suitable for copy and paste
2770 GnuBook.prototype.getEmbedCode = function() {
2771 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2776 // Returns true if we can switch to the requested mode
2777 GnuBook.prototype.canSwitchToMode = function(mode) {
2778 if (mode == this.constMode2up) {
2779 // check there are enough pages to display
2780 // $$$ this is a workaround for the mis-feature that we can't display
2781 // short books in 2up mode
2782 if (this.numLeafs < 6) {
2790 // Library functions
2792 clamp: function(value, min, max) {
2793 return Math.min(Math.max(value, min), max);