2 Copyright(c)2008-2009 Internet Archive. Software license AGPL version 3.
4 This file is part of GnuBook.
6 GnuBook is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Affero General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 GnuBook is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Affero General Public License for more details.
16 You should have received a copy of the GNU Affero General Public License
17 along with GnuBook. If not, see <http://www.gnu.org/licenses/>.
19 The GnuBook source is hosted at http://github.com/openlibrary/bookreader/
21 archive.org cvs $Revision: 1.2 $ $Date: 2009-06-22 18:42:51 $
25 //______________________________________________________________________________
26 // After you instantiate this object, you must supply the following
27 // book-specific functions, before calling init():
31 // You must also add a numLeafs property before calling init().
36 this.mode = 1; //1 or 2
37 this.ui = 'full'; // UI mode
39 this.displayedIndices = [];
40 //this.indicesToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
45 this.animating = false;
47 this.autoTimer = null;
48 this.flipSpeed = 'fast';
50 this.twoPagePopUp = null;
51 this.leafEdgeTmp = null;
52 this.embedPopup = null;
54 this.searchResults = {};
56 this.firstIndex = null;
58 this.lastDisplayableIndex2up = null;
60 // We link to index.php to avoid redirect which breaks back button
61 this.logoURL = 'http://www.archive.org/index.php';
63 // Base URL for images
64 this.imagesBaseURL = '/bookreader/images/';
67 this.constMode1up = 1;
68 this.constMode2up = 2;
73 //______________________________________________________________________________
74 GnuBook.prototype.init = function() {
76 var startIndex = undefined;
78 // Find start index and mode if set in location hash
79 var params = this.paramsFromFragment(window.location.hash);
81 if ('undefined' != typeof(params.index)) {
82 startIndex = params.index;
83 } else if ('undefined' != typeof(params.page)) {
84 startIndex = this.getPageIndex(params.page);
87 if ('undefined' == typeof(startIndex)) {
88 if ('undefined' != typeof(this.titleLeaf)) {
89 startIndex = this.leafNumToIndex(this.titleLeaf);
93 if ('undefined' == typeof(startIndex)) {
97 if ('undefined' != typeof(params.mode)) {
98 this.mode = params.mode;
101 // Set document title -- may have already been set in enclosing html for
102 // search engine visibility
103 document.title = this.shortTitle(50);
105 // Sanitize parameters
106 if ( !this.canSwitchToMode( this.mode ) ) {
107 this.mode = this.constMode1up;
110 $("#GnuBook").empty();
111 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
112 $("#GnuBook").append("<div id='GBcontainer'></div>");
113 $("#GBcontainer").append("<div id='GBpageview'></div>");
115 $("#GBcontainer").bind('scroll', this, function(e) {
119 this.setupKeyListeners();
120 this.startLocationPolling();
122 $(window).bind('resize', this, function(e) {
123 //console.log('resize!');
124 if (1 == e.data.mode) {
125 //console.log('centering 1page view');
126 e.data.centerPageView();
127 $('#GBpageview').empty()
128 e.data.displayedIndices = [];
129 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
132 //console.log('drawing 2 page view');
133 e.data.prepareTwoPageView();
137 $('.GBpagediv1up').bind('mousedown', this, function(e) {
138 //console.log('mousedown!');
141 if (1 == this.mode) {
142 this.resizePageView();
143 this.firstIndex = startIndex;
144 this.jumpToIndex(startIndex);
146 //this.resizePageView();
148 this.displayedIndices=[0];
149 this.firstIndex = startIndex;
150 this.displayedIndices = [this.firstIndex];
151 //console.log('titleLeaf: %d', this.titleLeaf);
152 //console.log('displayedIndices: %s', this.displayedIndices);
153 this.prepareTwoPageView();
154 //if (this.auto) this.nextPage();
157 // Enact other parts of initial params
158 this.updateFromParams(params);
161 GnuBook.prototype.setupKeyListeners = function() {
174 // We use document here instead of window to avoid a bug in jQuery on IE7
175 $(document).keydown(function(e) {
177 // Keyboard navigation
181 // In 1up mode page scrolling is handled by browser
182 if (2 == self.mode) {
188 if (2 == self.mode) {
199 if (self.keyboardNavigationIsDisabled(e)) {
202 if (2 == self.mode) {
207 if (self.keyboardNavigationIsDisabled(e)) {
210 if (2 == self.mode) {
219 //______________________________________________________________________________
220 GnuBook.prototype.drawLeafs = function() {
221 if (1 == this.mode) {
222 this.drawLeafsOnePage();
224 this.drawLeafsTwoPage();
228 // setDragHandler1up()
229 //______________________________________________________________________________
230 GnuBook.prototype.setDragHandler1up = function(div) {
231 div.dragging = false;
233 $(div).bind('mousedown', function(e) {
234 //console.log('mousedown at ' + e.pageY);
236 this.dragging = true;
237 this.prevMouseX = e.pageX;
238 this.prevMouseY = e.pageY;
240 var startX = e.pageX;
241 var startY = e.pageY;
242 var startTop = $('#GBcontainer').attr('scrollTop');
243 var startLeft = $('#GBcontainer').attr('scrollLeft');
248 $(div).bind('mousemove', function(ee) {
249 //console.log('mousemove ' + startY);
251 var offsetX = ee.pageX - this.prevMouseX;
252 var offsetY = ee.pageY - this.prevMouseY;
255 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
256 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
259 this.prevMouseX = ee.pageX;
260 this.prevMouseY = ee.pageY;
265 $(div).bind('mouseup', function(ee) {
266 //console.log('mouseup');
268 this.dragging = false;
272 $(div).bind('mouseleave', function(e) {
273 //console.log('mouseleave');
275 //$(this).unbind('mousemove mouseup');
276 this.dragging = false;
281 // drawLeafsOnePage()
282 //______________________________________________________________________________
283 GnuBook.prototype.drawLeafsOnePage = function() {
284 //alert('drawing leafs!');
288 var scrollTop = $('#GBcontainer').attr('scrollTop');
289 var scrollBottom = scrollTop + $('#GBcontainer').height();
290 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
292 var indicesToDisplay = [];
297 for (i=0; i<this.numLeafs; i++) {
298 var height = parseInt(this.getPageHeight(i)/this.reduce);
300 leafBottom += height;
301 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
302 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
303 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
304 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
305 if (topInView | bottomInView | middleInView) {
306 //console.log('displayed: ' + this.displayedIndices);
307 //console.log('to display: ' + i);
308 indicesToDisplay.push(i);
310 leafTop += height +10;
314 var firstIndexToDraw = indicesToDisplay[0];
315 this.firstIndex = firstIndexToDraw;
317 // Update hash, but only if we're currently displaying a leaf
318 // Hack that fixes #365790
319 if (this.displayedIndices.length > 0) {
320 this.updateLocationHash();
323 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
325 indicesToDisplay.unshift(firstIndexToDraw);
328 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
329 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
330 indicesToDisplay.push(lastIndexToDraw+1);
335 for (i=0; i<firstIndexToDraw; i++) {
336 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
339 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
340 var viewWidth = $('#GBcontainer').attr('scrollWidth');
343 for (i=0; i<indicesToDisplay.length; i++) {
344 var index = indicesToDisplay[i];
345 var height = parseInt(this.getPageHeight(index)/this.reduce);
347 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
348 var width = parseInt(this.getPageWidth(index)/this.reduce);
349 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
350 var div = document.createElement("div");
351 div.className = 'GBpagediv1up';
352 div.id = 'pagediv'+index;
353 div.style.position = "absolute";
354 $(div).css('top', leafTop + 'px');
355 var left = (viewWidth-width)>>1;
356 if (left<0) left = 0;
357 $(div).css('left', left+'px');
358 $(div).css('width', width+'px');
359 $(div).css('height', height+'px');
360 //$(div).text('loading...');
362 this.setDragHandler1up(div);
364 $('#GBpageview').append(div);
366 var img = document.createElement("img");
367 img.src = this.getPageURI(index);
368 $(img).css('width', width+'px');
369 $(img).css('height', height+'px');
373 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
376 leafTop += height +10;
380 for (i=0; i<this.displayedIndices.length; i++) {
381 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
382 var index = this.displayedIndices[i];
383 //console.log('Removing leaf ' + index);
384 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
385 $('#pagediv'+index).remove();
387 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
391 this.displayedIndices = indicesToDisplay.slice();
392 this.updateSearchHilites();
394 if (null != this.getPageNum(firstIndexToDraw)) {
395 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
397 $("#GBpagenum").val('');
401 // drawLeafsTwoPage()
402 //______________________________________________________________________________
403 GnuBook.prototype.drawLeafsTwoPage = function() {
404 //alert('drawing two leafs!');
406 var scrollTop = $('#GBcontainer').attr('scrollTop');
407 var scrollBottom = scrollTop + $('#GBcontainer').height();
409 //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentIndexL);
411 var index = this.currentIndexL;
412 var height = this.getPageHeight(index);
413 var width = this.getPageWidth(index);
414 var handSide= this.getPageSide(index);
416 var leafEdgeWidthL = this.leafEdgeWidth(index);
417 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
418 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
419 var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
420 //console.log(leafEdgeWidthL);
422 var middle = ($('#GBcontainer').width() >> 1);
423 var left = middle - this.twoPageW;
424 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
426 var scaledW = parseInt(this.twoPageH*width/height);
427 left = 10+leafEdgeWidthL;
428 //var right = left+scaledW;
429 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
431 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
433 this.prefetchImg(index);
434 $(this.prefetchedImgs[index]).css({
435 position: 'absolute',
436 /*right: gutter+'px',*/
437 left: gutter-scaledW+'px',
440 backgroundColor: 'rgb(234, 226, 205)',
441 height: this.twoPageH +'px',
442 width: scaledW + 'px',
443 borderRight: '1px solid black',
445 }).appendTo('#GBcontainer');
446 //$('#GBcontainer').append(this.prefetchedImgs[index]);
449 var index = this.currentIndexR;
450 var height = this.getPageHeight(index);
451 var width = this.getPageWidth(index);
452 // var left = ($('#GBcontainer').width() >> 1);
455 var scaledW = this.twoPageH*width/height;
456 this.prefetchImg(index);
457 $(this.prefetchedImgs[index]).css({
458 position: 'absolute',
462 backgroundColor: 'rgb(234, 226, 205)',
463 height: this.twoPageH + 'px',
464 width: scaledW + 'px',
465 borderLeft: '1px solid black',
467 }).appendTo('#GBcontainer');
468 //$('#GBcontainer').append(this.prefetchedImgs[index]);
471 this.displayedIndices = [this.currentIndexL, this.currentIndexR];
472 this.setClickHandlers();
474 this.updatePageNumBox2UP();
477 // updatePageNumBox2UP
478 //______________________________________________________________________________
479 GnuBook.prototype.updatePageNumBox2UP = function() {
480 if (null != this.getPageNum(this.currentIndexL)) {
481 $("#GBpagenum").val(this.getPageNum(this.currentIndexL));
483 $("#GBpagenum").val('');
485 this.updateLocationHash();
489 //______________________________________________________________________________
490 GnuBook.prototype.loadLeafs = function() {
494 if (null == this.timer) {
495 this.timer=setTimeout(function(){self.drawLeafs()},250);
497 clearTimeout(this.timer);
498 this.timer=setTimeout(function(){self.drawLeafs()},250);
504 //______________________________________________________________________________
505 GnuBook.prototype.zoom1up = function(dir) {
506 if (2 == this.mode) { //can only zoom in 1-page mode
512 if (this.reduce <= 0.5) return;
513 this.reduce*=0.5; //zoom in
515 if (this.reduce >= 8) return;
516 this.reduce*=2; //zoom out
519 this.resizePageView();
521 $('#GBpageview').empty()
522 this.displayedIndices = [];
525 $('#GBzoom').text(100/this.reduce);
529 //______________________________________________________________________________
530 GnuBook.prototype.resizePageView = function() {
533 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
534 var viewWidth = $('#GBcontainer').attr('clientWidth');
536 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
537 var oldViewHeight = $('#GBpageview').height();
538 if (0 != oldViewHeight) {
539 var scrollRatio = oldScrollTop / oldViewHeight;
544 for (i=0; i<this.numLeafs; i++) {
545 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
546 var width = parseInt(this.getPageWidth(i)/this.reduce);
547 if (width>viewWidth) viewWidth=width;
549 $('#GBpageview').height(viewHeight);
550 $('#GBpageview').width(viewWidth);
552 $('#GBcontainer').attr('scrollTop', Math.floor(scrollRatio*viewHeight));
554 this.centerPageView();
560 //______________________________________________________________________________
561 GnuBook.prototype.centerPageView = function() {
563 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
564 var clientWidth = $('#GBcontainer').attr('clientWidth');
565 //console.log('sW='+scrollWidth+' cW='+clientWidth);
566 if (scrollWidth > clientWidth) {
567 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
573 //______________________________________________________________________________
574 // Attempts to jump to page. Returns true if page could be found, false otherwise.
575 GnuBook.prototype.jumpToPage = function(pageNum) {
577 var pageIndex = this.getPageIndex(pageNum);
579 if ('undefined' != typeof(pageIndex)) {
582 this.jumpToIndex(pageIndex);
583 $('#GBcontainer').attr('scrollTop', leafTop);
592 //______________________________________________________________________________
593 GnuBook.prototype.jumpToIndex = function(index) {
595 if (2 == this.mode) {
598 // By checking against min/max we do nothing if requested index
600 if (index < Math.min(this.currentIndexL, this.currentIndexR)) {
601 this.flipBackToIndex(index);
602 } else if (index > Math.max(this.currentIndexL, this.currentIndexR)) {
603 this.flipFwdToIndex(index);
610 for (i=0; i<index; i++) {
611 h = parseInt(this.getPageHeight(i)/this.reduce);
612 leafTop += h + this.padding;
614 //$('#GBcontainer').attr('scrollTop', leafTop);
615 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
622 //______________________________________________________________________________
623 GnuBook.prototype.switchMode = function(mode) {
625 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
627 if (mode == this.mode) return;
629 if (!this.canSwitchToMode(mode)) {
634 this.removeSearchHilites();
638 this.switchToolbarMode(mode);
641 this.prepareOnePageView();
643 this.prepareTwoPageView();
648 //prepareOnePageView()
649 //______________________________________________________________________________
650 GnuBook.prototype.prepareOnePageView = function() {
652 // var startLeaf = this.displayedIndices[0];
653 var startLeaf = this.currentIndex();
655 $('#GBcontainer').empty();
656 $('#GBcontainer').css({
661 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
662 this.resizePageView();
664 this.jumpToIndex(startLeaf);
665 this.displayedIndices = [];
667 this.drawLeafsOnePage();
668 $('#GBzoom').text(100/this.reduce);
670 // Bind mouse handlers
671 // Disable mouse click to avoid selected/highlighted page images - bug 354239
672 gbPageView.bind('mousedown', function(e) {
675 // Special hack for IE7
676 gbPageView[0].onselectstart = function(e) { return false; };
679 // prepareTwoPageView()
680 //______________________________________________________________________________
681 GnuBook.prototype.prepareTwoPageView = function() {
682 $('#GBcontainer').empty();
684 // We want to display two facing pages. We may be missing
685 // one side of the spread because it is the first/last leaf,
686 // foldouts, missing pages, etc
688 //var targetLeaf = this.displayedIndices[0];
689 var targetLeaf = this.firstIndex;
691 if (targetLeaf < this.firstDisplayableIndex()) {
692 targetLeaf = this.firstDisplayableIndex();
695 if (targetLeaf > this.lastDisplayableIndex()) {
696 targetLeaf = this.lastDisplayableIndex();
699 this.currentIndexL = null;
700 this.currentIndexR = null;
701 this.pruneUnusedImgs();
703 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
704 this.currentIndexL = currentSpreadIndices[0];
705 this.currentIndexR = currentSpreadIndices[1];
706 this.firstIndex = this.currentIndexL;
708 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
710 // We want to minimize the unused space in two-up mode (maximize the amount of page
711 // shown). We give width to the leaf edges and these widths change (though the sum
712 // of the two remains constant) as we flip through the book. With the book
713 // cover centered and fixed in the GBcontainer div the page images will meet
714 // at the "gutter" which is generally offset from the center.
715 var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
716 //var gutter = middle+parseInt((2*this.currentIndexL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
718 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
720 var scaledWL = this.getPageWidth2UP(this.currentIndexL);
721 var scaledWR = this.getPageWidth2UP(this.currentIndexR);
722 var leafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
723 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
725 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
726 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
728 // The width of the book cover div. The combined width of both pages, twice the width
729 // of the book cover internal padding (2*10) and the page edges
730 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
732 // The height of the book cover div
733 var bookCoverDivHeight = this.twoPageH+20;
735 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
736 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
737 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
738 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
740 this.twoPageDiv = document.createElement('div');
741 $(this.twoPageDiv).attr('id', 'book_div_1').css({
742 border: '1px solid rgb(68, 25, 17)',
743 width: bookCoverDivWidth + 'px',
744 height: bookCoverDivHeight+'px',
745 visibility: 'visible',
746 position: 'absolute',
747 backgroundColor: '#663929',
748 left: bookCoverDivLeft + 'px',
749 top: bookCoverDivTop+'px',
750 MozBorderRadiusTopleft: '7px',
751 MozBorderRadiusTopright: '7px',
752 MozBorderRadiusBottomright: '7px',
753 MozBorderRadiusBottomleft: '7px'
754 }).appendTo('#GBcontainer');
755 //$('#GBcontainer').append('<div id="book_div_1" style="border: 1px solid rgb(68, 25, 17); width: ' + bookCoverDivWidth + 'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(136, 51, 34); left: ' + bookCoverDivLeft + 'px; top: '+bookCoverDivTop+'px; -moz-border-radius-topleft: 7px; -moz-border-radius-topright: 7px; -moz-border-radius-bottomright: 7px; -moz-border-radius-bottomleft: 7px;"/>');
758 var height = this.getPageHeight(this.currentIndexR);
759 var width = this.getPageWidth(this.currentIndexR);
760 var scaledW = this.twoPageH*width/height;
762 this.leafEdgeR = document.createElement('div');
763 this.leafEdgeR.className = 'leafEdgeR';
764 $(this.leafEdgeR).css({
765 borderStyle: 'solid solid solid none',
766 borderColor: 'rgb(51, 51, 34)',
767 borderWidth: '1px 1px 1px 0px',
768 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
769 width: leafEdgeWidthR + 'px',
770 height: this.twoPageH-1 + 'px',
772 left: gutter+scaledW+'px',
773 top: bookCoverDivTop+10+'px',
775 }).appendTo('#GBcontainer');
777 this.leafEdgeL = document.createElement('div');
778 this.leafEdgeL.className = 'leafEdgeL';
779 $(this.leafEdgeL).css({
780 borderStyle: 'solid none solid solid',
781 borderColor: 'rgb(51, 51, 34)',
782 borderWidth: '1px 0px 1px 1px',
783 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
784 width: leafEdgeWidthL + 'px',
785 height: this.twoPageH-1 + 'px',
786 left: bookCoverDivLeft+10+'px',
787 top: bookCoverDivTop+10+'px',
789 }).appendTo('#GBcontainer');
793 bookCoverDivWidth = 30;
794 bookCoverDivHeight = this.twoPageH+20;
795 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
796 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
798 div = document.createElement('div');
799 $(div).attr('id', 'book_div_2').css({
800 border: '1px solid rgb(68, 25, 17)',
801 width: bookCoverDivWidth+'px',
802 height: bookCoverDivHeight+'px',
803 position: 'absolute',
804 backgroundColor: 'rgb(68, 25, 17)',
805 left: bookCoverDivLeft+'px',
806 top: bookCoverDivTop+'px'
807 }).appendTo('#GBcontainer');
808 //$('#GBcontainer').append('<div id="book_div_2" style="border: 1px solid rgb(68, 25, 17); width: '+bookCoverDivWidth+'px; height: '+bookCoverDivHeight+'px; visibility: visible; position: absolute; background-color: rgb(68, 25, 17); left: '+bookCoverDivLeft+'px; top: '+bookCoverDivTop+'px;"/>');
810 bookCoverDivWidth = this.twoPageW*2;
811 bookCoverDivHeight = this.twoPageH;
812 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
813 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
816 this.prepareTwoPagePopUp();
818 this.displayedIndices = [];
820 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
821 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
823 this.drawLeafsTwoPage();
824 this.updateSearchHilites2UP();
827 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentIndexL)).toString().substr(0,4));
830 // prepareTwoPagePopUp()
832 // This function prepares the "View Page n" popup that shows while the mouse is
833 // over the left/right "stack of sheets" edges. It also binds the mouse
834 // events for these divs.
835 //______________________________________________________________________________
836 GnuBook.prototype.prepareTwoPagePopUp = function() {
837 this.twoPagePopUp = document.createElement('div');
838 $(this.twoPagePopUp).css({
839 border: '1px solid black',
841 position: 'absolute',
842 fontFamily: 'sans-serif',
845 backgroundColor: 'rgb(255, 255, 238)',
847 }).appendTo('#GBcontainer');
848 $(this.twoPagePopUp).hide();
850 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
851 $(e.data.twoPagePopUp).show();
854 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
855 $(e.data.twoPagePopUp).hide();
858 $(this.leafEdgeL).bind('click', this, function(e) {
860 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
861 e.data.jumpToIndex(jumpIndex);
864 $(this.leafEdgeR).bind('click', this, function(e) {
866 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
867 e.data.jumpToIndex(jumpIndex);
870 $(this.leafEdgeR).bind('mousemove', this, function(e) {
872 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
873 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
875 $(e.data.twoPagePopUp).css({
876 left: e.pageX +5+ 'px',
877 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
881 $(this.leafEdgeL).bind('mousemove', this, function(e) {
883 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
884 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
886 $(e.data.twoPagePopUp).css({
887 left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
888 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
893 // calculateSpreadSize()
894 //______________________________________________________________________________
895 // Calculates 2-page spread dimensions based on this.currentIndexL and
896 // this.currentIndexR
897 // This function sets this.twoPageH, twoPageW, and twoPageRatio
899 GnuBook.prototype.calculateSpreadSize = function() {
900 var firstIndex = this.currentIndexL;
901 var secondIndex = this.currentIndexR;
902 //console.log('first page is ' + firstIndex);
904 var canon5Dratio = 1.5;
906 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
907 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
908 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
911 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
912 ratio = firstIndexRatio;
913 //console.log('using firstIndexRatio ' + ratio);
915 ratio = secondIndexRatio;
916 //console.log('using secondIndexRatio ' + ratio);
919 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
920 var maxLeafEdgeWidth = parseInt($('#GBcontainer').width() * 0.1);
921 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
923 $('#GBcontainer').css('overflow', 'hidden');
925 var idealWidth = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
926 var idealHeight = $('#GBcontainer').height() - 30;
927 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
929 if (idealHeight/ratio <= idealWidth) {
931 idealWidth = parseInt(idealHeight/ratio);
934 idealHeight = parseInt(idealWidth*ratio);
937 this.twoPageH = idealHeight;
938 this.twoPageW = idealWidth;
939 this.twoPageRatio = ratio;
940 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
945 //______________________________________________________________________________
946 // Returns the currently active index.
947 GnuBook.prototype.currentIndex = function() {
948 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
949 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
950 return this.firstIndex;
952 throw 'currentIndex called for unimplemented mode ' + this.mode;
957 //______________________________________________________________________________
958 // Flip the right page over onto the left
959 GnuBook.prototype.right = function() {
960 if ('rl' != this.pageProgression) {
970 //______________________________________________________________________________
971 // Flip to the rightmost page
972 GnuBook.prototype.rightmost = function() {
973 if ('rl' != this.pageProgression) {
981 //______________________________________________________________________________
982 // Flip the left page over onto the right.
983 GnuBook.prototype.left = function() {
984 if ('rl' != this.pageProgression) {
994 //______________________________________________________________________________
995 // Flip to the leftmost page
996 GnuBook.prototype.leftmost = function() {
997 if ('rl' != this.pageProgression) {
1005 //______________________________________________________________________________
1006 GnuBook.prototype.next = function() {
1007 if (2 == this.mode) {
1009 this.flipFwdToIndex(null);
1011 if (this.firstIndex < this.lastDisplayableIndex()) {
1012 this.jumpToIndex(this.firstIndex+1);
1018 //______________________________________________________________________________
1019 GnuBook.prototype.prev = function() {
1020 if (2 == this.mode) {
1022 this.flipBackToIndex(null);
1024 if (this.firstIndex >= 1) {
1025 this.jumpToIndex(this.firstIndex-1);
1030 GnuBook.prototype.first = function() {
1031 if (2 == this.mode) {
1032 this.jumpToIndex(2);
1035 this.jumpToIndex(0);
1039 GnuBook.prototype.last = function() {
1040 if (2 == this.mode) {
1041 this.jumpToIndex(this.lastDisplayableIndex());
1044 this.jumpToIndex(this.lastDisplayableIndex());
1048 // flipBackToIndex()
1049 //______________________________________________________________________________
1050 // to flip back one spread, pass index=null
1051 GnuBook.prototype.flipBackToIndex = function(index) {
1052 if (1 == this.mode) return;
1054 var leftIndex = this.currentIndexL;
1056 // $$$ Need to change this to be able to see first spread.
1057 // See https://bugs.launchpad.net/gnubook/+bug/296788
1058 if (leftIndex <= 2) return;
1059 if (this.animating) return;
1061 if (null != this.leafEdgeTmp) {
1062 alert('error: leafEdgeTmp should be null!');
1066 if (null == index) {
1067 index = leftIndex-2;
1069 //if (index<0) return;
1071 var previousIndices = this.getSpreadIndices(index);
1073 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1077 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1079 this.animating = true;
1081 if ('rl' != this.pageProgression) {
1082 // Assume LTR and we are going backward
1083 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1084 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1087 // RTL and going backward
1088 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1089 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1093 // flipLeftToRight()
1094 //______________________________________________________________________________
1095 // Flips the page on the left towards the page on the right
1096 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1098 var leftLeaf = this.currentIndexL;
1100 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1101 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1102 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1104 var currWidthL = this.getPageWidth2UP(leftLeaf);
1105 var newWidthL = this.getPageWidth2UP(newIndexL);
1106 var newWidthR = this.getPageWidth2UP(newIndexR);
1108 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1110 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1111 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1113 //animation strategy:
1114 // 0. remove search highlight, if any.
1115 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1116 // of the left leaf and where the user clicked in the leaf edge.
1117 // Note that if this function was triggered by left() and not a
1118 // mouse click, the width of leafEdgeTmp is very small (zero px).
1119 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1120 // leftLeaf to width=0.
1121 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1122 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1123 // its new full width.
1124 // 4. After step 3 is finished, do the following:
1125 // - remove leafEdgeTmp from the dom.
1126 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1127 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1128 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1129 // and width=newLeafEdgeWidthL.
1130 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1131 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1132 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1133 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1134 // - prefetch new adjacent leafs.
1135 // - set up click handlers for both new left and right leafs.
1136 // - redraw the search highlight.
1137 // - update the pagenum box and the url.
1140 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1142 this.leafEdgeTmp = document.createElement('div');
1143 $(this.leafEdgeTmp).css({
1144 borderStyle: 'solid none solid solid',
1145 borderColor: 'rgb(51, 51, 34)',
1146 borderWidth: '1px 0px 1px 1px',
1147 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1148 width: leafEdgeTmpW + 'px',
1149 height: this.twoPageH-1 + 'px',
1150 left: leftEdgeTmpLeft + 'px',
1152 position: 'absolute',
1154 }).appendTo('#GBcontainer');
1156 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1157 $(this.leafEdgeL).css({
1158 width: newLeafEdgeWidthL+'px',
1159 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1162 // Left gets the offset of the current left leaf from the document
1163 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1164 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1165 var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1166 // We change the left leaf to right positioning
1167 $(this.prefetchedImgs[leftLeaf]).css({
1172 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1174 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1176 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1177 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1181 this.removeSearchHilites();
1183 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1184 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1186 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1187 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1189 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1190 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1191 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1193 $(self.leafEdgeR).css({
1194 // Moves the right leaf edge
1195 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1196 left: gutter+newWidthR+'px'
1199 $(self.leafEdgeL).css({
1200 // Moves and resizes the left leaf edge
1201 width: newLeafEdgeWidthL+'px',
1202 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1206 $(self.twoPageDiv).css({
1207 // Resizes the brown border div
1208 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1209 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1212 $(self.leafEdgeTmp).remove();
1213 self.leafEdgeTmp = null;
1215 self.currentIndexL = newIndexL;
1216 self.currentIndexR = newIndexR;
1217 self.firstIndex = self.currentIndexL;
1218 self.displayedIndices = [newIndexL, newIndexR];
1219 self.setClickHandlers();
1220 self.pruneUnusedImgs();
1222 self.animating = false;
1224 self.updateSearchHilites2UP();
1225 self.updatePageNumBox2UP();
1226 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1228 if (self.animationFinishedCallback) {
1229 self.animationFinishedCallback();
1230 self.animationFinishedCallback = null;
1238 //______________________________________________________________________________
1239 // Whether we flip left or right is dependent on the page progression
1240 // to flip forward one spread, pass index=null
1241 GnuBook.prototype.flipFwdToIndex = function(index) {
1243 if (this.animating) return;
1245 if (null != this.leafEdgeTmp) {
1246 alert('error: leafEdgeTmp should be null!');
1250 if (null == index) {
1251 index = this.currentIndexR+2; // $$$ assumes indices are continuous
1253 if (index > this.lastDisplayableIndex()) return;
1255 this.animating = true;
1257 var nextIndices = this.getSpreadIndices(index);
1259 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1261 if ('rl' != this.pageProgression) {
1262 // We did not specify RTL
1263 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1264 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1267 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1268 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1272 // flipRightToLeft(nextL, nextR, gutter)
1273 // $$$ better not to have to pass gutter in
1274 //______________________________________________________________________________
1275 // Flip from left to right and show the nextL and nextR indices on those sides
1276 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1277 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1278 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1279 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1280 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1282 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1284 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1286 var scaledW = this.getPageWidth2UP(this.currentIndexR);
1288 var middle = ($('#GBcontainer').width() >> 1);
1289 var currGutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1291 this.leafEdgeTmp = document.createElement('div');
1292 $(this.leafEdgeTmp).css({
1293 borderStyle: 'solid none solid solid',
1294 borderColor: 'rgb(51, 51, 34)',
1295 borderWidth: '1px 0px 1px 1px',
1296 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1297 width: leafEdgeTmpW + 'px',
1298 height: this.twoPageH-1 + 'px',
1299 left: currGutter+scaledW+'px',
1301 position: 'absolute',
1303 }).appendTo('#GBcontainer');
1305 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1306 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1308 var currWidthL = this.getPageWidth2UP(this.currentIndexL);
1309 var currWidthR = this.getPageWidth2UP(this.currentIndexR);
1310 var newWidthL = this.getPageWidth2UP(newIndexL);
1311 var newWidthR = this.getPageWidth2UP(newIndexR);
1313 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1315 var self = this; // closure-tastic!
1317 var speed = this.flipSpeed;
1319 this.removeSearchHilites();
1321 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1322 $(this.prefetchedImgs[this.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1323 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1324 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1325 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1327 $(self.leafEdgeL).css({
1328 width: newLeafEdgeWidthL+'px',
1329 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1332 $(self.twoPageDiv).css({
1333 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1334 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1337 $(self.leafEdgeTmp).remove();
1338 self.leafEdgeTmp = null;
1340 self.currentIndexL = newIndexL;
1341 self.currentIndexR = newIndexR;
1342 self.firstIndex = self.currentIndexL;
1343 self.displayedIndices = [newIndexL, newIndexR];
1344 self.setClickHandlers();
1345 self.pruneUnusedImgs();
1347 self.animating = false;
1350 self.updateSearchHilites2UP();
1351 self.updatePageNumBox2UP();
1352 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1354 if (self.animationFinishedCallback) {
1355 self.animationFinishedCallback();
1356 self.animationFinishedCallback = null;
1363 //______________________________________________________________________________
1364 GnuBook.prototype.setClickHandlers = function() {
1366 $(this.prefetchedImgs[this.currentIndexL]).click(function() {
1371 $(this.prefetchedImgs[this.currentIndexR]).click(function() {
1379 //______________________________________________________________________________
1380 GnuBook.prototype.prefetchImg = function(index) {
1381 if (undefined == this.prefetchedImgs[index]) {
1382 //console.log('prefetching ' + index);
1383 var img = document.createElement("img");
1384 img.src = this.getPageURI(index);
1385 this.prefetchedImgs[index] = img;
1390 // prepareFlipLeftToRight()
1392 //______________________________________________________________________________
1394 // Prepare to flip the left page towards the right. This corresponds to moving
1395 // backward when the page progression is left to right.
1396 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1398 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1400 this.prefetchImg(prevL);
1401 this.prefetchImg(prevR);
1403 var height = this.getPageHeight(prevL);
1404 var width = this.getPageWidth(prevL);
1405 var middle = ($('#GBcontainer').width() >> 1);
1406 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1407 var scaledW = this.twoPageH*width/height;
1409 // The gutter is the dividing line between the left and right pages.
1410 // It is offset from the middle to create the illusion of thickness to the pages
1411 var gutter = middle + this.gutterOffsetForIndex(prevL);
1413 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1414 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1415 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1417 $(this.prefetchedImgs[prevL]).css({
1418 position: 'absolute',
1419 /*right: middle+'px',*/
1420 left: gutter-scaledW+'px',
1423 backgroundColor: 'rgb(234, 226, 205)',
1424 height: this.twoPageH,
1425 width: scaledW+'px',
1426 borderRight: '1px solid black',
1430 $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1432 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1434 $(this.prefetchedImgs[prevR]).css({
1435 position: 'absolute',
1439 backgroundColor: 'rgb(234, 226, 205)',
1440 height: this.twoPageH,
1442 borderLeft: '1px solid black',
1446 $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1453 // prepareFlipRightToLeft()
1454 //______________________________________________________________________________
1455 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1457 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1459 this.prefetchImg(nextL);
1460 this.prefetchImg(nextR);
1462 var height = this.getPageHeight(nextR);
1463 var width = this.getPageWidth(nextR);
1464 var middle = ($('#GBcontainer').width() >> 1);
1465 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1466 var scaledW = this.twoPageH*width/height;
1468 var gutter = middle + this.gutterOffsetForIndex(nextL);
1470 //console.log('right to left to %d gutter is %d', nextL, gutter);
1472 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1473 $(this.prefetchedImgs[nextR]).css({
1474 position: 'absolute',
1477 backgroundColor: 'rgb(234, 226, 205)',
1478 height: this.twoPageH,
1479 width: scaledW+'px',
1480 borderLeft: '1px solid black',
1484 $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1486 height = this.getPageHeight(nextL);
1487 width = this.getPageWidth(nextL);
1488 scaledW = this.twoPageH*width/height;
1490 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1491 $(this.prefetchedImgs[nextL]).css({
1492 position: 'absolute',
1493 right: $('#GBcontainer').width()-gutter+'px',
1495 backgroundColor: 'rgb(234, 226, 205)',
1496 height: this.twoPageH,
1498 borderRight: '1px solid black',
1502 $('#GBcontainer').append(this.prefetchedImgs[nextL]);
1508 // getNextLeafs() -- NOT RTL AWARE
1509 //______________________________________________________________________________
1510 // GnuBook.prototype.getNextLeafs = function(o) {
1511 // //TODO: we might have two left or two right leafs in a row (damaged book)
1512 // //For now, assume that leafs are contiguous.
1514 // //return [this.currentIndexL+2, this.currentIndexL+3];
1515 // o.L = this.currentIndexL+2;
1516 // o.R = this.currentIndexL+3;
1519 // getprevLeafs() -- NOT RTL AWARE
1520 //______________________________________________________________________________
1521 // GnuBook.prototype.getPrevLeafs = function(o) {
1522 // //TODO: we might have two left or two right leafs in a row (damaged book)
1523 // //For now, assume that leafs are contiguous.
1525 // //return [this.currentIndexL-2, this.currentIndexL-1];
1526 // o.L = this.currentIndexL-2;
1527 // o.R = this.currentIndexL-1;
1530 // pruneUnusedImgs()
1531 //______________________________________________________________________________
1532 GnuBook.prototype.pruneUnusedImgs = function() {
1533 //console.log('current: ' + this.currentIndexL + ' ' + this.currentIndexR);
1534 for (var key in this.prefetchedImgs) {
1535 //console.log('key is ' + key);
1536 if ((key != this.currentIndexL) && (key != this.currentIndexR)) {
1537 //console.log('removing key '+ key);
1538 $(this.prefetchedImgs[key]).remove();
1540 if ((key < this.currentIndexL-4) || (key > this.currentIndexR+4)) {
1541 //console.log('deleting key '+ key);
1542 delete this.prefetchedImgs[key];
1548 //______________________________________________________________________________
1549 GnuBook.prototype.prefetch = function() {
1551 var lim = this.currentIndexL-4;
1553 lim = Math.max(lim, 0);
1554 for (i = lim; i < this.currentIndexL; i++) {
1555 this.prefetchImg(i);
1558 if (this.numLeafs > (this.currentIndexR+1)) {
1559 lim = Math.min(this.currentIndexR+4, this.numLeafs-1);
1560 for (i=this.currentIndexR+1; i<=lim; i++) {
1561 this.prefetchImg(i);
1566 // getPageWidth2UP()
1567 //______________________________________________________________________________
1568 GnuBook.prototype.getPageWidth2UP = function(index) {
1569 var height = this.getPageHeight(index);
1570 var width = this.getPageWidth(index);
1571 return Math.floor(this.twoPageH*width/height);
1575 //______________________________________________________________________________
1576 GnuBook.prototype.search = function(term) {
1577 $('#GnuBookSearchScript').remove();
1578 var script = document.createElement("script");
1579 script.setAttribute('id', 'GnuBookSearchScript');
1580 script.setAttribute("type", "text/javascript");
1581 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1582 document.getElementsByTagName('head')[0].appendChild(script);
1583 $('#GnuBookSearchResults').html('Searching...');
1586 // GBSearchCallback()
1587 //______________________________________________________________________________
1588 GnuBook.prototype.GBSearchCallback = function(txt) {
1590 if (jQuery.browser.msie) {
1591 var dom=new ActiveXObject("Microsoft.XMLDOM");
1595 var parser = new DOMParser();
1596 var dom = parser.parseFromString(txt, "text/xml");
1599 $('#GnuBookSearchResults').empty();
1600 $('#GnuBookSearchResults').append('<ul>');
1602 for (var key in this.searchResults) {
1603 if (null != this.searchResults[key].div) {
1604 $(this.searchResults[key].div).remove();
1606 delete this.searchResults[key];
1609 var pages = dom.getElementsByTagName('PAGE');
1611 if (0 == pages.length) {
1612 // $$$ it would be nice to echo the (sanitized) search result here
1613 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1615 for (var i = 0; i < pages.length; i++){
1616 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1619 var re = new RegExp (/_(\d{4})/);
1620 var reMatch = re.exec(pages[i].getAttribute('file'));
1621 var index = parseInt(reMatch[1], 10);
1622 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1624 var children = pages[i].childNodes;
1626 for (var j=0; j<children.length; j++) {
1627 //console.log(j + ' - ' + children[j].nodeName);
1628 //console.log(children[j].firstChild.nodeValue);
1629 if ('CONTEXT' == children[j].nodeName) {
1630 context += children[j].firstChild.nodeValue;
1631 } else if ('WORD' == children[j].nodeName) {
1632 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1634 var index = this.leafNumToIndex(index);
1635 if (null != index) {
1636 //coordinates are [left, bottom, right, top, [baseline]]
1637 //we'll skip baseline for now...
1638 var coords = children[j].getAttribute('coords').split(',',4);
1639 if (4 == coords.length) {
1640 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1645 var pageName = this.getPageName(index);
1646 //TODO: remove hardcoded instance name
1647 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1650 $('#GnuBookSearchResults').append('</ul>');
1652 this.updateSearchHilites();
1655 // updateSearchHilites()
1656 //______________________________________________________________________________
1657 GnuBook.prototype.updateSearchHilites = function() {
1658 if (2 == this.mode) {
1659 this.updateSearchHilites2UP();
1661 this.updateSearchHilites1UP();
1665 // showSearchHilites1UP()
1666 //______________________________________________________________________________
1667 GnuBook.prototype.updateSearchHilites1UP = function() {
1669 for (var key in this.searchResults) {
1671 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1672 var result = this.searchResults[key];
1673 if(null == result.div) {
1674 result.div = document.createElement('div');
1675 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1676 //console.log('appending ' + key);
1679 width: (result.r-result.l)/this.reduce + 'px',
1680 height: (result.b-result.t)/this.reduce + 'px',
1681 left: (result.l)/this.reduce + 'px',
1682 top: (result.t)/this.reduce +'px'
1686 //console.log(key + ' not displayed');
1687 this.searchResults[key].div=null;
1692 // showSearchHilites2UP()
1693 //______________________________________________________________________________
1694 GnuBook.prototype.updateSearchHilites2UP = function() {
1696 var middle = ($('#GBcontainer').width() >> 1);
1698 for (var key in this.searchResults) {
1699 key = parseInt(key, 10);
1700 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1701 var result = this.searchResults[key];
1702 if(null == result.div) {
1703 result.div = document.createElement('div');
1704 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1705 //console.log('appending ' + key);
1708 var height = this.getPageHeight(key);
1709 var width = this.getPageWidth(key)
1710 var reduce = this.twoPageH/height;
1711 var scaledW = parseInt(width*reduce);
1713 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1715 if ('L' == this.getPageSide(key)) {
1716 var pageL = gutter-scaledW;
1720 var pageT = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1723 width: (result.r-result.l)*reduce + 'px',
1724 height: (result.b-result.t)*reduce + 'px',
1725 left: pageL+(result.l)*reduce + 'px',
1726 top: pageT+(result.t)*reduce +'px'
1730 //console.log(key + ' not displayed');
1731 if (null != this.searchResults[key].div) {
1732 //console.log('removing ' + key);
1733 $(this.searchResults[key].div).remove();
1735 this.searchResults[key].div=null;
1740 // removeSearchHilites()
1741 //______________________________________________________________________________
1742 GnuBook.prototype.removeSearchHilites = function() {
1743 for (var key in this.searchResults) {
1744 if (null != this.searchResults[key].div) {
1745 $(this.searchResults[key].div).remove();
1746 this.searchResults[key].div=null;
1752 //______________________________________________________________________________
1753 GnuBook.prototype.showEmbedCode = function() {
1754 if (null != this.embedPopup) { // check if already showing
1758 this.embedPopup = document.createElement("div");
1759 $(this.embedPopup).css({
1760 position: 'absolute',
1762 left: ($('#GBcontainer').width()-400)/2 + 'px',
1765 border: "3px double #999999",
1767 backgroundColor: "#fff"
1768 }).appendTo('#GnuBook');
1770 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1771 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>';
1772 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1773 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1775 this.embedPopup.innerHTML = htmlStr;
1776 $(this.embedPopup).find('input').bind('click', function() {
1782 //______________________________________________________________________________
1783 GnuBook.prototype.autoToggle = function() {
1785 var bComingFrom1up = false;
1786 if (2 != this.mode) {
1787 bComingFrom1up = true;
1792 if (null == this.autoTimer) {
1793 this.flipSpeed = 2000;
1795 // $$$ Draw events currently cause layout problems when they occur during animation.
1796 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1797 // we workaround for now by not triggering immediate animation in that case.
1798 // See https://bugs.launchpad.net/gnubook/+bug/328327
1799 if (('rl' == this.pageProgression) && bComingFrom1up) {
1800 // don't flip immediately -- wait until timer fires
1803 this.flipFwdToIndex();
1806 $('#GBtoolbar .play').hide();
1807 $('#GBtoolbar .pause').show();
1808 this.autoTimer=setInterval(function(){
1809 if (self.animating) {return;}
1811 if (Math.max(self.currentIndexL, self.currentIndexR) >= self.lastDisplayableIndex()) {
1812 self.flipBackToIndex(1); // $$$ really what we want?
1814 self.flipFwdToIndex();
1823 //______________________________________________________________________________
1824 GnuBook.prototype.autoStop = function() {
1825 if (null != this.autoTimer) {
1826 clearInterval(this.autoTimer);
1827 this.flipSpeed = 'fast';
1828 $('#GBtoolbar .pause').hide();
1829 $('#GBtoolbar .play').show();
1830 this.autoTimer = null;
1834 // keyboardNavigationIsDisabled(event)
1835 // - returns true if keyboard navigation should be disabled for the event
1836 //______________________________________________________________________________
1837 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1838 if (event.target.tagName == "INPUT") {
1844 // gutterOffsetForIndex
1845 //______________________________________________________________________________
1847 // Returns the gutter offset for the spread containing the given index.
1848 // This function supports RTL
1849 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1851 // To find the offset of the gutter from the middle we calculate our percentage distance
1852 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1853 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1855 // But then again for RTL it's the opposite
1856 if ('rl' == this.pageProgression) {
1864 //______________________________________________________________________________
1865 // Returns the width of the leaf edge div for the page with index given
1866 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1867 // $$$ could there be single pixel rounding errors for L vs R?
1868 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1869 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1871 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1875 // jumpIndexForLeftEdgePageX
1876 //______________________________________________________________________________
1877 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1878 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1879 if ('rl' != this.pageProgression) {
1880 // LTR - flipping backward
1881 var jumpIndex = this.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1883 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1884 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexL - 2);
1888 var jumpIndex = this.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1889 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexL + 2, this.lastDisplayableIndex());
1894 // jumpIndexForRightEdgePageX
1895 //______________________________________________________________________________
1896 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1897 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1898 if ('rl' != this.pageProgression) {
1900 var jumpIndex = this.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1901 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexR + 2, this.lastDisplayableIndex());
1904 var jumpIndex = this.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1905 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexR - 2);
1910 GnuBook.prototype.initToolbar = function(mode, ui) {
1911 var modeButtons = '';
1913 // $$$ workaround for not displaying short books in 2up
1914 if (this.canSwitchToMode(this.constMode1up) && this.canSwitchToMode(this.constMode2up)) {
1915 modeButtons = " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1916 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>";
1919 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1920 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1921 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1922 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1923 + " <span class='label'>Zoom: <span id='GBzoom'>25</span>%</span>"
1925 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1928 if (ui == "embed") {
1929 $("#GnuBook a.logo").attr("target","_blank");
1932 // $$$ turn this into a member variable
1933 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1935 // We build in mode 2
1936 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1937 + "<button class='GBicon rollover embed' />"
1938 + "<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>"
1939 + "<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>"
1940 + "<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>"
1941 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1943 this.bindToolbarNavHandlers(jToolbar);
1945 // Setup tooltips -- later we could load these from a file for i18n
1946 var titles = { '.logo': 'Go to Archive.org',
1947 '.zoom_in': 'Zoom in',
1948 '.zoom_out': 'Zoom out',
1949 '.one_page_mode': 'One-page view',
1950 '.two_page_mode': 'Two-page view',
1951 '.embed': 'Embed bookreader',
1952 '.book_left': 'Flip left',
1953 '.book_right': 'Flip right',
1954 '.book_up': 'Page up',
1955 '.book_down': 'Page down',
1958 '.book_top': 'First page',
1959 '.book_bottom': 'Last page'
1961 if ('rl' == this.pageProgression) {
1962 titles['.book_leftmost'] = 'Last page';
1963 titles['.book_rightmost'] = 'First page';
1965 titles['.book_leftmost'] = 'First page';
1966 titles['.book_rightmost'] = 'Last page';
1969 for (var icon in titles) {
1970 jToolbar.find(icon).attr('title', titles[icon]);
1973 // Switch to requested mode -- binds other click handlers
1974 this.switchToolbarMode(mode);
1979 // switchToolbarMode
1980 //______________________________________________________________________________
1981 // Update the toolbar for the given mode (changes navigation buttons)
1982 // $$$ we should soon split the toolbar out into its own module
1983 GnuBook.prototype.switchToolbarMode = function(mode) {
1986 $('#GBtoolbar .GBtoolbarmode2').hide();
1987 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
1990 $('#GBtoolbar .GBtoolbarmode1').hide();
1991 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
1995 // bindToolbarNavHandlers
1996 //______________________________________________________________________________
1997 // Binds the toolbar handlers
1998 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2000 jToolbar.find('.book_left').bind('click', function(e) {
2005 jToolbar.find('.book_right').bind('click', function(e) {
2010 jToolbar.find('.book_up').bind('click', function(e) {
2015 jToolbar.find('.book_down').bind('click', function(e) {
2020 jToolbar.find('.embed').bind('click', function(e) {
2025 jToolbar.find('.play').bind('click', function(e) {
2030 jToolbar.find('.pause').bind('click', function(e) {
2035 jToolbar.find('.book_top').bind('click', function(e) {
2040 jToolbar.find('.book_bottom').bind('click', function(e) {
2045 jToolbar.find('.book_leftmost').bind('click', function(e) {
2050 jToolbar.find('.book_rightmost').bind('click', function(e) {
2056 // firstDisplayableIndex
2057 //______________________________________________________________________________
2058 // Returns the index of the first visible page, dependent on the mode.
2059 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2060 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2061 GnuBook.prototype.firstDisplayableIndex = function() {
2062 if (this.mode == 0) {
2065 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2069 // lastDisplayableIndex
2070 //______________________________________________________________________________
2071 // Returns the index of the last visible page, dependent on the mode.
2072 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2073 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2074 GnuBook.prototype.lastDisplayableIndex = function() {
2075 if (this.mode == 2) {
2076 if (this.lastDisplayableIndex2up === null) {
2077 // Calculate and cache
2078 var candidate = this.numLeafs - 1;
2079 for ( ; candidate >= 0; candidate--) {
2080 var spreadIndices = this.getSpreadIndices(candidate);
2081 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2085 this.lastDisplayableIndex2up = candidate;
2087 return this.lastDisplayableIndex2up;
2089 return this.numLeafs - 1;
2093 // shortTitle(maximumCharacters)
2095 // Returns a shortened version of the title with the maximum number of characters
2096 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2097 if (this.bookTitle.length < maximumCharacters) {
2098 return this.bookTitle;
2101 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2108 // Parameter related functions
2110 // updateFromParams(params)
2112 // Update ourselves from the params object.
2114 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2115 GnuBook.prototype.updateFromParams = function(params) {
2116 if ('undefined' != typeof(params.mode)) {
2117 this.switchMode(params.mode);
2120 // $$$ process /search
2121 // $$$ process /zoom
2123 // We only respect page if index is not set
2124 if ('undefined' != typeof(params.index)) {
2125 if (params.index != this.currentIndex()) {
2126 this.jumpToIndex(params.index);
2128 } else if ('undefined' != typeof(params.page)) {
2129 // $$$ this assumes page numbers are unique
2130 if (params.page != this.getPageNum(this.currentIndex())) {
2131 this.jumpToPage(params.page);
2135 // $$$ process /region
2136 // $$$ process /highlight
2139 // paramsFromFragment(urlFragment)
2141 // Returns a object with configuration parametes from a URL fragment.
2143 // E.g paramsFromFragment(window.location.hash)
2144 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2145 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2149 // For convenience we allow an initial # character (as from window.location.hash)
2150 // but don't require it
2151 if (urlFragment.substr(0,1) == '#') {
2152 urlFragment = urlFragment.substr(1);
2155 // Simple #nn syntax
2156 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2157 if ( !isNaN(oldStyleLeafNum) ) {
2158 params.index = oldStyleLeafNum;
2160 // Done processing if using old-style syntax
2164 // Split into key-value pairs
2165 var urlArray = urlFragment.split('/');
2167 for (var i = 0; i < urlArray.length; i += 2) {
2168 urlHash[urlArray[i]] = urlArray[i+1];
2172 if ('1up' == urlHash['mode']) {
2173 params.mode = this.constMode1up;
2174 } else if ('2up' == urlHash['mode']) {
2175 params.mode = this.constMode2up;
2179 if ('undefined' != typeof(urlHash['page'])) {
2180 // page was set -- may not be int
2181 params.page = urlHash['page'];
2184 // $$$ process /region
2185 // $$$ process /search
2186 // $$$ process /highlight
2191 // paramsFromCurrent()
2193 // Create a params object from the current parameters.
2194 GnuBook.prototype.paramsFromCurrent = function() {
2198 var pageNum = this.getPageNum(this.currentIndex());
2199 if ((pageNum === 0) || pageNum) {
2200 params.page = pageNum;
2203 params.index = this.currentIndex();
2204 params.mode = this.mode;
2213 // fragmentFromParams(params)
2215 // Create a fragment string from the params object.
2216 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2217 GnuBook.prototype.fragmentFromParams = function(params) {
2218 var separator = '/';
2222 if ('undefined' != typeof(params.page)) {
2223 fragments.push('page', params.page);
2225 // Don't have page numbering -- use index instead
2226 fragments.push('page', 'n' + params.index);
2234 if ('undefined' != typeof(params.mode)) {
2235 if (params.mode == this.constMode1up) {
2236 fragments.push('mode', '1up');
2237 } else if (params.mode == this.constMode2up) {
2238 fragments.push('mode', '2up');
2240 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2244 return fragments.join(separator);
2247 // getPageIndex(pageNum)
2249 // Returns the *highest* index the given page number, or undefined
2250 GnuBook.prototype.getPageIndex = function(pageNum) {
2251 var pageIndices = this.getPageIndices(pageNum);
2253 if (pageIndices.length > 0) {
2254 return pageIndices[pageIndices.length - 1];
2260 // getPageIndices(pageNum)
2262 // Returns an array (possibly empty) of the indices with the given page number
2263 GnuBook.prototype.getPageIndices = function(pageNum) {
2266 // Check for special "nXX" page number
2267 if (pageNum.slice(0,1) == 'n') {
2269 var pageIntStr = pageNum.slice(1, pageNum.length);
2270 var pageIndex = parseInt(pageIntStr);
2271 indices.append(pageIndex);
2274 // Do nothing... will run through page names and see if one matches
2279 for (i=0; i<this.numLeafs; i++) {
2280 if (this.getPageNum(i) == pageNum) {
2288 // getPageName(index)
2290 // Returns the name of the page as it should be displayed in the user interface
2291 GnuBook.prototype.getPageName = function(index) {
2292 return 'Page ' + this.getPageNum(index);
2295 // updateLocationHash
2297 // Update the location hash from the current parameters. Call this instead of manually
2298 // using window.location.replace
2299 GnuBook.prototype.updateLocationHash = function() {
2300 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2301 window.location.replace(newHash);
2303 // This is the variable checked in the timer. Only user-generated changes
2304 // to the URL will trigger the event.
2305 this.oldLocationHash = newHash;
2308 // startLocationPolling
2310 // Starts polling of window.location to see hash fragment changes
2311 GnuBook.prototype.startLocationPolling = function() {
2312 var self = this; // remember who I am
2313 self.oldLocationHash = window.location.hash;
2315 if (this.locationPollId) {
2316 clearInterval(this.locationPollID);
2317 this.locationPollId = null;
2320 this.locationPollId = setInterval(function() {
2321 var newHash = window.location.hash;
2322 if (newHash != self.oldLocationHash) {
2323 if (newHash != self.oldUserHash) { // Only process new user hash once
2324 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2326 // Queue change if animating
2327 if (self.animating) {
2329 self.animationFinishedCallback = function() {
2330 self.updateFromParams(self.paramsFromFragment(newHash));
2332 } else { // update immediately
2333 self.updateFromParams(self.paramsFromFragment(newHash));
2335 self.oldUserHash = newHash;
2343 // Returns a URL for an embedded version of the current book
2344 GnuBook.prototype.getEmbedURL = function() {
2345 // We could generate a URL hash fragment here but for now we just leave at defaults
2346 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2351 // Returns the embed code HTML fragment suitable for copy and paste
2352 GnuBook.prototype.getEmbedCode = function() {
2353 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2356 GnuBook.prototype.canSwitchToMode = function(mode) {
2357 if (mode == this.constMode2up) {
2358 // check there are enough pages to display
2359 // $$$ this is a workaround for the mis-feature that we can't display
2360 // short books in 2up mode
2361 if (this.numLeafs < 6) {
2369 // Library functions
2371 clamp: function(value, min, max) {
2372 return Math.min(Math.max(value, min), max);