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
44 this.thumbRowBuffer = 4; // number of rows to pre-cache out a view
46 this.displayedIndices = [];
47 this.displayedRows=[];
48 //this.indicesToDisplay = [];
50 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
53 this.animating = false;
55 this.autoTimer = null;
56 this.flipSpeed = 'fast';
58 this.twoPagePopUp = null;
59 this.leafEdgeTmp = null;
60 this.embedPopup = null;
61 this.printPopup = null;
64 this.searchResults = {};
66 this.firstIndex = null;
68 this.lastDisplayableIndex2up = null;
70 // We link to index.php to avoid redirect which breaks back button
71 this.logoURL = 'http://www.archive.org/index.php';
73 // Base URL for images
74 this.imagesBaseURL = '/bookreader/images/';
77 this.constMode1up = 1;
78 this.constMode2up = 2;
79 this.constModeThumb = 3;
82 this.reductionFactors = [0.5, 1, 2, 4, 8, 16];
84 // Object to hold parameters related to 2up mode
86 coverInternalPadding: 10, // Width of cover
87 coverExternalPadding: 10, // Padding outside of cover
88 bookSpineDivWidth: 30, // Width of book spine $$$ consider sizing based on book length
92 // Background color for pages (e.g. when loading page image)
93 // $$$ TODO dynamically calculate based on page images
94 this.pageDefaultBackgroundColor = 'rgb(234, 226, 205)';
98 //______________________________________________________________________________
99 GnuBook.prototype.init = function() {
101 var startIndex = undefined;
102 this.pageScale = this.reduce; // preserve current reduce
104 // Find start index and mode if set in location hash
105 var params = this.paramsFromFragment(window.location.hash);
107 if ('undefined' != typeof(params.index)) {
108 startIndex = params.index;
109 } else if ('undefined' != typeof(params.page)) {
110 startIndex = this.getPageIndex(params.page);
113 if ('undefined' == typeof(startIndex)) {
114 if ('undefined' != typeof(this.titleLeaf)) {
115 startIndex = this.leafNumToIndex(this.titleLeaf);
119 if ('undefined' == typeof(startIndex)) {
123 if ('undefined' != typeof(params.mode)) {
124 this.mode = params.mode;
127 // Set document title -- may have already been set in enclosing html for
128 // search engine visibility
129 document.title = this.shortTitle(50);
131 // Sanitize parameters
132 if ( !this.canSwitchToMode( this.mode ) ) {
133 this.mode = this.constMode1up;
136 $("#GnuBook").empty();
137 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
138 $("#GnuBook").append("<div id='GBcontainer'></div>");
139 $("#GBcontainer").append("<div id='GBpageview'></div>");
141 $("#GBcontainer").bind('scroll', this, function(e) {
145 this.setupKeyListeners();
146 this.startLocationPolling();
148 $(window).bind('resize', this, function(e) {
149 //console.log('resize!');
150 if (1 == e.data.mode) {
151 //console.log('centering 1page view');
152 e.data.centerPageView();
153 $('#GBpageview').empty()
154 e.data.displayedIndices = [];
155 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
157 } else if (3 == e.data.mode){
158 e.data.prepareThumbnailView();
160 //console.log('drawing 2 page view');
162 // We only need to prepare again in autofit (size of spread changes)
163 if (e.data.twoPage.autofit) {
164 e.data.prepareTwoPageView();
166 // Re-center if the scrollbars have disappeared
167 var center = e.data.twoPageGetViewCenter();
168 var doRecenter = false;
169 if (e.data.twoPage.totalWidth < $('#GBcontainer').attr('clientWidth')) {
170 center.percentageX = 0.5;
173 if (e.data.twoPage.totalHeight < $('#GBcontainer').attr('clientHeight')) {
174 center.percentageY = 0.5;
178 e.data.twoPageCenterView(center.percentageX, center.percentageY);
184 $('.GBpagediv1up').bind('mousedown', this, function(e) {
185 // $$$ the purpose of this is to disable selection of the image (makes it turn blue)
186 // but this also interferes with right-click. See https://bugs.edge.launchpad.net/gnubook/+bug/362626
189 if (1 == this.mode) {
190 this.resizePageView();
191 this.firstIndex = startIndex;
192 this.jumpToIndex(startIndex);
193 } else if (3 == this.mode) {
194 this.firstIndex = startIndex;
195 this.prepareThumbnailView();
196 this.jumpToIndex(startIndex);
198 //this.resizePageView();
200 this.displayedIndices=[0];
201 this.firstIndex = startIndex;
202 this.displayedIndices = [this.firstIndex];
203 //console.log('titleLeaf: %d', this.titleLeaf);
204 //console.log('displayedIndices: %s', this.displayedIndices);
205 this.prepareTwoPageView();
208 // Enact other parts of initial params
209 this.updateFromParams(params);
212 GnuBook.prototype.setupKeyListeners = function() {
225 // We use document here instead of window to avoid a bug in jQuery on IE7
226 $(document).keydown(function(e) {
228 // Keyboard navigation
229 if (!self.keyboardNavigationIsDisabled(e)) {
233 // In 1up mode page scrolling is handled by browser
234 if (2 == self.mode) {
241 if (2 == self.mode) {
255 if (2 == self.mode) {
261 if (2 == self.mode) {
272 //______________________________________________________________________________
273 GnuBook.prototype.drawLeafs = function() {
274 if (1 == this.mode) {
275 this.drawLeafsOnePage();
276 } else if(3 == this.mode) {
277 this.drawLeafsThumbnail();
279 this.drawLeafsTwoPage();
284 //______________________________________________________________________________
285 GnuBook.prototype.setDragHandler = function(div) {
286 div.dragging = false;
288 $(div).unbind('mousedown').bind('mousedown', function(e) {
291 //console.log('mousedown at ' + e.pageY);
293 this.dragging = true;
294 this.prevMouseX = e.pageX;
295 this.prevMouseY = e.pageY;
297 var startX = e.pageX;
298 var startY = e.pageY;
299 var startTop = $('#GBcontainer').attr('scrollTop');
300 var startLeft = $('#GBcontainer').attr('scrollLeft');
304 $(div).unbind('mousemove').bind('mousemove', function(ee) {
307 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
309 var offsetX = ee.pageX - this.prevMouseX;
310 var offsetY = ee.pageY - this.prevMouseY;
313 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
314 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
317 this.prevMouseX = ee.pageX;
318 this.prevMouseY = ee.pageY;
322 $(div).unbind('mouseup').bind('mouseup', function(ee) {
324 //console.log('mouseup');
326 this.dragging = false;
329 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
331 //console.log('mouseleave');
333 this.dragging = false;
336 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
338 //console.log('mouseenter');
340 this.dragging = false;
344 // setDragHandler2UP()
345 //______________________________________________________________________________
346 GnuBook.prototype.setDragHandler2UP = function(div) {
347 div.dragging = false;
349 $(div).unbind('mousedown').bind('mousedown', function(e) {
352 //console.log('mousedown at ' + e.pageY);
354 this.dragStart = {x: e.pageX, y: e.pageY };
355 this.mouseDown = true;
356 this.dragging = false; // wait until drag distance
357 this.prevMouseX = e.pageX;
358 this.prevMouseY = e.pageY;
360 var startX = e.pageX;
361 var startY = e.pageY;
362 var startTop = $('#GBcontainer').attr('scrollTop');
363 var startLeft = $('#GBcontainer').attr('scrollLeft');
367 $(div).unbind('mousemove').bind('mousemove', function(ee) {
370 // console.log('mousemove ' + ee.pageX + ',' + ee.pageY);
372 var offsetX = ee.pageX - this.prevMouseX;
373 var offsetY = ee.pageY - this.prevMouseY;
375 var minDragDistance = 5; // $$$ constant
377 var distance = Math.max(Math.abs(offsetX), Math.abs(offsetY));
379 if (this.mouseDown && (distance > minDragDistance)) {
380 //console.log('drag start!');
382 this.dragging = true;
386 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
387 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
388 this.prevMouseX = ee.pageX;
389 this.prevMouseY = ee.pageY;
396 $(div).unbind('mouseup').bind('mouseup', function(ee) {
398 //console.log('mouseup');
400 this.dragging = false;
401 this.mouseDown = false;
406 $(div).unbind('mouseleave').bind('mouseleave', function(e) {
408 //console.log('mouseleave');
410 this.dragging = false;
411 this.mouseDown = false;
414 $(div).unbind('mouseenter').bind('mouseenter', function(e) {
416 //console.log('mouseenter');
418 this.dragging = false;
419 this.mouseDown = false;
423 GnuBook.prototype.setClickHandler2UP = function( element, data, handler) {
424 //console.log('setting handler');
425 //console.log(element.tagName);
427 $(element).unbind('click').bind('click', data, function(e) {
430 //console.log('click!');
432 if (this.mouseDown && (!this.dragging)) {
433 //console.log('click not dragging!');
437 this.dragging = false;
438 this.mouseDown = false;
442 // drawLeafsOnePage()
443 //______________________________________________________________________________
444 GnuBook.prototype.drawLeafsOnePage = function() {
445 //alert('drawing leafs!');
449 var scrollTop = $('#GBcontainer').attr('scrollTop');
450 var scrollBottom = scrollTop + $('#GBcontainer').height();
451 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
453 var indicesToDisplay = [];
458 for (i=0; i<this.numLeafs; i++) {
459 var height = parseInt(this._getPageHeight(i)/this.reduce);
461 leafBottom += height;
462 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
463 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
464 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
465 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
466 if (topInView | bottomInView | middleInView) {
467 //console.log('displayed: ' + this.displayedIndices);
468 //console.log('to display: ' + i);
469 indicesToDisplay.push(i);
471 leafTop += height +10;
475 var firstIndexToDraw = indicesToDisplay[0];
476 this.firstIndex = firstIndexToDraw;
478 // Update hash, but only if we're currently displaying a leaf
479 // Hack that fixes #365790
480 if (this.displayedIndices.length > 0) {
481 this.updateLocationHash();
484 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
486 indicesToDisplay.unshift(firstIndexToDraw);
489 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
490 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
491 indicesToDisplay.push(lastIndexToDraw+1);
496 for (i=0; i<firstIndexToDraw; i++) {
497 leafTop += parseInt(this._getPageHeight(i)/this.reduce) +10;
500 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
501 var viewWidth = $('#GBcontainer').attr('scrollWidth');
504 for (i=0; i<indicesToDisplay.length; i++) {
505 var index = indicesToDisplay[i];
506 var height = parseInt(this._getPageHeight(index)/this.reduce);
508 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
509 var width = parseInt(this._getPageWidth(index)/this.reduce);
510 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
511 var div = document.createElement("div");
512 div.className = 'GBpagediv1up';
513 div.id = 'pagediv'+index;
514 div.style.position = "absolute";
515 $(div).css('top', leafTop + 'px');
516 var left = (viewWidth-width)>>1;
517 if (left<0) left = 0;
518 $(div).css('left', left+'px');
519 $(div).css('width', width+'px');
520 $(div).css('height', height+'px');
521 //$(div).text('loading...');
523 this.setDragHandler(div);
525 $('#GBpageview').append(div);
527 var img = document.createElement("img");
528 img.src = this._getPageURI(index, this.reduce, 0);
529 $(img).css('width', width+'px');
530 $(img).css('height', height+'px');
534 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
537 leafTop += height +10;
541 for (i=0; i<this.displayedIndices.length; i++) {
542 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
543 var index = this.displayedIndices[i];
544 //console.log('Removing leaf ' + index);
545 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
546 $('#pagediv'+index).remove();
548 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
552 this.displayedIndices = indicesToDisplay.slice();
553 this.updateSearchHilites();
555 if (null != this.getPageNum(firstIndexToDraw)) {
556 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
558 $("#GBpagenum").val('');
561 this.updateToolbarZoom(this.reduce);
565 // drawLeafsThumbnail()
566 //______________________________________________________________________________
567 GnuBook.prototype.drawLeafsThumbnail = function() {
568 //alert('drawing leafs!');
571 var viewWidth = $('#GBcontainer').attr('scrollWidth') - 20; // width minus buffer
573 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
585 for (i=0; i<this.numLeafs; i++) {
586 leafWidth = parseInt(this.getPageWidth(i)/this.reduce, 10);
587 if (rightPos + (leafWidth + this.padding) > viewWidth){
593 if (leafMap[currentRow]===undefined) { leafMap[currentRow] = {}; }
594 if (leafMap[currentRow].leafs===undefined) {
595 leafMap[currentRow].leafs = [];
596 leafMap[currentRow].height = 0;
597 leafMap[currentRow].top = 0;
599 leafMap[currentRow].leafs[leafIndex] = {};
600 leafMap[currentRow].leafs[leafIndex].num = i;
601 leafMap[currentRow].leafs[leafIndex].left = rightPos;
603 leafHeight = parseInt(this.getPageHeight(leafMap[currentRow].leafs[leafIndex].num)/this.reduce, 10);
604 if (leafHeight > leafMap[currentRow].height) { leafMap[currentRow].height = leafHeight; }
605 if (leafIndex===0) { bottomPos += this.padding + leafMap[currentRow].height; }
606 rightPos += leafWidth + this.padding;
607 if (rightPos > maxRight) { maxRight = rightPos; }
611 // reset the bottom position based on thumbnails
612 $('#GBpageview').height(bottomPos);
614 var pageViewBuffer = Math.floor(($('#GBcontainer').attr('scrollWidth') - maxRight) / 2) - 14;
615 var scrollTop = $('#GBcontainer').attr('scrollTop');
616 var scrollBottom = scrollTop + $('#GBcontainer').height();
620 var rowsToDisplay = [];
622 for (i=0; i<leafMap.length; i++) {
623 leafBottom += this.padding + leafMap[i].height;
624 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
625 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
626 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
627 if (topInView | bottomInView | middleInView) {
628 //console.log('row to display: ' + j);
629 rowsToDisplay.push(i);
631 if(leafTop > leafMap[i].top) { leafMap[i].top = leafTop; }
632 leafTop = leafBottom;
635 var firstRow = rowsToDisplay[0];
636 var lastRow = rowsToDisplay[rowsToDisplay.length-1];
637 for (i=1; i<this.thumbRowBuffer+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 + "<div class='GBtoolbarmode3' style='display: none'><button class='GBicon rollover book_top' /><button class='GBicon rollover book_thumb_prev' /> <button class='GBicon rollover book_thumb_next' /><button class='GBicon rollover book_bottom' /></div>"
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 + "<div class='GBtoolbarzoom' style='display: none'><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></div>"
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;'/>"
3026 + " <button class='GBicon rollover thumbnail_mode' onclick='gb.switchMode(3); return false;'/>"
3029 + "<span id='#GBbooktitle'>"
3030 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.bookTitle+"</a>"
3034 this.updateToolbarZoom(this.reduce); // Pretty format
3036 if (ui == "embed") {
3037 $("#GnuBook a.logo").attr("target","_blank");
3040 // $$$ turn this into a member variable
3041 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
3043 // We build in mode 2
3046 this.bindToolbarNavHandlers(jToolbar);
3048 // Setup tooltips -- later we could load these from a file for i18n
3049 var titles = { '.logo': 'Go to Archive.org',
3050 '.zoom_in': 'Zoom in',
3051 '.zoom_out': 'Zoom out',
3052 '.one_page_mode': 'One-page view',
3053 '.two_page_mode': 'Two-page view',
3054 '.thumbnail_mode': 'Thumbnail view',
3055 '.print': 'Print this page',
3056 '.embed': 'Embed bookreader',
3057 '.book_left': 'Flip left',
3058 '.book_right': 'Flip right',
3059 '.book_up': 'Page up',
3060 '.book_down': 'Page down',
3063 '.book_top': 'First page',
3064 '.book_bottom': 'Last page',
3065 '.book_thumb_next': 'Next',
3066 '.book_thumb_prev': 'Previous'
3068 if ('rl' == this.pageProgression) {
3069 titles['.book_leftmost'] = 'Last page';
3070 titles['.book_rightmost'] = 'First page';
3072 titles['.book_leftmost'] = 'First page';
3073 titles['.book_rightmost'] = 'Last page';
3076 for (var icon in titles) {
3077 jToolbar.find(icon).attr('title', titles[icon]);
3080 // Hide mode buttons and autoplay if 2up is not available
3081 // $$$ if we end up with more than two modes we should show the applicable buttons
3082 if ( !this.canSwitchToMode(this.constMode2up) ) {
3083 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
3086 // Switch to requested mode -- binds other click handlers
3087 this.switchToolbarMode(mode);
3092 // switchToolbarMode
3093 //______________________________________________________________________________
3094 // Update the toolbar for the given mode (changes navigation buttons)
3095 // $$$ we should soon split the toolbar out into its own module
3096 GnuBook.prototype.switchToolbarMode = function(mode) {
3100 $('#GBtoolbar .GBtoolbarzoom').show().css('display', 'inline');
3101 $('#GBtoolbar .GBtoolbarmode2').hide();
3102 $('#GBtoolbar .GBtoolbarmode3').hide();
3103 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
3104 } else if (2 == mode) {
3106 $('#GBtoolbar .GBtoolbarzoom').show().css('display', 'inline');
3107 $('#GBtoolbar .GBtoolbarmode1').hide();
3108 $('#GBtoolbar .GBtoolbarmode3').hide();
3109 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
3112 $('#GBtoolbar .GBtoolbarzoom').hide();
3113 $('#GBtoolbar .GBtoolbarmode2').hide();
3114 $('#GBtoolbar .GBtoolbarmode1').hide();
3115 $('#GBtoolbar .GBtoolbarmode3').show().css('display', 'inline');
3119 // bindToolbarNavHandlers
3120 //______________________________________________________________________________
3121 // Binds the toolbar handlers
3122 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
3124 jToolbar.find('.book_left').bind('click', function(e) {
3129 jToolbar.find('.book_right').bind('click', function(e) {
3134 jToolbar.find('.book_up').bind('click', function(e) {
3139 jToolbar.find('.book_down').bind('click', function(e) {
3144 jToolbar.find('.print').bind('click', function(e) {
3149 jToolbar.find('.embed').bind('click', function(e) {
3154 jToolbar.find('.play').bind('click', function(e) {
3159 jToolbar.find('.pause').bind('click', function(e) {
3164 jToolbar.find('.book_top').bind('click', function(e) {
3169 jToolbar.find('.book_bottom').bind('click', function(e) {
3174 jToolbar.find('.book_leftmost').bind('click', function(e) {
3179 jToolbar.find('.book_rightmost').bind('click', function(e) {
3184 jToolbar.find('.book_thumb_prev').bind('click', function(e) {
3189 jToolbar.find('.book_thumb_next').bind('click', function(e) {
3195 // updateToolbarZoom(reduce)
3196 //______________________________________________________________________________
3197 // Update the displayed zoom factor based on reduction factor
3198 GnuBook.prototype.updateToolbarZoom = function(reduce) {
3200 if (this.constMode2up == this.mode && this.twoPage.autofit) {
3203 value = (100 / reduce).toFixed(2);
3204 // Strip trailing zeroes and decimal if all zeroes
3205 value = value.replace(/0+$/,'');
3206 value = value.replace(/\.$/,'');
3209 $('#GBzoom').text(value);
3212 // firstDisplayableIndex
3213 //______________________________________________________________________________
3214 // Returns the index of the first visible page, dependent on the mode.
3215 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3216 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
3217 GnuBook.prototype.firstDisplayableIndex = function() {
3218 if (this.mode != this.constMode2up) {
3222 if ('rl' != this.pageProgression) {
3224 if (this.getPageSide(0) == 'L') {
3231 if (this.getPageSide(0) == 'R') {
3239 // lastDisplayableIndex
3240 //______________________________________________________________________________
3241 // Returns the index of the last visible page, dependent on the mode.
3242 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
3243 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
3244 GnuBook.prototype.lastDisplayableIndex = function() {
3246 var lastIndex = this.numLeafs - 1;
3248 if (this.mode != this.constMode2up) {
3252 if ('rl' != this.pageProgression) {
3254 if (this.getPageSide(lastIndex) == 'R') {
3257 return lastIndex + 1;
3261 if (this.getPageSide(lastIndex) == 'L') {
3264 return lastIndex + 1;
3269 // shortTitle(maximumCharacters)
3271 // Returns a shortened version of the title with the maximum number of characters
3272 GnuBook.prototype.shortTitle = function(maximumCharacters) {
3273 if (this.bookTitle.length < maximumCharacters) {
3274 return this.bookTitle;
3277 var title = this.bookTitle.substr(0, maximumCharacters - 3);
3282 // Parameter related functions
3284 // updateFromParams(params)
3286 // Update ourselves from the params object.
3288 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
3289 GnuBook.prototype.updateFromParams = function(params) {
3290 if ('undefined' != typeof(params.mode)) {
3291 this.switchMode(params.mode);
3295 if ('undefined' != typeof(params.searchTerm)) {
3296 if (this.searchTerm != params.searchTerm) {
3297 this.search(params.searchTerm);
3301 // $$$ process /zoom
3303 // We only respect page if index is not set
3304 if ('undefined' != typeof(params.index)) {
3305 if (params.index != this.currentIndex()) {
3306 this.jumpToIndex(params.index);
3308 } else if ('undefined' != typeof(params.page)) {
3309 // $$$ this assumes page numbers are unique
3310 if (params.page != this.getPageNum(this.currentIndex())) {
3311 this.jumpToPage(params.page);
3315 // $$$ process /region
3316 // $$$ process /highlight
3319 // paramsFromFragment(urlFragment)
3321 // Returns a object with configuration parametes from a URL fragment.
3323 // E.g paramsFromFragment(window.location.hash)
3324 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
3325 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
3329 // For convenience we allow an initial # character (as from window.location.hash)
3330 // but don't require it
3331 if (urlFragment.substr(0,1) == '#') {
3332 urlFragment = urlFragment.substr(1);
3335 // Simple #nn syntax
3336 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
3337 if ( !isNaN(oldStyleLeafNum) ) {
3338 params.index = oldStyleLeafNum;
3340 // Done processing if using old-style syntax
3344 // Split into key-value pairs
3345 var urlArray = urlFragment.split('/');
3347 for (var i = 0; i < urlArray.length; i += 2) {
3348 urlHash[urlArray[i]] = urlArray[i+1];
3352 if ('1up' == urlHash['mode']) {
3353 params.mode = this.constMode1up;
3354 } else if ('2up' == urlHash['mode']) {
3355 params.mode = this.constMode2up;
3356 } else if ('thumb' == urlHash['mode']) {
3357 params.mode = this.constModeThumb;
3361 if ('undefined' != typeof(urlHash['page'])) {
3362 // page was set -- may not be int
3363 params.page = urlHash['page'];
3366 // $$$ process /region
3367 // $$$ process /search
3369 if (urlHash['search'] != undefined) {
3370 params.searchTerm = GnuBook.util.decodeURIComponentPlus(urlHash['search']);
3373 // $$$ process /highlight
3378 // paramsFromCurrent()
3380 // Create a params object from the current parameters.
3381 GnuBook.prototype.paramsFromCurrent = function() {
3385 var index = this.currentIndex();
3386 var pageNum = this.getPageNum(index);
3387 if ((pageNum === 0) || pageNum) {
3388 params.page = pageNum;
3391 params.index = index;
3392 params.mode = this.mode;
3398 if (this.searchHighlightVisible()) {
3399 params.searchTerm = this.searchTerm;
3405 // fragmentFromParams(params)
3407 // Create a fragment string from the params object.
3408 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
3409 GnuBook.prototype.fragmentFromParams = function(params) {
3410 var separator = '/';
3414 if ('undefined' != typeof(params.page)) {
3415 fragments.push('page', params.page);
3417 // Don't have page numbering -- use index instead
3418 fragments.push('page', 'n' + params.index);
3425 if ('undefined' != typeof(params.mode)) {
3426 if (params.mode == this.constMode1up) {
3427 fragments.push('mode', '1up');
3428 } else if (params.mode == this.constMode2up) {
3429 fragments.push('mode', '2up');
3430 } else if (params.mode == this.constModeThumb) {
3431 fragments.push('mode', 'thumb');
3433 throw 'fragmentFromParams called with unknown mode ' + params.mode;
3438 if (params.searchTerm) {
3439 fragments.push('search', params.searchTerm);
3442 return GnuBook.util.encodeURIComponentPlus(fragments.join(separator)).replace(/%2F/g, '/');
3445 // getPageIndex(pageNum)
3447 // Returns the *highest* index the given page number, or undefined
3448 GnuBook.prototype.getPageIndex = function(pageNum) {
3449 var pageIndices = this.getPageIndices(pageNum);
3451 if (pageIndices.length > 0) {
3452 return pageIndices[pageIndices.length - 1];
3458 // getPageIndices(pageNum)
3460 // Returns an array (possibly empty) of the indices with the given page number
3461 GnuBook.prototype.getPageIndices = function(pageNum) {
3464 // Check for special "nXX" page number
3465 if (pageNum.slice(0,1) == 'n') {
3467 var pageIntStr = pageNum.slice(1, pageNum.length);
3468 var pageIndex = parseInt(pageIntStr);
3469 indices.push(pageIndex);
3472 // Do nothing... will run through page names and see if one matches
3477 for (i=0; i<this.numLeafs; i++) {
3478 if (this.getPageNum(i) == pageNum) {
3486 // getPageName(index)
3488 // Returns the name of the page as it should be displayed in the user interface
3489 GnuBook.prototype.getPageName = function(index) {
3490 return 'Page ' + this.getPageNum(index);
3493 // updateLocationHash
3495 // Update the location hash from the current parameters. Call this instead of manually
3496 // using window.location.replace
3497 GnuBook.prototype.updateLocationHash = function() {
3498 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
3499 window.location.replace(newHash);
3501 // This is the variable checked in the timer. Only user-generated changes
3502 // to the URL will trigger the event.
3503 this.oldLocationHash = newHash;
3506 // startLocationPolling
3508 // Starts polling of window.location to see hash fragment changes
3509 GnuBook.prototype.startLocationPolling = function() {
3510 var self = this; // remember who I am
3511 self.oldLocationHash = window.location.hash;
3513 if (this.locationPollId) {
3514 clearInterval(this.locationPollID);
3515 this.locationPollId = null;
3518 this.locationPollId = setInterval(function() {
3519 var newHash = window.location.hash;
3520 if (newHash != self.oldLocationHash) {
3521 if (newHash != self.oldUserHash) { // Only process new user hash once
3522 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
3524 // Queue change if animating
3525 if (self.animating) {
3527 self.animationFinishedCallback = function() {
3528 self.updateFromParams(self.paramsFromFragment(newHash));
3530 } else { // update immediately
3531 self.updateFromParams(self.paramsFromFragment(newHash));
3533 self.oldUserHash = newHash;
3541 // Returns true if we can switch to the requested mode
3542 GnuBook.prototype.canSwitchToMode = function(mode) {
3543 if (mode == this.constMode2up) {
3544 // check there are enough pages to display
3545 // $$$ this is a workaround for the mis-feature that we can't display
3546 // short books in 2up mode
3547 if (this.numLeafs < 6) {
3555 // searchHighlightVisible
3557 // Returns true if a search highlight is currently being displayed
3558 GnuBook.prototype.searchHighlightVisible = function() {
3559 if (this.constMode2up == this.mode) {
3560 if (this.searchResults[this.twoPage.currentIndexL]
3561 || this.searchResults[this.twoPage.currentIndexR]) {
3565 if (this.searchResults[this.currentIndex()]) {
3572 // getPageBackgroundColor
3574 // Returns a CSS property string for the background color for the given page
3575 // $$$ turn into regular CSS?
3576 GnuBook.prototype.getPageBackgroundColor = function(index) {
3577 if (index >= 0 && index < this.numLeafs) {
3579 return this.pageDefaultBackgroundColor;
3587 // Returns the page width for the given index, or first or last page if out of range
3588 GnuBook.prototype._getPageWidth = function(index) {
3589 // Synthesize a page width for pages not actually present in book.
3590 // May or may not be the best approach.
3591 // If index is out of range we return the width of first or last page
3592 index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3593 return this.getPageWidth(index);
3598 // Returns the page height for the given index, or first or last page if out of range
3599 GnuBook.prototype._getPageHeight= function(index) {
3600 index = GnuBook.util.clamp(index, 0, this.numLeafs - 1);
3601 return this.getPageHeight(index);
3606 // Returns the page URI or transparent image if out of range
3607 GnuBook.prototype._getPageURI = function(index, reduce, rotate) {
3608 if (index < 0 || index >= this.numLeafs) { // Synthesize page
3609 return this.imagesBaseURL + "/transparent.png";
3612 return this.getPageURI(index, reduce, rotate);
3615 // Library functions
3617 clamp: function(value, min, max) {
3618 return Math.min(Math.max(value, min), max);
3621 getIFrameDocument: function(iframe) {
3622 // Adapted from http://xkr.us/articles/dom/iframe-document/
3623 var outer = (iframe.contentWindow || iframe.contentDocument);
3624 return (outer.document || outer);
3627 decodeURIComponentPlus: function(value) {
3628 // Decodes a URI component and converts '+' to ' '
3629 return decodeURIComponent(value).replace(/\+/g, ' ');
3632 encodeURIComponentPlus: function(value) {
3633 // Encodes a URI component and converts ' ' to '+'
3634 return encodeURIComponent(value).replace(/%20/g, '+');
3636 // The final property here must NOT have a comma after it - IE7