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(). Some of these functions
28 // can just be stubs for simple books.
35 // - getSpreadIndices()
36 // You must also add a numLeafs property before calling init().
41 this.mode = 1; //1, 2, 3
42 this.ui = 'full'; // UI mode
43 this.thumbScale = 10; // thumbnail default
45 this.displayedIndices = [];
46 this.displayedRows=[];
47 //this.indicesToDisplay = [];
49 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
52 this.animating = false;
54 this.autoTimer = null;
55 this.flipSpeed = 'fast';
57 this.twoPagePopUp = null;
58 this.leafEdgeTmp = null;
59 this.embedPopup = null;
60 this.printPopup = null;
63 this.searchResults = {};
65 this.firstIndex = null;
67 this.lastDisplayableIndex2up = null;
69 // We link to index.php to avoid redirect which breaks back button
70 this.logoURL = 'http://www.archive.org/index.php';
72 // Base URL for images
73 this.imagesBaseURL = '/bookreader/images/';
76 this.constMode1up = 1;
77 this.constMode2up = 2;
78 this.constModeThumb = 3;
81 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
83 // Object to hold parameters related to 2up mode
85 coverInternalPadding: 10, // Width of cover
86 coverExternalPadding: 10, // Padding outside of cover
87 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
91 // Background color for pages (e.g. when loading page image)
92 // $$$ TODO dynamically calculate based on page images
93 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
97 //______________________________________________________________________________
98 GnuBook.prototype.init = function() {
100 var startIndex = undefined;
101 this.pageScale = this.reduce; // preserve current reduce
103 // Find start index and mode if set in location hash
104 var params = this.paramsFromFragment(window.location.hash);
106 if ('undefined' != typeof(params.index)) {
107 startIndex = params.index;
108 } else if ('undefined' != typeof(params.page)) {
109 startIndex = this.getPageIndex(params.page);
112 if ('undefined' == typeof(startIndex)) {
113 if ('undefined' != typeof(this.titleLeaf)) {
114 startIndex = this.leafNumToIndex(this.titleLeaf);
118 if ('undefined' == typeof(startIndex)) {
122 if ('undefined' != typeof(params.mode)) {
123 this.mode = params.mode;
126 // Set document title -- may have already been set in enclosing html for
127 // search engine visibility
128 document.title = this.shortTitle(50);
130 // Sanitize parameters
131 if ( !this.canSwitchToMode( this.mode ) ) {
132 this.mode = this.constMode1up;
135 $("#GnuBook").empty();
136 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
137 $("#GnuBook").append("<div id='GBcontainer'></div>");
138 $("#GBcontainer").append("<div id='GBpageview'></div>");
140 $("#GBcontainer").bind('scroll', this, function(e) {
144 this.setupKeyListeners();
145 this.startLocationPolling();
147 $(window).bind('resize', this, function(e) {
148 //console.log('resize!');
149 if (1 == e.data.mode) {
150 //console.log('centering 1page view');
151 e.data.centerPageView();
152 $('#GBpageview').empty()
153 e.data.displayedIndices = [];
154 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
156 } else if (3 == e.data.mode){
157 e.data.prepareThumbnailView();
159 //console.log('drawing 2 page view');
161 // We only need to prepare again in autofit (size of spread changes)
162 if (e.data.twoPage.autofit) {
163 e.data.prepareTwoPageView();
165 // Re-center if the scrollbars have disappeared
166 var center = e.data.twoPageGetViewCenter();
167 var doRecenter = false;
168 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
169 center.percentageX = 0.5;
172 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
173 center.percentageY = 0.5;
177 e.data.twoPageCenterView(center.percentageX, center.percentageY);
183 $('.GBpagediv1up').bind('mousedown', this, function(e) {
184 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
185 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
188 if (1 == this.mode) {
189 this.resizePageView();
190 this.firstIndex = startIndex;
191 this.jumpToIndex(startIndex);
192 } else if (3 == this.mode) {
193 this.firstIndex = startIndex;
194 this.prepareThumbnailView();
195 this.jumpToIndex(startIndex);
197 //this.resizePageView();
199 this.displayedIndices=[0];
200 this.firstIndex = startIndex;
201 this.displayedIndices = [this.firstIndex];
202 //console.log('titleLeaf: %d', this.titleLeaf);
203 //console.log('displayedIndices: %s', this.displayedIndices);
204 this.prepareTwoPageView();
207 // Enact other parts of initial params
208 this.updateFromParams(params);
211 GnuBook.prototype.setupKeyListeners = function() {
224 // We use document here instead of window to avoid a bug in jQuery on IE7
225 $(document).keydown(function(e) {
227 // Keyboard navigation
228 if (!self.keyboardNavigationIsDisabled(e)) {
232 // In 1up mode page scrolling is handled by browser
233 if (2 == self.mode) {
240 if (2 == self.mode) {
254 if (2 == self.mode) {
260 if (2 == self.mode) {
271 //______________________________________________________________________________
272 GnuBook.prototype.drawLeafs = function() {
273 if (1 == this.mode) {
274 this.drawLeafsOnePage();
275 } else if(3 == this.mode) {
276 this.drawLeafsThumbnail();
278 this.drawLeafsTwoPage();
283 //______________________________________________________________________________
284 GnuBook.prototype.setDragHandler = function(div) {
285 div.dragging = false;
287 $(div).unbind('mousedown').bind('mousedown', function(e) {
290 //console.log('mousedown at ' + e.pageY);
292 this.dragging = true;
293 this.prevMouseX = e.pageX;
294 this.prevMouseY = e.pageY;
296 var startX = e.pageX;
297 var startY = e.pageY;
298 var startTop = $('#GBcontainer').attr('scrollTop');
299 var startLeft = $('#GBcontainer').attr('scrollLeft');
303 $(div).unbind('mousemove').bind('mousemove', function(ee) {
306 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
308 var offsetX = ee.pageX - this.prevMouseX;
309 var offsetY = ee.pageY - this.prevMouseY;
312 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
313 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
316 this.prevMouseX = ee.pageX;
317 this.prevMouseY = ee.pageY;
321 $(div).unbind('mouseup').bind('mouseup', function(ee) {
323 //console.log('mouseup');
325 this.dragging = false;
328 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
330 //console.log('mouseleave');
332 this.dragging = false;
335 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
337 //console.log('mouseenter');
339 this.dragging = false;
343 // setDragHandler2UP()
344 //______________________________________________________________________________
345 GnuBook.prototype.setDragHandler2UP = function(div) {
346 div.dragging = false;
348 $(div).unbind('mousedown').bind('mousedown', function(e) {
351 //console.log('mousedown at ' + e.pageY);
353 this.dragStart = {x: e.pageX, y: e.pageY };
354 this.mouseDown = true;
355 this.dragging = false; // wait until drag distance
356 this.prevMouseX = e.pageX;
357 this.prevMouseY = e.pageY;
359 var startX = e.pageX;
360 var startY = e.pageY;
361 var startTop = $('#GBcontainer').attr('scrollTop');
362 var startLeft = $('#GBcontainer').attr('scrollLeft');
366 $(div).unbind('mousemove').bind('mousemove', function(ee) {
369 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
371 var offsetX = ee.pageX - this.prevMouseX;
372 var offsetY = ee.pageY - this.prevMouseY;
374 var minDragDistance = 5; // $$$ constant
376 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
378 if (this.mouseDown && (distance > minDragDistance)) {
379 //console.log('drag start!');
381 this.dragging = true;
385 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
386 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
387 this.prevMouseX = ee.pageX;
388 this.prevMouseY = ee.pageY;
395 $(div).unbind('mouseup').bind('mouseup', function(ee) {
397 //console.log('mouseup');
399 this.dragging = false;
400 this.mouseDown = false;
405 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
407 //console.log('mouseleave');
409 this.dragging = false;
410 this.mouseDown = false;
413 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
415 //console.log('mouseenter');
417 this.dragging = false;
418 this.mouseDown = false;
422 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
423 //console.log('setting handler');
424 //console.log(element.tagName);
426 $(element).unbind('click').bind('click', data, function(e) {
429 //console.log('click!');
431 if (this.mouseDown && (!this.dragging)) {
432 //console.log('click not dragging!');
436 this.dragging = false;
437 this.mouseDown = false;
441 // drawLeafsOnePage()
442 //______________________________________________________________________________
443 GnuBook.prototype.drawLeafsOnePage = function() {
444 //alert('drawing leafs!');
448 var scrollTop = $('#GBcontainer').attr('scrollTop');
449 var scrollBottom = scrollTop + $('#GBcontainer').height();
450 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
452 var indicesToDisplay = [];
457 for (i=0; i<this.numLeafs; i++) {
458 var height = parseInt(this._getPageHeight(i)/this.reduce);
460 leafBottom += height;
461 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
462 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
463 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
464 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
465 if (topInView | bottomInView | middleInView) {
466 //console.log('displayed: ' + this.displayedIndices);
467 //console.log('to display: ' + i);
468 indicesToDisplay.push(i);
470 leafTop += height +10;
474 var firstIndexToDraw = indicesToDisplay[0];
475 this.firstIndex = firstIndexToDraw;
477 // Update hash, but only if we're currently displaying a leaf
478 // Hack that fixes #365790
479 if (this.displayedIndices.length > 0) {
480 this.updateLocationHash();
483 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
485 indicesToDisplay.unshift(firstIndexToDraw);
488 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
489 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
490 indicesToDisplay.push(lastIndexToDraw+1);
495 for (i=0; i<firstIndexToDraw; i++) {
496 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
499 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
500 var viewWidth = $('#GBcontainer').attr('scrollWidth');
503 for (i=0; i<indicesToDisplay.length; i++) {
504 var index = indicesToDisplay[i];
505 var height = parseInt(this._getPageHeight(index)/this.reduce);
507 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
508 var width = parseInt(this._getPageWidth(index)/this.reduce);
509 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
510 var div = document.createElement("div");
511 div.className = 'GBpagediv1up';
512 div.id = 'pagediv'+index;
513 div.style.position = "absolute";
514 $(div).css('top', leafTop + 'px');
515 var left = (viewWidth-width)>>1;
516 if (left<0) left = 0;
517 $(div).css('left', left+'px');
518 $(div).css('width', width+'px');
519 $(div).css('height', height+'px');
520 //$(div).text('loading...');
522 this.setDragHandler(div);
524 $('#GBpageview').append(div);
526 var img = document.createElement("img");
527 img.src = this._getPageURI(index, this.reduce, 0);
528 $(img).css('width', width+'px');
529 $(img).css('height', height+'px');
533 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
536 leafTop += height +10;
540 for (i=0; i<this.displayedIndices.length; i++) {
541 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
542 var index = this.displayedIndices[i];
543 //console.log('Removing leaf ' + index);
544 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
545 $('#pagediv'+index).remove();
547 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
551 this.displayedIndices = indicesToDisplay.slice();
552 this.updateSearchHilites();
554 if (null != this.getPageNum(firstIndexToDraw)) {
555 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
557 $("#GBpagenum").val('');
560 this.updateToolbarZoom(this.reduce);
564 // drawLeafsThumbnail()
565 //______________________________________________________________________________
566 GnuBook.prototype.drawLeafsThumbnail = function() {
567 //alert('drawing leafs!');
570 var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
572 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
584 for (i=0; i<this.numLeafs; i++) {
585 leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
586 if (rightPos + (leafWidth + this.padding) > viewWidth){
592 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
593 if (leafMap[currentRow].leafs===undefined) {
594 leafMap[currentRow].leafs = [];
595 leafMap[currentRow].height = 0;
596 leafMap[currentRow].top = 0;
598 leafMap[currentRow].leafs[leafIndex] = {};
599 leafMap[currentRow].leafs[leafIndex].num = i;
600 leafMap[currentRow].leafs[leafIndex].left = rightPos;
602 leafHeight = parseInt(this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)/this.reduce, 10);
603 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
604 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
605 rightPos += leafWidth + this.padding;
606 if (rightPos > maxRight) { maxRight = rightPos; }
610 // reset the bottom position based on thumbnails
611 $('#GBpageview').height(bottomPos);
613 var pageViewBuffer = Math.floor(($('#GBcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
614 var scrollTop = $('#GBcontainer').attr('scrollTop');
615 var scrollBottom = scrollTop + $('#GBcontainer').height();
619 var rowsToDisplay = [];
621 for (i=0; i<leafMap.length; i++) {
622 leafBottom += this.padding + leafMap[i].height;
623 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
624 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
625 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
626 if (topInView | bottomInView | middleInView) {
627 //console.log('row to display: ' + j);
628 rowsToDisplay.push(i);
630 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
631 leafTop = leafBottom;
634 var firstRow = rowsToDisplay[0];
635 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
637 for (i=1; i<rowBuffer+1; i++) {
638 if (firstRow-i >= 0) { rowsToDisplay.unshift(firstRow-i); }
639 if (lastRow+i < leafMap.length) { rowsToDisplay.push(lastRow+i); }
642 // Update hash, but only if we're currently displaying a leaf
643 // Hack that fixes #365790
644 if (this.displayedRows.length > 0) {
645 this.updateLocationHash();
655 for (i=0; i<rowsToDisplay.length; i++) {
656 if (-1 == jQuery.inArray(rowsToDisplay[i], this.displayedRows)) {
657 row = rowsToDisplay[i];
660 for (j=0; j<leafMap[row].leafs.length; j++) {
661 index = leafMap[row].leafs[j].num;
663 leafWidth = parseInt(this.getPageWidth(index)/this.reduce, 10);
664 leafHeight = parseInt(this.getPageHeight(index)/this.reduce, 10);
665 leafTop = leafMap[row].top;
666 left = leafMap[row].leafs[j].left + pageViewBuffer;
668 div = document.createElement("div");
669 div.id = 'pagediv'+index;
670 div.style.position = "absolute";
671 div.className = "GBpagedivthumb";
673 left += this.padding;
674 $(div).css('top', leafTop + 'px');
675 $(div).css('left', left+'px');
676 $(div).css('width', leafWidth+'px');
677 $(div).css('height', leafHeight+'px');
678 //$(div).text('loading...');
680 // link to page in single page mode
681 link = document.createElement("a");
682 link.href = '#page/' + (this.getPageNum(index)) +'/mode/1up' ;
685 $('#GBpageview').append(div);
687 img = document.createElement("img");
688 img.src = this.getPageURI(index);
689 $(img).css('width', leafWidth+'px');
690 $(img).css('height', leafHeight+'px');
691 img.style.border = "0";
693 //console.log('displaying thumbnail: ' + leafMap[j]);
699 // remove previous highlights
700 if ($('.GBpagedivthumb_highlight').length>0) {
701 div = $('.GBpagedivthumb_highlight')
702 div.attr({className: 'GBpagedivthumb' });
704 // highlight current page
705 $('#pagediv'+this.currentIndex()).attr({className: 'GBpagedivthumb_highlight' });
708 for (i=0; i<this.displayedRows.length; i++) {
709 if (-1 == jQuery.inArray(this.displayedRows[i], rowsToDisplay)) {
710 row = this.displayedRows[i];
711 for (k=0; k<leafMap[row].leafs.length; k++) {
712 index = leafMap[row].leafs[k].num;
713 //console.log('Removing leaf ' + index);
714 $('#pagediv'+index).remove();
718 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
722 this.displayedRows = rowsToDisplay.slice();
724 if (null !== this.getPageNum(this.currentIndex())) {
725 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
727 $("#GBpagenum").val('');
730 this.updateToolbarZoom(this.reduce);
733 // drawLeafsTwoPage()
734 //______________________________________________________________________________
735 GnuBook.prototype.drawLeafsTwoPage = function() {
736 var scrollTop = $('#GBtwopageview').attr('scrollTop');
737 var scrollBottom = scrollTop + $('#GBtwopageview').height();
739 // $$$ we should use calculated values in this.twoPage (recalc if necessary)
741 var indexL = this.twoPage.currentIndexL;
743 var heightL = this._getPageHeight(indexL);
744 var widthL = this._getPageWidth(indexL);
746 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
747 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
748 //var bookCoverDivWidth = this.twoPage.width*2 + 20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
749 var bookCoverDivWidth = this.twoPage.bookCoverDivWidth;
750 //console.log(leafEdgeWidthL);
752 var middle = this.twoPage.middle; // $$$ getter instead?
753 var top = this.twoPageTop();
754 var bookCoverDivLeft = this.twoPage.bookCoverDivLeft;
756 this.twoPage.scaledWL = this.getPageWidth2UP(indexL);
757 this.twoPage.gutter = this.twoPageGutter();
759 this.prefetchImg(indexL);
760 $(this.prefetchedImgs[indexL]).css({
761 position: 'absolute',
762 left: this.twoPage.gutter-this.twoPage.scaledWL+'px',
765 backgroundColor: this.getPageBackgroundColor(indexL),
766 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
767 width: this.twoPage.scaledWL + 'px',
768 borderRight: '1px solid black',
770 }).appendTo('#GBtwopageview');
772 var indexR = this.twoPage.currentIndexR;
773 var heightR = this._getPageHeight(indexR);
774 var widthR = this._getPageWidth(indexR);
776 // $$$ should use getwidth2up?
777 //var scaledWR = this.twoPage.height*widthR/heightR;
778 this.twoPage.scaledWR = this.getPageWidth2UP(indexR);
779 this.prefetchImg(indexR);
780 $(this.prefetchedImgs[indexR]).css({
781 position: 'absolute',
782 left: this.twoPage.gutter+'px',
785 backgroundColor: this.getPageBackgroundColor(indexR),
786 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
787 width: this.twoPage.scaledWR + 'px',
788 borderLeft: '1px solid black',
790 }).appendTo('#GBtwopageview');
793 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
794 this.setMouseHandlers2UP();
795 this.twoPageSetCursor();
797 this.updatePageNumBox2UP();
798 this.updateToolbarZoom(this.reduce);
800 // this.twoPagePlaceFlipAreas(); // No longer used
804 // updatePageNumBox2UP
805 //______________________________________________________________________________
806 GnuBook.prototype.updatePageNumBox2UP = function() {
807 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
808 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
810 $("#GBpagenum").val('');
812 this.updateLocationHash();
816 //______________________________________________________________________________
817 GnuBook.prototype.loadLeafs = function() {
821 if (null == this.timer) {
822 this.timer=setTimeout(function(){self.drawLeafs()},250);
824 clearTimeout(this.timer);
825 this.timer=setTimeout(function(){self.drawLeafs()},250);
831 // Pass 1 to zoom in, anything else to zoom out
832 //______________________________________________________________________________
833 GnuBook.prototype.zoom = function(direction) {
835 case this.constMode1up:
836 return this.zoom1up(direction);
837 case this.constMode2up:
838 return this.zoom2up(direction);
843 //______________________________________________________________________________
844 GnuBook.prototype.zoom1up = function(dir) {
846 if (2 == this.mode) { //can only zoom in 1-page mode
851 // $$$ with flexible zoom we could "snap" to /2 page reductions
852 // for better scaling
854 if (this.reduce <= 0.5) return;
855 this.reduce*=0.5; //zoom in
857 if (this.reduce >= 8) return;
858 this.reduce*=2; //zoom out
861 this.pageScale = this.reduce; // preserve current reduce
862 this.resizePageView();
864 $('#GBpageview').empty()
865 this.displayedIndices = [];
868 this.updateToolbarZoom(this.reduce);
870 // Recalculate search hilites
871 this.removeSearchHilites();
872 this.updateSearchHilites();
877 //______________________________________________________________________________
878 GnuBook.prototype.resizePageView = function() {
881 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
882 var viewWidth = $('#GBcontainer').attr('clientWidth');
884 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
885 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
886 var oldPageViewHeight = $('#GBpageview').height();
887 var oldPageViewWidth = $('#GBpageview').width();
889 var oldCenterY = this.centerY1up();
890 var oldCenterX = this.centerX1up();
892 if (0 != oldPageViewHeight) {
893 var scrollRatio = oldCenterY / oldPageViewHeight;
898 for (i=0; i<this.numLeafs; i++) {
899 viewHeight += parseInt(this._getPageHeight(i)/this.reduce) + this.padding;
900 var width = parseInt(this._getPageWidth(i)/this.reduce);
901 if (width>viewWidth) viewWidth=width;
903 $('#GBpageview').height(viewHeight);
904 $('#GBpageview').width(viewWidth);
906 var newCenterY = scrollRatio*viewHeight;
907 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
908 $('#GBcontainer').attr('scrollTop', newTop);
910 // We use clientWidth here to avoid miscalculating due to scroll bar
911 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
912 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
913 newLeft = Math.max(newLeft, 0);
914 $('#GBcontainer').attr('scrollLeft', newLeft);
915 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
917 //this.centerPageView();
920 // Not really needed until there is 1up autofit
921 this.removeSearchHilites();
922 this.updateSearchHilites();
926 //______________________________________________________________________________
927 // Returns the current offset of the viewport center in scaled document coordinates.
928 GnuBook.prototype.centerX1up = function() {
930 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
931 centerX = $('#GBpageview').width();
933 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
935 centerX = Math.floor(centerX);
940 //______________________________________________________________________________
941 // Returns the current offset of the viewport center in scaled document coordinates.
942 GnuBook.prototype.centerY1up = function() {
943 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
944 return Math.floor(centerY);
948 //______________________________________________________________________________
949 GnuBook.prototype.centerPageView = function() {
951 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
952 var clientWidth = $('#GBcontainer').attr('clientWidth');
953 //console.log('sW='+scrollWidth+' cW='+clientWidth);
954 if (scrollWidth > clientWidth) {
955 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
960 // zoom2up(direction)
961 //______________________________________________________________________________
962 GnuBook.prototype.zoom2up = function(direction) {
964 // Hard stop autoplay
965 this.stopFlipAnimations();
967 // Get new zoom state
968 var newZoom = this.twoPageNextReduce(this.reduce, direction);
969 if ((this.reduce == newZoom.reduce) && (this.twoPage.autofit == newZoom.autofit)) {
972 this.twoPage.autofit = newZoom.autofit;
973 this.reduce = newZoom.reduce;
974 this.pageScale = this.reduce; // preserve current reduce
976 // Preserve view center position
977 var oldCenter = this.twoPageGetViewCenter();
979 // If zooming in, reload imgs. DOM elements will be removed by prepareTwoPageView
980 // $$$ An improvement would be to use the low res image until the larger one is loaded.
981 if (1 == direction) {
982 for (var img in this.prefetchedImgs) {
983 delete this.prefetchedImgs[img];
987 // Prepare view with new center to minimize visual glitches
988 this.prepareTwoPageView(oldCenter.percentageX, oldCenter.percentageY);
992 // quantizeReduce(reduce)
993 //______________________________________________________________________________
994 // Quantizes the given reduction factor to closest power of two from set from 12.5% to 200%
995 GnuBook.prototype.quantizeReduce = function(reduce) {
996 var quantized = this.reductionFactors[0];
997 var distance = Math.abs(reduce - quantized);
998 for (var i = 1; i < this.reductionFactors.length; i++) {
999 newDistance = Math.abs(reduce - this.reductionFactors[i]);
1000 if (newDistance < distance) {
1001 distance = newDistance;
1002 quantized = this.reductionFactors[i];
1009 // twoPageNextReduce()
1010 //______________________________________________________________________________
1011 // Returns the next reduction level
1012 GnuBook.prototype.twoPageNextReduce = function(reduce, direction) {
1014 var autofitReduce = this.twoPageGetAutofitReduce();
1016 if (0 == direction) { // autofit
1017 result.autofit = true;
1018 result.reduce = autofitReduce;
1020 } else if (1 == direction) { // zoom in
1021 var newReduce = this.reductionFactors[0];
1023 for (var i = 1; i < this.reductionFactors.length; i++) {
1024 if (this.reductionFactors[i] < reduce) {
1025 newReduce = this.reductionFactors[i];
1029 if (!this.twoPage.autofit && (autofitReduce < reduce && autofitReduce > newReduce)) {
1031 result.autofit = true;
1032 result.reduce = autofitReduce;
1034 result.autofit = false;
1035 result.reduce = newReduce;
1038 } else { // zoom out
1039 var lastIndex = this.reductionFactors.length - 1;
1040 var newReduce = this.reductionFactors[lastIndex];
1042 for (var i = lastIndex; i >= 0; i--) {
1043 if (this.reductionFactors[i] > reduce) {
1044 newReduce = this.reductionFactors[i];
1048 if (!this.twoPage.autofit && (autofitReduce > reduce && autofitReduce < newReduce)) {
1050 result.autofit = true;
1051 result.reduce = autofitReduce;
1053 result.autofit = false;
1054 result.reduce = newReduce;
1062 //______________________________________________________________________________
1063 // Attempts to jump to page. Returns true if page could be found, false otherwise.
1064 GnuBook.prototype.jumpToPage = function(pageNum) {
1066 var pageIndex = this.getPageIndex(pageNum);
1068 if ('undefined' != typeof(pageIndex)) {
1071 this.jumpToIndex(pageIndex);
1072 $('#GBcontainer').attr('scrollTop', leafTop);
1081 //______________________________________________________________________________
1082 GnuBook.prototype.jumpToIndex = function(index, pageX, pageY) {
1084 if (2 == this.mode) {
1087 // By checking against min/max we do nothing if requested index
1089 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1090 this.flipBackToIndex(index);
1091 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
1092 this.flipFwdToIndex(index);
1095 } else if (3 == this.mode){
1096 var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
1106 for (i=0; i<(index+1); i++) {
1107 leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
1108 if (rightPos + (leafWidth + this.padding) > viewWidth){
1113 leafHeight = parseInt(this.getPageHeight(i)/this.reduce, 10);
1114 if(leafHeight > rowHeight) { rowHeight = leafHeight; }
1115 if (leafIndex==0) { leafTop = bottomPos; }
1116 if (leafIndex==0) { bottomPos += this.padding + rowHeight; }
1117 rightPos += leafWidth + this.padding;
1120 this.firstIndex=index;
1121 if ($('#GBcontainer').attr('scrollTop') == leafTop) {
1124 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
1131 for (i=0; i<index; i++) {
1132 h = parseInt(this._getPageHeight(i)/this.reduce);
1133 leafTop += h + this.padding;
1137 //console.log('pageY ' + pageY);
1138 var offset = parseInt( (pageY) / this.reduce);
1139 offset -= $('#GBcontainer').attr('clientHeight') >> 1;
1140 //console.log( 'jumping to ' + leafTop + ' ' + offset);
1145 var offset = parseInt( (pageX) / this.reduce);
1146 offset -= $('#GBcontainer').attr('clientWidth') >> 1;
1150 //$('#GBcontainer').attr('scrollTop', leafTop);
1151 $('#GBcontainer').animate({scrollTop: leafTop, scrollLeft: leafLeft },'fast');
1157 //______________________________________________________________________________
1158 GnuBook.prototype.switchMode = function(mode) {
1160 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
1162 if (mode == this.mode) return;
1164 if (!this.canSwitchToMode(mode)) {
1169 this.removeSearchHilites();
1172 this.switchToolbarMode(mode);
1174 // reinstate scale if moving from thumbnail view
1175 if (this.pageScale != this.reduce) this.reduce = this.pageScale;
1177 // $$$ TODO preserve center of view when switching between mode
1178 // See https://bugs.edge.launchpad.net/gnubook/+bug/416682
1181 this.reduce = this.quantizeReduce(this.reduce);
1182 this.prepareOnePageView();
1183 } else if (3 == mode) {
1184 this.reduce = this.quantizeReduce(this.reduce);
1185 this.prepareThumbnailView();
1186 this.jumpToIndex(this.currentIndex());
1188 this.twoPage.autofit = false; // Take zoom level from other mode
1189 this.reduce = this.quantizeReduce(this.reduce);
1190 this.prepareTwoPageView();
1191 this.twoPageCenterView(0.5, 0.5); // $$$ TODO preserve center
1196 //prepareOnePageView()
1197 //______________________________________________________________________________
1198 GnuBook.prototype.prepareOnePageView = function() {
1200 // var startLeaf = this.displayedIndices[0];
1201 var startLeaf = this.currentIndex();
1203 $('#GBcontainer').empty();
1204 $('#GBcontainer').css({
1205 overflowY: 'scroll',
1209 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
1211 this.resizePageView();
1213 this.jumpToIndex(startLeaf);
1214 this.displayedIndices = [];
1216 this.drawLeafsOnePage();
1218 // Bind mouse handlers
1219 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1220 gbPageView.bind('mousedown', function(e) {
1221 // $$$ check here for right-click and don't disable. Also use jQuery style
1222 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1225 // Special hack for IE7
1226 gbPageView[0].onselectstart = function(e) { return false; };
1229 //prepareThumbnailView()
1230 //______________________________________________________________________________
1231 GnuBook.prototype.prepareThumbnailView = function() {
1233 // var startLeaf = this.displayedIndices[0];
1234 var startLeaf = this.currentIndex();
1235 this.reduce = this.thumbScale;
1237 $('#GBcontainer').empty();
1238 $('#GBcontainer').css({
1239 overflowY: 'scroll',
1243 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
1245 this.resizePageView();
1247 this.displayedRows = [];
1248 this.drawLeafsThumbnail();
1250 // Bind mouse handlers
1251 // Disable mouse click to avoid selected/highlighted page images - bug 354239
1252 gbPageView.bind('mousedown', function(e) {
1253 // $$$ check here for right-click and don't disable. Also use jQuery style
1254 // for stopping propagation. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
1257 // Special hack for IE7
1258 gbPageView[0].onselectstart = function(e) { return false; };
1261 // prepareTwoPageView()
1262 //______________________________________________________________________________
1263 // Some decisions about two page view:
1265 // Both pages will be displayed at the same height, even if they were different physical/scanned
1266 // sizes. This simplifies the animation (from a design as well as technical standpoint). We
1267 // examine the page aspect ratios (in calculateSpreadSize) and use the page with the most "normal"
1268 // aspect ratio to determine the height.
1270 // The two page view div is resized to keep the middle of the book in the middle of the div
1271 // even as the page sizes change. To e.g. keep the middle of the book in the middle of the GBcontent
1272 // div requires adjusting the offset of GBtwpageview and/or scrolling in GBcontent.
1273 GnuBook.prototype.prepareTwoPageView = function(centerPercentageX, centerPercentageY) {
1274 $('#GBcontainer').empty();
1275 $('#GBcontainer').css('overflow', 'auto');
1277 // We want to display two facing pages. We may be missing
1278 // one side of the spread because it is the first/last leaf,
1279 // foldouts, missing pages, etc
1281 //var targetLeaf = this.displayedIndices[0];
1282 var targetLeaf = this.firstIndex;
1284 if (targetLeaf < this.firstDisplayableIndex()) {
1285 targetLeaf = this.firstDisplayableIndex();
1288 if (targetLeaf > this.lastDisplayableIndex()) {
1289 targetLeaf = this.lastDisplayableIndex();
1292 //this.twoPage.currentIndexL = null;
1293 //this.twoPage.currentIndexR = null;
1294 //this.pruneUnusedImgs();
1296 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
1297 this.twoPage.currentIndexL = currentSpreadIndices[0];
1298 this.twoPage.currentIndexR = currentSpreadIndices[1];
1299 this.firstIndex = this.twoPage.currentIndexL;
1301 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height and others
1303 this.pruneUnusedImgs();
1304 this.prefetch(); // Preload images or reload if scaling has changed
1306 //console.dir(this.twoPage);
1308 // Add the two page view
1309 // $$$ Can we get everything set up and then append?
1310 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
1312 // $$$ calculate first then set
1313 $('#GBtwopageview').css( {
1314 height: this.twoPage.totalHeight + 'px',
1315 width: this.twoPage.totalWidth + 'px',
1316 position: 'absolute'
1319 // If there will not be scrollbars (e.g. when zooming out) we center the book
1320 // since otherwise the book will be stuck off-center
1321 if (this.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
1322 centerPercentageX = 0.5;
1324 if (this.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
1325 centerPercentageY = 0.5;
1328 this.twoPageCenterView(centerPercentageX, centerPercentageY);
1330 this.twoPage.coverDiv = document.createElement('div');
1331 $(this.twoPage.coverDiv).attr('id', 'GBbookcover').css({
1332 border: '1px solid rgb(68, 25, 17)',
1333 width: this.twoPage.bookCoverDivWidth + 'px',
1334 height: this.twoPage.bookCoverDivHeight+'px',
1335 visibility: 'visible',
1336 position: 'absolute',
1337 backgroundColor: '#663929',
1338 left: this.twoPage.bookCoverDivLeft + 'px',
1339 top: this.twoPage.bookCoverDivTop+'px',
1340 MozBorderRadiusTopleft: '7px',
1341 MozBorderRadiusTopright: '7px',
1342 MozBorderRadiusBottomright: '7px',
1343 MozBorderRadiusBottomleft: '7px'
1344 }).appendTo('#GBtwopageview');
1346 this.leafEdgeR = document.createElement('div');
1347 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
1348 $(this.leafEdgeR).css({
1349 borderStyle: 'solid solid solid none',
1350 borderColor: 'rgb(51, 51, 34)',
1351 borderWidth: '1px 1px 1px 0px',
1352 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
1353 width: this.twoPage.leafEdgeWidthR + 'px',
1354 height: this.twoPage.height-1 + 'px',
1356 left: this.twoPage.gutter+this.twoPage.scaledWR+'px',
1357 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1358 position: 'absolute'
1359 }).appendTo('#GBtwopageview');
1361 this.leafEdgeL = document.createElement('div');
1362 this.leafEdgeL.className = 'leafEdgeL';
1363 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
1364 borderStyle: 'solid none solid solid',
1365 borderColor: 'rgb(51, 51, 34)',
1366 borderWidth: '1px 0px 1px 1px',
1367 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1368 width: this.twoPage.leafEdgeWidthL + 'px',
1369 height: this.twoPage.height-1 + 'px',
1370 left: this.twoPage.bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
1371 top: this.twoPage.bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
1372 position: 'absolute'
1373 }).appendTo('#GBtwopageview');
1375 div = document.createElement('div');
1376 $(div).attr('id', 'GBbookspine').css({
1377 border: '1px solid rgb(68, 25, 17)',
1378 width: this.twoPage.bookSpineDivWidth+'px',
1379 height: this.twoPage.bookSpineDivHeight+'px',
1380 position: 'absolute',
1381 backgroundColor: 'rgb(68, 25, 17)',
1382 left: this.twoPage.bookSpineDivLeft+'px',
1383 top: this.twoPage.bookSpineDivTop+'px'
1384 }).appendTo('#GBtwopageview');
1386 var self = this; // for closure
1388 /* Flip areas no longer used
1389 this.twoPage.leftFlipArea = document.createElement('div');
1390 this.twoPage.leftFlipArea.className = 'GBfliparea';
1391 $(this.twoPage.leftFlipArea).attr('id', 'GBleftflip').css({
1393 width: this.twoPageFlipAreaWidth() + 'px',
1394 height: this.twoPageFlipAreaHeight() + 'px',
1395 position: 'absolute',
1396 left: this.twoPageLeftFlipAreaLeft() + 'px',
1397 top: this.twoPageFlipAreaTop() + 'px',
1400 }).bind('click', function(e) {
1402 }).bind('mousedown', function(e) {
1404 }).appendTo('#GBtwopageview');
1406 this.twoPage.rightFlipArea = document.createElement('div');
1407 this.twoPage.rightFlipArea.className = 'GBfliparea';
1408 $(this.twoPage.rightFlipArea).attr('id', 'GBrightflip').css({
1410 width: this.twoPageFlipAreaWidth() + 'px',
1411 height: this.twoPageFlipAreaHeight() + 'px',
1412 position: 'absolute',
1413 left: this.twoPageRightFlipAreaLeft() + 'px',
1414 top: this.twoPageFlipAreaTop() + 'px',
1417 }).bind('click', function(e) {
1419 }).bind('mousedown', function(e) {
1421 }).appendTo('#GBtwopageview');
1424 this.prepareTwoPagePopUp();
1426 this.displayedIndices = [];
1428 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
1429 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
1431 this.drawLeafsTwoPage();
1432 this.updateToolbarZoom(this.reduce);
1436 this.removeSearchHilites();
1437 this.updateSearchHilites();
1441 // prepareTwoPagePopUp()
1443 // This function prepares the "View Page n" popup that shows while the mouse is
1444 // over the left/right "stack of sheets" edges. It also binds the mouse
1445 // events for these divs.
1446 //______________________________________________________________________________
1447 GnuBook.prototype.prepareTwoPagePopUp = function() {
1449 this.twoPagePopUp = document.createElement('div');
1450 $(this.twoPagePopUp).css({
1451 border: '1px solid black',
1453 position: 'absolute',
1454 fontFamily: 'sans-serif',
1457 backgroundColor: 'rgb(255, 255, 238)',
1459 }).appendTo('#GBcontainer');
1460 $(this.twoPagePopUp).hide();
1462 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
1463 $(e.data.twoPagePopUp).show();
1466 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
1467 $(e.data.twoPagePopUp).hide();
1470 $(this.leafEdgeL).bind('click', this, function(e) {
1472 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1473 e.data.jumpToIndex(jumpIndex);
1476 $(this.leafEdgeR).bind('click', this, function(e) {
1478 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1479 e.data.jumpToIndex(jumpIndex);
1482 $(this.leafEdgeR).bind('mousemove', this, function(e) {
1484 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
1485 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
1487 // $$$ TODO: Make sure popup is positioned so that it is in view
1488 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1489 $(e.data.twoPagePopUp).css({
1490 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
1491 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1495 $(this.leafEdgeL).bind('mousemove', this, function(e) {
1497 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
1498 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
1500 // $$$ TODO: Make sure popup is positioned so that it is in view
1501 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
1502 $(e.data.twoPagePopUp).css({
1503 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
1504 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1509 // calculateSpreadSize()
1510 //______________________________________________________________________________
1511 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1512 // this.twoPage.currentIndexR
1513 // This function sets this.twoPage.height, twoPage.width
1515 GnuBook.prototype.calculateSpreadSize = function() {
1517 var firstIndex = this.twoPage.currentIndexL;
1518 var secondIndex = this.twoPage.currentIndexR;
1519 //console.log('first page is ' + firstIndex);
1521 // Calculate page sizes and total leaf width
1523 if ( this.twoPage.autofit) {
1524 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1526 // set based on reduction factor
1527 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1530 // Both pages together
1531 this.twoPage.height = spreadSize.height;
1532 this.twoPage.width = spreadSize.width;
1535 this.twoPage.scaledWL = this.getPageWidth2UP(firstIndex);
1536 this.twoPage.scaledWR = this.getPageWidth2UP(secondIndex);
1539 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1540 this.twoPage.leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1541 this.twoPage.leafEdgeWidthR = this.twoPage.edgeWidth - this.twoPage.leafEdgeWidthL;
1545 // The width of the book cover div. The combined width of both pages, twice the width
1546 // of the book cover internal padding (2*10) and the page edges
1547 this.twoPage.bookCoverDivWidth = this.twoPage.scaledWL + this.twoPage.scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
1548 // The height of the book cover div
1549 this.twoPage.bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
1552 // We calculate the total width and height for the div so that we can make the book
1554 var leftGutterOffset = this.gutterOffsetForIndex(firstIndex);
1555 var leftWidthFromCenter = this.twoPage.scaledWL - leftGutterOffset + this.twoPage.leafEdgeWidthL;
1556 var rightWidthFromCenter = this.twoPage.scaledWR + leftGutterOffset + this.twoPage.leafEdgeWidthR;
1557 var largestWidthFromCenter = Math.max( leftWidthFromCenter, rightWidthFromCenter );
1558 this.twoPage.totalWidth = 2 * (largestWidthFromCenter + this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1559 this.twoPage.totalHeight = this.twoPage.height + 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1561 // We want to minimize the unused space in two-up mode (maximize the amount of page
1562 // shown). We give width to the leaf edges and these widths change (though the sum
1563 // of the two remains constant) as we flip through the book. With the book
1564 // cover centered and fixed in the GBcontainer div the page images will meet
1565 // at the "gutter" which is generally offset from the center.
1566 this.twoPage.middle = this.twoPage.totalWidth >> 1;
1567 this.twoPage.gutter = this.twoPage.middle + this.gutterOffsetForIndex(firstIndex);
1569 // The left edge of the book cover moves depending on the width of the pages
1570 // $$$ change to getter
1571 this.twoPage.bookCoverDivLeft = this.twoPage.gutter - this.twoPage.scaledWL - this.twoPage.leafEdgeWidthL - this.twoPage.coverInternalPadding;
1572 // The top edge of the book cover stays a fixed distance from the top
1573 this.twoPage.bookCoverDivTop = this.twoPage.coverExternalPadding;
1576 this.twoPage.bookSpineDivHeight = this.twoPage.height + 2*this.twoPage.coverInternalPadding;
1577 this.twoPage.bookSpineDivLeft = this.twoPage.middle - (this.twoPage.bookSpineDivWidth >> 1);
1578 this.twoPage.bookSpineDivTop = this.twoPage.bookCoverDivTop;
1581 this.reduce = spreadSize.reduce; // $$$ really set this here?
1584 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1587 // We check which page is closest to a "normal" page and use that to set the height
1588 // for both pages. This means that foldouts and other odd size pages will be displayed
1589 // smaller than the nominal zoom amount.
1590 var canon5Dratio = 1.5;
1593 height: this._getPageHeight(firstIndex),
1594 width: this._getPageWidth(firstIndex)
1598 height: this._getPageHeight(secondIndex),
1599 width: this._getPageWidth(secondIndex)
1602 var firstIndexRatio = first.height / first.width;
1603 var secondIndexRatio = second.height / second.width;
1604 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1607 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1608 ratio = firstIndexRatio;
1609 //console.log('using firstIndexRatio ' + ratio);
1611 ratio = secondIndexRatio;
1612 //console.log('using secondIndexRatio ' + ratio);
1615 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1616 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1617 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1619 var widthOutsidePages = 2 * (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding) + ideal.totalLeafEdgeWidth;
1620 var heightOutsidePages = 2* (this.twoPage.coverInternalPadding + this.twoPage.coverExternalPadding);
1622 ideal.width = ($('#GBcontainer').width() - widthOutsidePages) >> 1;
1623 ideal.width -= 10; // $$$ fudge factor
1624 ideal.height = $('#GBcontainer').height() - heightOutsidePages;
1625 ideal.height -= 20; // fudge factor
1626 //console.log('init idealWidth='+ideal.width+' idealHeight='+ideal.height + ' ratio='+ratio);
1628 if (ideal.height/ratio <= ideal.width) {
1630 ideal.width = parseInt(ideal.height/ratio);
1633 ideal.height = parseInt(ideal.width*ratio);
1636 // $$$ check this logic with large spreads
1637 ideal.reduce = ((first.height + second.height) / 2) / ideal.height;
1642 // getSpreadSizeFromReduce()
1643 //______________________________________________________________________________
1644 // Returns the spread size calculated from the reduction factor for the given pages
1645 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1646 var spreadSize = {};
1647 // $$$ Scale this based on reduce?
1648 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1649 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1); // $$$ Assumes leaf edge width constant at all zoom levels
1650 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1652 // $$$ Possibly incorrect -- we should make height "dominant"
1653 var nativeWidth = this._getPageWidth(firstIndex) + this._getPageWidth(secondIndex);
1654 var nativeHeight = this._getPageHeight(firstIndex) + this._getPageHeight(secondIndex);
1655 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1656 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1657 spreadSize.reduce = reduce;
1662 // twoPageGetAutofitReduce()
1663 //______________________________________________________________________________
1664 // Returns the current ideal reduction factor
1665 GnuBook.prototype.twoPageGetAutofitReduce = function() {
1666 var spreadSize = this.getIdealSpreadSize(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
1667 return spreadSize.reduce;
1670 // twoPageSetCursor()
1671 //______________________________________________________________________________
1672 // Set the cursor for two page view
1673 GnuBook.prototype.twoPageSetCursor = function() {
1674 // console.log('setting cursor');
1675 if ( ($('#GBtwopageview').width() > $('#GBcontainer').attr('clientWidth')) ||
1676 ($('#GBtwopageview').height() > $('#GBcontainer').attr('clientHeight')) ) {
1677 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','move');
1678 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','move');
1680 $(this.prefetchedImgs[this.twoPage.currentIndexL]).css('cursor','');
1681 $(this.prefetchedImgs[this.twoPage.currentIndexR]).css('cursor','');
1686 //______________________________________________________________________________
1687 // Returns the currently active index.
1688 GnuBook.prototype.currentIndex = function() {
1689 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1690 if (this.mode == this.constMode1up || this.mode == this.constModeThumb) {
1691 return this.firstIndex; // $$$ TODO page in center of view would be better
1692 } else if (this.mode == this.constMode2up) {
1693 // Only allow indices that are actually present in book
1694 return GnuBook.util.clamp(this.firstIndex, 0, this.numLeafs - 1);
1696 throw 'currentIndex called for unimplemented mode ' + this.mode;
1701 //______________________________________________________________________________
1702 // Flip the right page over onto the left
1703 GnuBook.prototype.right = function() {
1704 if ('rl' != this.pageProgression) {
1714 //______________________________________________________________________________
1715 // Flip to the rightmost page
1716 GnuBook.prototype.rightmost = function() {
1717 if ('rl' != this.pageProgression) {
1725 //______________________________________________________________________________
1726 // Flip the left page over onto the right.
1727 GnuBook.prototype.left = function() {
1728 if ('rl' != this.pageProgression) {
1738 //______________________________________________________________________________
1739 // Flip to the leftmost page
1740 GnuBook.prototype.leftmost = function() {
1741 if ('rl' != this.pageProgression) {
1749 //______________________________________________________________________________
1750 GnuBook.prototype.next = function() {
1751 if (2 == this.mode) {
1753 this.flipFwdToIndex(null);
1755 if (this.firstIndex < this.lastDisplayableIndex()) {
1756 this.jumpToIndex(this.firstIndex+1);
1762 //______________________________________________________________________________
1763 GnuBook.prototype.prev = function() {
1764 if (2 == this.mode) {
1766 this.flipBackToIndex(null);
1768 if (this.firstIndex >= 1) {
1769 this.jumpToIndex(this.firstIndex-1);
1774 GnuBook.prototype.first = function() {
1775 this.jumpToIndex(this.firstDisplayableIndex());
1778 GnuBook.prototype.last = function() {
1779 this.jumpToIndex(this.lastDisplayableIndex());
1782 // flipBackToIndex()
1783 //______________________________________________________________________________
1784 // to flip back one spread, pass index=null
1785 GnuBook.prototype.flipBackToIndex = function(index) {
1787 if (1 == this.mode) return;
1789 var leftIndex = this.twoPage.currentIndexL;
1791 if (this.animating) return;
1793 if (null != this.leafEdgeTmp) {
1794 alert('error: leafEdgeTmp should be null!');
1798 if (null == index) {
1799 index = leftIndex-2;
1801 //if (index<0) return;
1803 var previousIndices = this.getSpreadIndices(index);
1805 if (previousIndices[0] < this.firstDisplayableIndex() || previousIndices[1] < this.firstDisplayableIndex()) {
1809 this.animating = true;
1811 if ('rl' != this.pageProgression) {
1812 // Assume LTR and we are going backward
1813 this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1814 this.flipLeftToRight(previousIndices[0], previousIndices[1]);
1816 // RTL and going backward
1817 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1818 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1822 // flipLeftToRight()
1823 //______________________________________________________________________________
1824 // Flips the page on the left towards the page on the right
1825 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR) {
1827 var leftLeaf = this.twoPage.currentIndexL;
1829 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1830 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1831 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1833 var currWidthL = this.getPageWidth2UP(leftLeaf);
1834 var newWidthL = this.getPageWidth2UP(newIndexL);
1835 var newWidthR = this.getPageWidth2UP(newIndexR);
1837 var top = this.twoPageTop();
1838 var gutter = this.twoPage.middle + this.gutterOffsetForIndex(newIndexL);
1840 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1841 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1843 //animation strategy:
1844 // 0. remove search highlight, if any.
1845 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1846 // of the left leaf and where the user clicked in the leaf edge.
1847 // Note that if this function was triggered by left() and not a
1848 // mouse click, the width of leafEdgeTmp is very small (zero px).
1849 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1850 // leftLeaf to width=0.
1851 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1852 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1853 // its new full width.
1854 // 4. After step 3 is finished, do the following:
1855 // - remove leafEdgeTmp from the dom.
1856 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1857 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1858 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1859 // and width=newLeafEdgeWidthL.
1860 // - resize the back cover (twoPage.coverDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1861 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1862 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1863 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1864 // - prefetch new adjacent leafs.
1865 // - set up click handlers for both new left and right leafs.
1866 // - redraw the search highlight.
1867 // - update the pagenum box and the url.
1870 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1872 this.leafEdgeTmp = document.createElement('div');
1873 $(this.leafEdgeTmp).css({
1874 borderStyle: 'solid none solid solid',
1875 borderColor: 'rgb(51, 51, 34)',
1876 borderWidth: '1px 0px 1px 1px',
1877 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1878 width: leafEdgeTmpW + 'px',
1879 height: this.twoPage.height-1 + 'px',
1880 left: leftEdgeTmpLeft + 'px',
1882 position: 'absolute',
1884 }).appendTo('#GBtwopageview');
1886 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1887 $(this.leafEdgeL).css({
1888 width: newLeafEdgeWidthL+'px',
1889 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1892 // Left gets the offset of the current left leaf from the document
1893 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1894 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1895 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1897 // We change the left leaf to right positioning
1898 // $$$ This causes animation glitches during resize. See https://bugs.edge.launchpad.net/gnubook/+bug/328327
1899 $(this.prefetchedImgs[leftLeaf]).css({
1904 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1905 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1909 this.removeSearchHilites();
1911 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1912 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1914 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1915 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1917 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1918 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1919 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1921 $(self.leafEdgeR).css({
1922 // Moves the right leaf edge
1923 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1924 left: gutter+newWidthR+'px'
1927 $(self.leafEdgeL).css({
1928 // Moves and resizes the left leaf edge
1929 width: newLeafEdgeWidthL+'px',
1930 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1933 // Resizes the brown border div
1934 $(self.twoPage.coverDiv).css({
1935 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
1936 left: gutter-newWidthL-newLeafEdgeWidthL-self.twoPage.coverInternalPadding+'px'
1939 $(self.leafEdgeTmp).remove();
1940 self.leafEdgeTmp = null;
1942 // $$$ TODO refactor with opposite direction flip
1944 self.twoPage.currentIndexL = newIndexL;
1945 self.twoPage.currentIndexR = newIndexR;
1946 self.twoPage.scaledWL = newWidthL;
1947 self.twoPage.scaledWR = newWidthR;
1948 self.twoPage.gutter = gutter;
1950 self.firstIndex = self.twoPage.currentIndexL;
1951 self.displayedIndices = [newIndexL, newIndexR];
1952 self.pruneUnusedImgs();
1954 self.animating = false;
1956 self.updateSearchHilites2UP();
1957 self.updatePageNumBox2UP();
1959 // self.twoPagePlaceFlipAreas(); // No longer used
1960 self.setMouseHandlers2UP();
1961 self.twoPageSetCursor();
1963 if (self.animationFinishedCallback) {
1964 self.animationFinishedCallback();
1965 self.animationFinishedCallback = null;
1973 //______________________________________________________________________________
1974 // Whether we flip left or right is dependent on the page progression
1975 // to flip forward one spread, pass index=null
1976 GnuBook.prototype.flipFwdToIndex = function(index) {
1978 if (this.animating) return;
1980 if (null != this.leafEdgeTmp) {
1981 alert('error: leafEdgeTmp should be null!');
1985 if (null == index) {
1986 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1988 if (index > this.lastDisplayableIndex()) return;
1990 this.animating = true;
1992 var nextIndices = this.getSpreadIndices(index);
1994 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1996 if ('rl' != this.pageProgression) {
1997 // We did not specify RTL
1998 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1999 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
2002 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
2003 this.flipLeftToRight(nextIndices[0], nextIndices[1]);
2007 // flipRightToLeft(nextL, nextR, gutter)
2008 // $$$ better not to have to pass gutter in
2009 //______________________________________________________________________________
2010 // Flip from left to right and show the nextL and nextR indices on those sides
2011 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR) {
2012 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
2013 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
2014 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
2015 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
2017 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
2019 var top = this.twoPageTop();
2020 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
2022 var middle = this.twoPage.middle;
2023 var gutter = middle + this.gutterOffsetForIndex(newIndexL);
2025 this.leafEdgeTmp = document.createElement('div');
2026 $(this.leafEdgeTmp).css({
2027 borderStyle: 'solid none solid solid',
2028 borderColor: 'rgb(51, 51, 34)',
2029 borderWidth: '1px 0px 1px 1px',
2030 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
2031 width: leafEdgeTmpW + 'px',
2032 height: this.twoPage.height-1 + 'px',
2033 left: gutter+scaledW+'px',
2035 position: 'absolute',
2037 }).appendTo('#GBtwopageview');
2039 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
2040 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
2042 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
2043 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
2044 var newWidthL = this.getPageWidth2UP(newIndexL);
2045 var newWidthR = this.getPageWidth2UP(newIndexR);
2047 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
2049 var self = this; // closure-tastic!
2051 var speed = this.flipSpeed;
2053 this.removeSearchHilites();
2055 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
2056 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
2057 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
2058 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
2059 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
2061 $(self.leafEdgeL).css({
2062 width: newLeafEdgeWidthL+'px',
2063 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
2066 // Resizes the book cover
2067 $(self.twoPage.coverDiv).css({
2068 width: self.twoPageCoverWidth(newWidthL+newWidthR)+'px',
2069 left: gutter - newWidthL - newLeafEdgeWidthL - self.twoPage.coverInternalPadding + 'px'
2072 $(self.leafEdgeTmp).remove();
2073 self.leafEdgeTmp = null;
2075 self.twoPage.currentIndexL = newIndexL;
2076 self.twoPage.currentIndexR = newIndexR;
2077 self.twoPage.scaledWL = newWidthL;
2078 self.twoPage.scaledWR = newWidthR;
2079 self.twoPage.gutter = gutter;
2081 self.firstIndex = self.twoPage.currentIndexL;
2082 self.displayedIndices = [newIndexL, newIndexR];
2083 self.pruneUnusedImgs();
2085 self.animating = false;
2088 self.updateSearchHilites2UP();
2089 self.updatePageNumBox2UP();
2091 // self.twoPagePlaceFlipAreas(); // No longer used
2092 self.setMouseHandlers2UP();
2093 self.twoPageSetCursor();
2095 if (self.animationFinishedCallback) {
2096 self.animationFinishedCallback();
2097 self.animationFinishedCallback = null;
2103 // setMouseHandlers2UP
2104 //______________________________________________________________________________
2105 GnuBook.prototype.setMouseHandlers2UP = function() {
2107 $(this.prefetchedImgs[this.twoPage.currentIndexL]).bind('dblclick', function() {
2112 $(this.prefetchedImgs[this.twoPage.currentIndexR]).bind('dblclick', function() {
2119 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL] );
2120 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexL],
2127 this.setDragHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR] );
2128 this.setClickHandler2UP( this.prefetchedImgs[this.twoPage.currentIndexR],
2131 e.data.self.right();
2137 //______________________________________________________________________________
2138 GnuBook.prototype.prefetchImg = function(index) {
2139 var pageURI = this._getPageURI(index);
2141 // Load image if not loaded or URI has changed (e.g. due to scaling)
2142 var loadImage = false;
2143 if (undefined == this.prefetchedImgs[index]) {
2144 //console.log('no image for ' + index);
2146 } else if (pageURI != this.prefetchedImgs[index].uri) {
2147 //console.log('uri changed for ' + index);
2152 //console.log('prefetching ' + index);
2153 var img = document.createElement("img");
2155 img.uri = pageURI; // browser may rewrite src so we stash raw URI here
2156 this.prefetchedImgs[index] = img;
2161 // prepareFlipLeftToRight()
2163 //______________________________________________________________________________
2165 // Prepare to flip the left page towards the right. This corresponds to moving
2166 // backward when the page progression is left to right.
2167 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
2169 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
2171 this.prefetchImg(prevL);
2172 this.prefetchImg(prevR);
2174 var height = this._getPageHeight(prevL);
2175 var width = this._getPageWidth(prevL);
2176 var middle = this.twoPage.middle;
2177 var top = this.twoPageTop();
2178 var scaledW = this.twoPage.height*width/height; // $$$ assumes height of page is dominant
2180 // The gutter is the dividing line between the left and right pages.
2181 // It is offset from the middle to create the illusion of thickness to the pages
2182 var gutter = middle + this.gutterOffsetForIndex(prevL);
2184 //console.log(' gutter for ' + prevL + ' is ' + gutter);
2185 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
2186 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
2189 position: 'absolute',
2190 left: gutter-scaledW+'px',
2191 right: '', // clear right property
2193 height: this.twoPage.height,
2194 width: scaledW+'px',
2195 backgroundColor: this.getPageBackgroundColor(prevL),
2196 borderRight: '1px solid black',
2200 $(this.prefetchedImgs[prevL]).css(leftCSS);
2202 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
2204 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
2207 position: 'absolute',
2211 height: this.twoPage.height,
2213 backgroundColor: this.getPageBackgroundColor(prevR),
2214 borderLeft: '1px solid black',
2218 $(this.prefetchedImgs[prevR]).css(rightCSS);
2220 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
2224 // $$$ mang we're adding an extra pixel in the middle. See https://bugs.edge.launchpad.net/gnubook/+bug/411667
2225 // prepareFlipRightToLeft()
2226 //______________________________________________________________________________
2227 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
2229 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
2232 this.prefetchImg(nextL);
2233 this.prefetchImg(nextR);
2235 var height = this._getPageHeight(nextR);
2236 var width = this._getPageWidth(nextR);
2237 var middle = this.twoPage.middle;
2238 var top = this.twoPageTop();
2239 var scaledW = this.twoPage.height*width/height;
2241 var gutter = middle + this.gutterOffsetForIndex(nextL);
2243 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
2244 $(this.prefetchedImgs[nextR]).css({
2245 position: 'absolute',
2248 backgroundColor: this.getPageBackgroundColor(nextR),
2249 height: this.twoPage.height,
2250 width: scaledW+'px',
2251 borderLeft: '1px solid black',
2255 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
2257 height = this._getPageHeight(nextL);
2258 width = this._getPageWidth(nextL);
2259 scaledW = this.twoPage.height*width/height;
2261 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
2262 $(this.prefetchedImgs[nextL]).css({
2263 position: 'absolute',
2264 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
2266 backgroundColor: this.getPageBackgroundColor(nextL),
2267 height: this.twoPage.height,
2268 width: 0+'px', // Start at 0 width, then grow to the left
2269 borderRight: '1px solid black',
2273 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
2277 // getNextLeafs() -- NOT RTL AWARE
2278 //______________________________________________________________________________
2279 // GnuBook.prototype.getNextLeafs = function(o) {
2280 // //TODO: we might have two left or two right leafs in a row (damaged book)
2281 // //For now, assume that leafs are contiguous.
2283 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
2284 // o.L = this.twoPage.currentIndexL+2;
2285 // o.R = this.twoPage.currentIndexL+3;
2288 // getprevLeafs() -- NOT RTL AWARE
2289 //______________________________________________________________________________
2290 // GnuBook.prototype.getPrevLeafs = function(o) {
2291 // //TODO: we might have two left or two right leafs in a row (damaged book)
2292 // //For now, assume that leafs are contiguous.
2294 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
2295 // o.L = this.twoPage.currentIndexL-2;
2296 // o.R = this.twoPage.currentIndexL-1;
2299 // pruneUnusedImgs()
2300 //______________________________________________________________________________
2301 GnuBook.prototype.pruneUnusedImgs = function() {
2302 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
2303 for (var key in this.prefetchedImgs) {
2304 //console.log('key is ' + key);
2305 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
2306 //console.log('removing key '+ key);
2307 $(this.prefetchedImgs[key]).remove();
2309 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
2310 //console.log('deleting key '+ key);
2311 delete this.prefetchedImgs[key];
2317 //______________________________________________________________________________
2318 GnuBook.prototype.prefetch = function() {
2320 // prefetch visible pages first
2321 this.prefetchImg(this.twoPage.currentIndexL);
2322 this.prefetchImg(this.twoPage.currentIndexR);
2324 var adjacentPagesToLoad = 3;
2326 var lowCurrent = Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2327 var highCurrent = Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR);
2329 var start = Math.max(lowCurrent - adjacentPagesToLoad, 0);
2330 var end = Math.min(highCurrent + adjacentPagesToLoad, this.numLeafs - 1);
2332 // Load images spreading out from current
2333 for (var i = 1; i <= adjacentPagesToLoad; i++) {
2334 var goingDown = lowCurrent - i;
2335 if (goingDown >= start) {
2336 this.prefetchImg(goingDown);
2338 var goingUp = highCurrent + i;
2339 if (goingUp <= end) {
2340 this.prefetchImg(goingUp);
2345 var lim = this.twoPage.currentIndexL-4;
2347 lim = Math.max(lim, 0);
2348 for (i = lim; i < this.twoPage.currentIndexL; i++) {
2349 this.prefetchImg(i);
2352 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
2353 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
2354 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
2355 this.prefetchImg(i);
2361 // getPageWidth2UP()
2362 //______________________________________________________________________________
2363 GnuBook.prototype.getPageWidth2UP = function(index) {
2364 // We return the width based on the dominant height
2365 var height = this._getPageHeight(index);
2366 var width = this._getPageWidth(index);
2367 return Math.floor(this.twoPage.height*width/height); // $$$ we assume width is relative to current spread
2371 //______________________________________________________________________________
2372 GnuBook.prototype.search = function(term) {
2373 term = term.replace(/\//g, ' '); // strip slashes
2374 this.searchTerm = term;
2375 $('#GnuBookSearchScript').remove();
2376 var script = document.createElement("script");
2377 script.setAttribute('id', 'GnuBookSearchScript');
2378 script.setAttribute("type", "text/javascript");
2379 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
2380 document.getElementsByTagName('head')[0].appendChild(script);
2381 $('#GnuBookSearchBox').val(term);
2382 $('#GnuBookSearchResults').html('Searching...');
2385 // GBSearchCallback()
2386 //______________________________________________________________________________
2387 GnuBook.prototype.GBSearchCallback = function(txt) {
2389 if (jQuery.browser.msie) {
2390 var dom=new ActiveXObject("Microsoft.XMLDOM");
2394 var parser = new DOMParser();
2395 var dom = parser.parseFromString(txt, "text/xml");
2398 $('#GnuBookSearchResults').empty();
2399 $('#GnuBookSearchResults').append('<ul>');
2401 for (var key in this.searchResults) {
2402 if (null != this.searchResults[key].div) {
2403 $(this.searchResults[key].div).remove();
2405 delete this.searchResults[key];
2408 var pages = dom.getElementsByTagName('PAGE');
2410 if (0 == pages.length) {
2411 // $$$ it would be nice to echo the (sanitized) search result here
2412 $('#GnuBookSearchResults').append('<li>No search results found</li>');
2414 for (var i = 0; i < pages.length; i++){
2415 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
2418 var re = new RegExp (/_(\d{4})/);
2419 var reMatch = re.exec(pages[i].getAttribute('file'));
2420 var index = parseInt(reMatch[1], 10);
2421 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
2423 var children = pages[i].childNodes;
2425 for (var j=0; j<children.length; j++) {
2426 //console.log(j + ' - ' + children[j].nodeName);
2427 //console.log(children[j].firstChild.nodeValue);
2428 if ('CONTEXT' == children[j].nodeName) {
2429 context += children[j].firstChild.nodeValue;
2430 } else if ('WORD' == children[j].nodeName) {
2431 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
2433 var index = this.leafNumToIndex(index);
2434 if (null != index) {
2435 //coordinates are [left, bottom, right, top, [baseline]]
2436 //we'll skip baseline for now...
2437 var coords = children[j].getAttribute('coords').split(',',4);
2438 if (4 == coords.length) {
2439 this.searchResults[index] = {'l':parseInt(coords[0]), 'b':parseInt(coords[1]), 'r':parseInt(coords[2]), 't':parseInt(coords[3]), 'div':null};
2444 var pageName = this.getPageName(index);
2445 var middleX = (this.searchResults[index].l + this.searchResults[index].r) >> 1;
2446 var middleY = (this.searchResults[index].t + this.searchResults[index].b) >> 1;
2447 //TODO: remove hardcoded instance name
2448 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+','+middleX+','+middleY+');">' + pageName + '</a></b> - ' + context + '</li>');
2451 $('#GnuBookSearchResults').append('</ul>');
2453 // $$$ update again for case of loading search URL in new browser window (search box may not have been ready yet)
2454 $('#GnuBookSearchBox').val(this.searchTerm);
2456 this.updateSearchHilites();
2459 // updateSearchHilites()
2460 //______________________________________________________________________________
2461 GnuBook.prototype.updateSearchHilites = function() {
2462 if (2 == this.mode) {
2463 this.updateSearchHilites2UP();
2465 this.updateSearchHilites1UP();
2469 // showSearchHilites1UP()
2470 //______________________________________________________________________________
2471 GnuBook.prototype.updateSearchHilites1UP = function() {
2473 for (var key in this.searchResults) {
2475 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
2476 var result = this.searchResults[key];
2477 if(null == result.div) {
2478 result.div = document.createElement('div');
2479 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
2480 //console.log('appending ' + key);
2483 width: (result.r-result.l)/this.reduce + 'px',
2484 height: (result.b-result.t)/this.reduce + 'px',
2485 left: (result.l)/this.reduce + 'px',
2486 top: (result.t)/this.reduce +'px'
2490 //console.log(key + ' not displayed');
2491 this.searchResults[key].div=null;
2497 //______________________________________________________________________________
2498 // Returns the position of the gutter (line between the page images)
2499 GnuBook.prototype.twoPageGutter = function() {
2500 return this.twoPage.middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
2504 //______________________________________________________________________________
2505 // Returns the offset for the top of the page images
2506 GnuBook.prototype.twoPageTop = function() {
2507 return this.twoPage.coverExternalPadding + this.twoPage.coverInternalPadding; // $$$ + border?
2510 // twoPageCoverWidth()
2511 //______________________________________________________________________________
2512 // Returns the width of the cover div given the total page width
2513 GnuBook.prototype.twoPageCoverWidth = function(totalPageWidth) {
2514 return totalPageWidth + this.twoPage.edgeWidth + 2*this.twoPage.coverInternalPadding;
2517 // twoPageGetViewCenter()
2518 //______________________________________________________________________________
2519 // Returns the percentage offset into twopageview div at the center of container div
2520 // { percentageX: float, percentageY: float }
2521 GnuBook.prototype.twoPageGetViewCenter = function() {
2524 var containerOffset = $('#GBcontainer').offset();
2525 var viewOffset = $('#GBtwopageview').offset();
2526 center.percentageX = (containerOffset.left - viewOffset.left + ($('#GBcontainer').attr('clientWidth') >> 1)) / this.twoPage.totalWidth;
2527 center.percentageY = (containerOffset.top - viewOffset.top + ($('#GBcontainer').attr('clientHeight') >> 1)) / this.twoPage.totalHeight;
2532 // twoPageCenterView(percentageX, percentageY)
2533 //______________________________________________________________________________
2534 // Centers the point given by percentage from left,top of twopageview
2535 GnuBook.prototype.twoPageCenterView = function(percentageX, percentageY) {
2536 if ('undefined' == typeof(percentageX)) {
2539 if ('undefined' == typeof(percentageY)) {
2543 var viewWidth = $('#GBtwopageview').width();
2544 var containerClientWidth = $('#GBcontainer').attr('clientWidth');
2545 var intoViewX = percentageX * viewWidth;
2547 var viewHeight = $('#GBtwopageview').height();
2548 var containerClientHeight = $('#GBcontainer').attr('clientHeight');
2549 var intoViewY = percentageY * viewHeight;
2551 if (viewWidth < containerClientWidth) {
2552 // Can fit width without scrollbars - center by adjusting offset
2553 $('#GBtwopageview').css('left', (containerClientWidth >> 1) - intoViewX + 'px');
2555 // Need to scroll to center
2556 $('#GBtwopageview').css('left', 0);
2557 $('#GBcontainer').scrollLeft(intoViewX - (containerClientWidth >> 1));
2560 if (viewHeight < containerClientHeight) {
2561 // Fits with scrollbars - add offset
2562 $('#GBtwopageview').css('top', (containerClientHeight >> 1) - intoViewY + 'px');
2564 $('#GBtwopageview').css('top', 0);
2565 $('#GBcontainer').scrollTop(intoViewY - (containerClientHeight >> 1));
2569 // twoPageFlipAreaHeight
2570 //______________________________________________________________________________
2571 // Returns the integer height of the click-to-flip areas at the edges of the book
2572 GnuBook.prototype.twoPageFlipAreaHeight = function() {
2573 return parseInt(this.twoPage.height);
2576 // twoPageFlipAreaWidth
2577 //______________________________________________________________________________
2578 // Returns the integer width of the flip areas
2579 GnuBook.prototype.twoPageFlipAreaWidth = function() {
2580 var max = 100; // $$$ TODO base on view width?
2583 var width = this.twoPage.width * 0.15;
2584 return parseInt(GnuBook.util.clamp(width, min, max));
2587 // twoPageFlipAreaTop
2588 //______________________________________________________________________________
2589 // Returns integer top offset for flip areas
2590 GnuBook.prototype.twoPageFlipAreaTop = function() {
2591 return parseInt(this.twoPage.bookCoverDivTop + this.twoPage.coverInternalPadding);
2594 // twoPageLeftFlipAreaLeft
2595 //______________________________________________________________________________
2596 // Left offset for left flip area
2597 GnuBook.prototype.twoPageLeftFlipAreaLeft = function() {
2598 return parseInt(this.twoPage.gutter - this.twoPage.scaledWL);
2601 // twoPageRightFlipAreaLeft
2602 //______________________________________________________________________________
2603 // Left offset for right flip area
2604 GnuBook.prototype.twoPageRightFlipAreaLeft = function() {
2605 return parseInt(this.twoPage.gutter + this.twoPage.scaledWR - this.twoPageFlipAreaWidth());
2608 // twoPagePlaceFlipAreas
2609 //______________________________________________________________________________
2610 // Readjusts position of flip areas based on current layout
2611 GnuBook.prototype.twoPagePlaceFlipAreas = function() {
2612 // We don't set top since it shouldn't change relative to view
2613 $(this.twoPage.leftFlipArea).css({
2614 left: this.twoPageLeftFlipAreaLeft() + 'px',
2615 width: this.twoPageFlipAreaWidth() + 'px'
2617 $(this.twoPage.rightFlipArea).css({
2618 left: this.twoPageRightFlipAreaLeft() + 'px',
2619 width: this.twoPageFlipAreaWidth() + 'px'
2623 // showSearchHilites2UP()
2624 //______________________________________________________________________________
2625 GnuBook.prototype.updateSearchHilites2UP = function() {
2627 for (var key in this.searchResults) {
2628 key = parseInt(key, 10);
2629 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
2630 var result = this.searchResults[key];
2631 if(null == result.div) {
2632 result.div = document.createElement('div');
2633 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
2634 //console.log('appending ' + key);
2637 // We calculate the reduction factor for the specific page because it can be different
2638 // for each page in the spread
2639 var height = this._getPageHeight(key);
2640 var width = this._getPageWidth(key)
2641 var reduce = this.twoPage.height/height;
2642 var scaledW = parseInt(width*reduce);
2644 var gutter = this.twoPageGutter();
2646 if ('L' == this.getPageSide(key)) {
2647 pageL = gutter-scaledW;
2651 var pageT = this.twoPageTop();
2654 width: (result.r-result.l)*reduce + 'px',
2655 height: (result.b-result.t)*reduce + 'px',
2656 left: pageL+(result.l)*reduce + 'px',
2657 top: pageT+(result.t)*reduce +'px'
2661 //console.log(key + ' not displayed');
2662 if (null != this.searchResults[key].div) {
2663 //console.log('removing ' + key);
2664 $(this.searchResults[key].div).remove();
2666 this.searchResults[key].div=null;
2671 // removeSearchHilites()
2672 //______________________________________________________________________________
2673 GnuBook.prototype.removeSearchHilites = function() {
2674 for (var key in this.searchResults) {
2675 if (null != this.searchResults[key].div) {
2676 $(this.searchResults[key].div).remove();
2677 this.searchResults[key].div=null;
2683 //______________________________________________________________________________
2684 GnuBook.prototype.printPage = function() {
2685 window.open(this.getPrintURI(), 'printpage', 'width=400, height=500, resizable=yes, scrollbars=no, toolbar=no, location=no');
2687 /* iframe implementation
2689 if (null != this.printPopup) { // check if already showing
2692 this.printPopup = document.createElement("div");
2693 $(this.printPopup).css({
2694 position: 'absolute',
2696 left: ($('#GBcontainer').width()-400)/2 + 'px',
2699 border: "3px double #999999",
2701 backgroundColor: "#fff"
2702 }).appendTo('#GnuBook');
2705 if (this.constMode1up == this.mode) {
2706 indexToPrint = this.firstIndex;
2708 indexToPrint = this.twoPage.currentIndexL;
2711 this.indexToPrint = indexToPrint;
2713 var htmlStr = '<div style="text-align: center;">';
2714 htmlStr = '<p style="text-align:center;"><b><a href="javascript:void(0);" onclick="window.frames[0].focus(); window.frames[0].print(); return false;">Click here to print this page</a></b></p>';
2715 htmlStr += '<div id="printDiv" name="printDiv" style="text-align: center; width: 233px; margin: auto">'
2716 htmlStr += '<p style="text-align:right; margin: 0; font-size: 0.85em">';
2717 //htmlStr += '<button class="GBicon rollover book_up" onclick="gb.updatePrintFrame(-1); return false;"></button> ';
2718 //htmlStr += '<button class="GBicon rollover book_down" onclick="gb.updatePrintFrame(1); return false;"></button>';
2719 htmlStr += '<a href="#" onclick="gb.updatePrintFrame(-1); return false;">Prev</a> <a href="#" onclick="gb.updatePrintFrame(1); return false;">Next</a>';
2721 htmlStr += '</div>';
2722 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.printPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2723 htmlStr += '</div>';
2725 this.printPopup.innerHTML = htmlStr;
2727 var iframe = document.createElement('iframe');
2728 iframe.id = 'printFrame';
2729 iframe.name = 'printFrame';
2730 iframe.width = '233px'; // 8.5 x 11 aspect
2731 iframe.height = '300px';
2733 var self = this; // closure
2735 $(iframe).load(function() {
2736 var doc = GnuBook.util.getIFrameDocument(this);
2737 $('body', doc).html(self.getPrintFrameContent(self.indexToPrint));
2740 $('#printDiv').prepend(iframe);
2744 // Get print URI from current indices and mode
2745 GnuBook.prototype.getPrintURI = function() {
2747 if (this.constMode2up == this.mode) {
2748 indexToPrint = this.twoPage.currentIndexL;
2750 indexToPrint = this.firstIndex; // $$$ the index in the middle of the viewport would make more sense
2753 var options = 'id=' + this.bookId + '&server=' + this.server + '&zip=' + this.zip
2754 + '&format=' + this.imageFormat + '&file=' + this._getPageFile(indexToPrint)
2755 + '&width=' + this._getPageWidth(indexToPrint) + '&height=' + this._getPageHeight(indexToPrint);
2757 if (this.constMode2up == this.mode) {
2758 options += '&file2=' + this._getPageFile(this.twoPage.currentIndexR) + '&width2=' + this._getPageWidth(this.twoPage.currentIndexR);
2759 options += '&height2=' + this._getPageHeight(this.twoPage.currentIndexR);
2760 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Pages ' + this.getPageNum(this.twoPage.currentIndexL) + ', ' + this.getPageNum(this.twoPage.currentIndexR));
2762 options += '&title=' + encodeURIComponent(this.shortTitle(50) + ' - Page ' + this.getPageNum(indexToPrint));
2765 return '/bookreader/print.php?' + options;
2768 /* iframe implementation
2769 GnuBook.prototype.getPrintFrameContent = function(index) {
2770 // We fit the image based on an assumed A4 aspect ratio. A4 is a bit taller aspect than
2771 // 8.5x11 so we should end up not overflowing on either paper size.
2772 var paperAspect = 8.5 / 11;
2773 var imageAspect = this._getPageWidth(index) / this._getPageHeight(index);
2777 // Rotate if possible and appropriate, to get larger image size on printed page
2778 if (this.canRotatePage(index)) {
2779 if (imageAspect > 1 && imageAspect > paperAspect) {
2780 // more wide than square, and more wide than paper
2782 imageAspect = 1/imageAspect;
2787 if (imageAspect > paperAspect) {
2788 // wider than paper, fit width
2789 fitAttrs = 'width="95%"';
2791 // taller than paper, fit height
2792 fitAttrs = 'height="95%"';
2795 var imageURL = this._getPageURI(index, 1, rotate);
2796 var iframeStr = '<html style="padding: 0; border: 0; margin: 0"><head><title>' + this.bookTitle + '</title></head><body style="padding: 0; border:0; margin: 0">';
2797 iframeStr += '<div style="text-align: center; width: 99%; height: 99%; overflow: hidden;">';
2798 iframeStr += '<img src="' + imageURL + '" ' + fitAttrs + ' />';
2799 iframeStr += '</div>';
2800 iframeStr += '</body></html>';
2805 GnuBook.prototype.updatePrintFrame = function(delta) {
2806 var newIndex = this.indexToPrint + delta;
2807 newIndex = GnuBook.util.clamp(newIndex, 0, this.numLeafs - 1);
2808 if (newIndex == this.indexToPrint) {
2811 this.indexToPrint = newIndex;
2812 var doc = GnuBook.util.getIFrameDocument($('#printFrame')[0]);
2813 $('body', doc).html(this.getPrintFrameContent(this.indexToPrint));
2818 //______________________________________________________________________________
2819 GnuBook.prototype.showEmbedCode = function() {
2820 if (null != this.embedPopup) { // check if already showing
2824 this.embedPopup = document.createElement("div");
2825 $(this.embedPopup).css({
2826 position: 'absolute',
2828 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
2831 border: "3px double #999999",
2833 backgroundColor: "#fff"
2834 }).appendTo('#GnuBook');
2836 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
2837 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>';
2838 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
2839 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
2841 this.embedPopup.innerHTML = htmlStr;
2842 $(this.embedPopup).find('input').bind('click', function() {
2848 //______________________________________________________________________________
2849 GnuBook.prototype.autoToggle = function() {
2851 var bComingFrom1up = false;
2852 if (2 != this.mode) {
2853 bComingFrom1up = true;
2857 // Change to autofit if book is too large
2858 if (this.reduce < this.twoPageGetAutofitReduce()) {
2863 if (null == this.autoTimer) {
2864 this.flipSpeed = 2000;
2866 // $$$ Draw events currently cause layout problems when they occur during animation.
2867 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
2868 // we workaround for now by not triggering immediate animation in that case.
2869 // See https://bugs.launchpad.net/gnubook/+bug/328327
2870 if (('rl' == this.pageProgression) && bComingFrom1up) {
2871 // don't flip immediately -- wait until timer fires
2874 this.flipFwdToIndex();
2877 $('#GBtoolbar .play').hide();
2878 $('#GBtoolbar .pause').show();
2879 this.autoTimer=setInterval(function(){
2880 if (self.animating) {return;}
2882 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
2883 self.flipBackToIndex(1); // $$$ really what we want?
2885 self.flipFwdToIndex();
2894 //______________________________________________________________________________
2895 // Stop autoplay mode, allowing animations to finish
2896 GnuBook.prototype.autoStop = function() {
2897 if (null != this.autoTimer) {
2898 clearInterval(this.autoTimer);
2899 this.flipSpeed = 'fast';
2900 $('#GBtoolbar .pause').hide();
2901 $('#GBtoolbar .play').show();
2902 this.autoTimer = null;
2906 // stopFlipAnimations
2907 //______________________________________________________________________________
2908 // Immediately stop flip animations. Callbacks are triggered.
2909 GnuBook.prototype.stopFlipAnimations = function() {
2911 this.autoStop(); // Clear timers
2913 // Stop animation, clear queue, trigger callbacks
2914 if (this.leafEdgeTmp) {
2915 $(this.leafEdgeTmp).stop(false, true);
2917 jQuery.each(this.prefetchedImgs, function() {
2918 $(this).stop(false, true);
2921 // And again since animations also queued in callbacks
2922 if (this.leafEdgeTmp) {
2923 $(this.leafEdgeTmp).stop(false, true);
2925 jQuery.each(this.prefetchedImgs, function() {
2926 $(this).stop(false, true);
2931 // keyboardNavigationIsDisabled(event)
2932 // - returns true if keyboard navigation should be disabled for the event
2933 //______________________________________________________________________________
2934 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2935 if (event.target.tagName == "INPUT") {
2941 // gutterOffsetForIndex
2942 //______________________________________________________________________________
2944 // Returns the gutter offset for the spread containing the given index.
2945 // This function supports RTL
2946 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2948 // To find the offset of the gutter from the middle we calculate our percentage distance
2949 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2950 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2952 // But then again for RTL it's the opposite
2953 if ('rl' == this.pageProgression) {
2961 //______________________________________________________________________________
2962 // Returns the width of the leaf edge div for the page with index given
2963 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2964 // $$$ could there be single pixel rounding errors for L vs R?
2965 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2966 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2968 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2972 // jumpIndexForLeftEdgePageX
2973 //______________________________________________________________________________
2974 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2975 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2976 if ('rl' != this.pageProgression) {
2977 // LTR - flipping backward
2978 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2980 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2981 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2985 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2986 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2991 // jumpIndexForRightEdgePageX
2992 //______________________________________________________________________________
2993 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2994 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2995 if ('rl' != this.pageProgression) {
2997 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2998 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
3001 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
3002 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
3007 GnuBook.prototype.initToolbar = function(mode, ui) {
3009 $("#GnuBook").append("<div id='GBtoolbar'>"
3010 + "<span id='GBtoolbarbuttons' style='float: right'>"
3011 + "<button class='GBicon print rollover' /> <button class='GBicon rollover embed' />"
3012 + "<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>"
3013 + "<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>"
3014 + "<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>"
3015 + "<button class='GBicon rollover thumbnail_mode' onclick='gb.switchMode(3); return false;'/>"
3016 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' />"
3020 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
3021 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
3022 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
3023 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span></span>"
3024 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
3025 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
3028 + "<span id='#GBbooktitle'>"
3029 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3033 this.updateToolbarZoom(this.reduce); // Pretty format
3035 if (ui == "embed") {
3036 $("#GnuBook a.logo").attr("target","_blank");
3039 // $$$ turn this into a member variable
3040 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
3042 // We build in mode 2
3045 this.bindToolbarNavHandlers(jToolbar);
3047 // Setup tooltips -- later we could load these from a file for i18n
3048 var titles = { '.logo': 'Go to Archive.org',
3049 '.zoom_in': 'Zoom in',
3050 '.zoom_out': 'Zoom out',
3051 '.one_page_mode': 'One-page view',
3052 '.two_page_mode': 'Two-page view',
3053 '.thumbnail_mode': 'Thumbnail view',
3054 '.print': 'Print this page',
3055 '.embed': 'Embed bookreader',
3056 '.book_left': 'Flip left',
3057 '.book_right': 'Flip right',
3058 '.book_up': 'Page up',
3059 '.book_down': 'Page down',
3062 '.book_top': 'First page',
3063 '.book_bottom': 'Last page'
3065 if ('rl' == this.pageProgression) {
3066 titles['.book_leftmost'] = 'Last page';
3067 titles['.book_rightmost'] = 'First page';
3069 titles['.book_leftmost'] = 'First page';
3070 titles['.book_rightmost'] = 'Last page';
3073 for (var icon in titles) {
3074 jToolbar.find(icon).attr('title', titles[icon]);
3077 // Hide mode buttons and autoplay if 2up is not available
3078 // $$$ if we end up with more than two modes we should show the applicable buttons
3079 if ( !this.canSwitchToMode(this.constMode2up) ) {
3080 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3083 // Switch to requested mode -- binds other click handlers
3084 this.switchToolbarMode(mode);
3089 // switchToolbarMode
3090 //______________________________________________________________________________
3091 // Update the toolbar for the given mode (changes navigation buttons)
3092 // $$$ we should soon split the toolbar out into its own module
3093 GnuBook.prototype.switchToolbarMode = function(mode) {
3096 $('#GBtoolbar .GBtoolbarmode2').hide();
3097 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
3100 $('#GBtoolbar .GBtoolbarmode1').hide();
3101 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
3105 // bindToolbarNavHandlers
3106 //______________________________________________________________________________
3107 // Binds the toolbar handlers
3108 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
3110 jToolbar.find('.book_left').bind('click', function(e) {
3115 jToolbar.find('.book_right').bind('click', function(e) {
3120 jToolbar.find('.book_up').bind('click', function(e) {
3125 jToolbar.find('.book_down').bind('click', function(e) {
3130 jToolbar.find('.print').bind('click', function(e) {
3135 jToolbar.find('.embed').bind('click', function(e) {
3140 jToolbar.find('.play').bind('click', function(e) {
3145 jToolbar.find('.pause').bind('click', function(e) {
3150 jToolbar.find('.book_top').bind('click', function(e) {
3155 jToolbar.find('.book_bottom').bind('click', function(e) {
3160 jToolbar.find('.book_leftmost').bind('click', function(e) {
3165 jToolbar.find('.book_rightmost').bind('click', function(e) {
3171 // updateToolbarZoom(reduce)
3172 //______________________________________________________________________________
3173 // Update the displayed zoom factor based on reduction factor
3174 GnuBook.prototype.updateToolbarZoom = function(reduce) {
3176 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3179 value = (100 / reduce).toFixed(2);
3180 // Strip trailing zeroes and decimal if all zeroes
3181 value = value.replace(/0+$/,'');
3182 value = value.replace(/\.$/,'');
3185 $('#GBzoom').text(value);
3188 // firstDisplayableIndex
3189 //______________________________________________________________________________
3190 // Returns the index of the first visible page, dependent on the mode.
3191 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3192 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3193 GnuBook.prototype.firstDisplayableIndex = function() {
3194 if (this.mode != this.constMode2up) {
3198 if ('rl' != this.pageProgression) {
3200 if (this.getPageSide(0) == 'L') {
3207 if (this.getPageSide(0) == 'R') {
3215 // lastDisplayableIndex
3216 //______________________________________________________________________________
3217 // Returns the index of the last visible page, dependent on the mode.
3218 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3219 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3220 GnuBook.prototype.lastDisplayableIndex = function() {
3222 var lastIndex = this.numLeafs - 1;
3224 if (this.mode != this.constMode2up) {
3228 if ('rl' != this.pageProgression) {
3230 if (this.getPageSide(lastIndex) == 'R') {
3233 return lastIndex + 1;
3237 if (this.getPageSide(lastIndex) == 'L') {
3240 return lastIndex + 1;
3245 // shortTitle(maximumCharacters)
3247 // Returns a shortened version of the title with the maximum number of characters
3248 GnuBook.prototype.shortTitle = function(maximumCharacters) {
3249 if (this.bookTitle.length < maximumCharacters) {
3250 return this.bookTitle;
3253 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3258 // Parameter related functions
3260 // updateFromParams(params)
3262 // Update ourselves from the params object.
3264 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3265 GnuBook.prototype.updateFromParams = function(params) {
3266 if ('undefined' != typeof(params.mode)) {
3267 this.switchMode(params.mode);
3271 if ('undefined' != typeof(params.searchTerm)) {
3272 if (this.searchTerm != params.searchTerm) {
3273 this.search(params.searchTerm);
3277 // $$$ process /zoom
3279 // We only respect page if index is not set
3280 if ('undefined' != typeof(params.index)) {
3281 if (params.index != this.currentIndex()) {
3282 this.jumpToIndex(params.index);
3284 } else if ('undefined' != typeof(params.page)) {
3285 // $$$ this assumes page numbers are unique
3286 if (params.page != this.getPageNum(this.currentIndex())) {
3287 this.jumpToPage(params.page);
3291 // $$$ process /region
3292 // $$$ process /highlight
3295 // paramsFromFragment(urlFragment)
3297 // Returns a object with configuration parametes from a URL fragment.
3299 // E.g paramsFromFragment(window.location.hash)
3300 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
3301 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3305 // For convenience we allow an initial # character (as from window.location.hash)
3306 // but don't require it
3307 if (urlFragment.substr(0,1) == '#') {
3308 urlFragment = urlFragment.substr(1);
3311 // Simple #nn syntax
3312 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3313 if ( !isNaN(oldStyleLeafNum) ) {
3314 params.index = oldStyleLeafNum;
3316 // Done processing if using old-style syntax
3320 // Split into key-value pairs
3321 var urlArray = urlFragment.split('/');
3323 for (var i = 0; i < urlArray.length; i += 2) {
3324 urlHash[urlArray[i]] = urlArray[i+1];
3328 if ('1up' == urlHash['mode']) {
3329 params.mode = this.constMode1up;
3330 } else if ('2up' == urlHash['mode']) {
3331 params.mode = this.constMode2up;
3332 } else if ('thumb' == urlHash['mode']) {
3333 params.mode = this.constModeThumb;
3337 if ('undefined' != typeof(urlHash['page'])) {
3338 // page was set -- may not be int
3339 params.page = urlHash['page'];
3342 // $$$ process /region
3343 // $$$ process /search
3345 if (urlHash['search'] != undefined) {
3346 params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3349 // $$$ process /highlight
3354 // paramsFromCurrent()
3356 // Create a params object from the current parameters.
3357 GnuBook.prototype.paramsFromCurrent = function() {
3361 var index = this.currentIndex();
3362 var pageNum = this.getPageNum(index);
3363 if ((pageNum === 0) || pageNum) {
3364 params.page = pageNum;
3367 params.index = index;
3368 params.mode = this.mode;
3374 if (this.searchHighlightVisible()) {
3375 params.searchTerm = this.searchTerm;
3381 // fragmentFromParams(params)
3383 // Create a fragment string from the params object.
3384 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3385 GnuBook.prototype.fragmentFromParams = function(params) {
3386 var separator = '/';
3390 if ('undefined' != typeof(params.page)) {
3391 fragments.push('page', params.page);
3393 // Don't have page numbering -- use index instead
3394 fragments.push('page', 'n' + params.index);
3401 if ('undefined' != typeof(params.mode)) {
3402 if (params.mode == this.constMode1up) {
3403 fragments.push('mode', '1up');
3404 } else if (params.mode == this.constMode2up) {
3405 fragments.push('mode', '2up');
3406 } else if (params.mode == this.constModeThumb) {
3407 fragments.push('mode', 'thumb');
3409 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3414 if (params.searchTerm) {
3415 fragments.push('search', params.searchTerm);
3418 return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3421 // getPageIndex(pageNum)
3423 // Returns the *highest* index the given page number, or undefined
3424 GnuBook.prototype.getPageIndex = function(pageNum) {
3425 var pageIndices = this.getPageIndices(pageNum);
3427 if (pageIndices.length > 0) {
3428 return pageIndices[pageIndices.length - 1];
3434 // getPageIndices(pageNum)
3436 // Returns an array (possibly empty) of the indices with the given page number
3437 GnuBook.prototype.getPageIndices = function(pageNum) {
3440 // Check for special "nXX" page number
3441 if (pageNum.slice(0,1) == 'n') {
3443 var pageIntStr = pageNum.slice(1, pageNum.length);
3444 var pageIndex = parseInt(pageIntStr);
3445 indices.push(pageIndex);
3448 // Do nothing... will run through page names and see if one matches
3453 for (i=0; i<this.numLeafs; i++) {
3454 if (this.getPageNum(i) == pageNum) {
3462 // getPageName(index)
3464 // Returns the name of the page as it should be displayed in the user interface
3465 GnuBook.prototype.getPageName = function(index) {
3466 return 'Page ' + this.getPageNum(index);
3469 // updateLocationHash
3471 // Update the location hash from the current parameters. Call this instead of manually
3472 // using window.location.replace
3473 GnuBook.prototype.updateLocationHash = function() {
3474 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3475 window.location.replace(newHash);
3477 // This is the variable checked in the timer. Only user-generated changes
3478 // to the URL will trigger the event.
3479 this.oldLocationHash = newHash;
3482 // startLocationPolling
3484 // Starts polling of window.location to see hash fragment changes
3485 GnuBook.prototype.startLocationPolling = function() {
3486 var self = this; // remember who I am
3487 self.oldLocationHash = window.location.hash;
3489 if (this.locationPollId) {
3490 clearInterval(this.locationPollID);
3491 this.locationPollId = null;
3494 this.locationPollId = setInterval(function() {
3495 var newHash = window.location.hash;
3496 if (newHash != self.oldLocationHash) {
3497 if (newHash != self.oldUserHash) { // Only process new user hash once
3498 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3500 // Queue change if animating
3501 if (self.animating) {
3503 self.animationFinishedCallback = function() {
3504 self.updateFromParams(self.paramsFromFragment(newHash));
3506 } else { // update immediately
3507 self.updateFromParams(self.paramsFromFragment(newHash));
3509 self.oldUserHash = newHash;
3517 // Returns true if we can switch to the requested mode
3518 GnuBook.prototype.canSwitchToMode = function(mode) {
3519 if (mode == this.constMode2up) {
3520 // check there are enough pages to display
3521 // $$$ this is a workaround for the mis-feature that we can't display
3522 // short books in 2up mode
3523 if (this.numLeafs < 6) {
3531 // searchHighlightVisible
3533 // Returns true if a search highlight is currently being displayed
3534 GnuBook.prototype.searchHighlightVisible = function() {
3535 if (this.constMode2up == this.mode) {
3536 if (this.searchResults[this.twoPage.currentIndexL]
3537 || this.searchResults[this.twoPage.currentIndexR]) {
3541 if (this.searchResults[this.currentIndex()]) {
3548 // getPageBackgroundColor
3550 // Returns a CSS property string for the background color for the given page
3551 // $$$ turn into regular CSS?
3552 GnuBook.prototype.getPageBackgroundColor = function(index) {
3553 if (index >= 0 && index < this.numLeafs) {
3555 return this.pageDefaultBackgroundColor;
3563 // Returns the page width for the given index, or first or last page if out of range
3564 GnuBook.prototype._getPageWidth = function(index) {
3565 // Synthesize a page width for pages not actually present in book.
3566 // May or may not be the best approach.
3567 // If index is out of range we return the width of first or last page
3568 index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3569 return this.getPageWidth(index);
3574 // Returns the page height for the given index, or first or last page if out of range
3575 GnuBook.prototype._getPageHeight= function(index) {
3576 index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3577 return this.getPageHeight(index);
3582 // Returns the page URI or transparent image if out of range
3583 GnuBook.prototype._getPageURI = function(index, reduce, rotate) {
3584 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3585 return this.imagesBaseURL + "/transparent.png";
3588 return this.getPageURI(index, reduce, rotate);
3591 // Library functions
3593 clamp: function(value, min, max) {
3594 return Math.min(Math.max(value, min), max);
3597 getIFrameDocument: function(iframe) {
3598 // Adapted from http://xkr.us/articles/dom/iframe-document/
3599 var outer = (iframe.contentWindow || iframe.contentDocument);
3600 return (outer.document || outer);
3603 decodeURIComponentPlus: function(value) {
3604 // Decodes a URI component and converts '+' to ' '
3605 return decodeURIComponent(value).replace(/\+/g, ' ');
3608 encodeURIComponentPlus: function(value) {
3609 // Encodes a URI component and converts ' ' to '+'
3610 return encodeURIComponent(value).replace(/%20/g, '+');
3612 // The final property here must NOT have a comma after it - IE7