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 $("#GnuBook").empty();
106 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
107 $("#GnuBook").append("<div id='GBcontainer'></div>");
108 $("#GBcontainer").append("<div id='GBpageview'></div>");
110 $("#GBcontainer").bind('scroll', this, function(e) {
114 this.setupKeyListeners();
115 this.startLocationPolling();
117 $(window).bind('resize', this, function(e) {
118 //console.log('resize!');
119 if (1 == e.data.mode) {
120 //console.log('centering 1page view');
121 e.data.centerPageView();
122 $('#GBpageview').empty()
123 e.data.displayedIndices = [];
124 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
127 //console.log('drawing 2 page view');
128 e.data.prepareTwoPageView();
132 $('.GBpagediv1up').bind('mousedown', this, function(e) {
133 //console.log('mousedown!');
136 if (1 == this.mode) {
137 this.resizePageView();
138 this.firstIndex = startIndex;
139 this.jumpToIndex(startIndex);
141 //this.resizePageView();
143 this.displayedIndices=[0];
144 this.firstIndex = startIndex;
145 this.displayedIndices = [this.firstIndex];
146 //console.log('titleLeaf: %d', this.titleLeaf);
147 //console.log('displayedIndices: %s', this.displayedIndices);
148 this.prepareTwoPageView();
149 //if (this.auto) this.nextPage();
152 // Enact other parts of initial params
153 this.updateFromParams(params);
156 GnuBook.prototype.setupKeyListeners = function() {
169 // We use document here instead of window to avoid a bug in jQuery on IE7
170 $(document).keydown(function(e) {
172 // Keyboard navigation
176 // In 1up mode page scrolling is handled by browser
177 if (2 == self.mode) {
183 if (2 == self.mode) {
194 if (self.keyboardNavigationIsDisabled(e)) {
197 if (2 == self.mode) {
202 if (self.keyboardNavigationIsDisabled(e)) {
205 if (2 == self.mode) {
214 //______________________________________________________________________________
215 GnuBook.prototype.drawLeafs = function() {
216 if (1 == this.mode) {
217 this.drawLeafsOnePage();
219 this.drawLeafsTwoPage();
223 // setDragHandler1up()
224 //______________________________________________________________________________
225 GnuBook.prototype.setDragHandler1up = function(div) {
226 div.dragging = false;
228 $(div).bind('mousedown', function(e) {
229 //console.log('mousedown at ' + e.pageY);
231 this.dragging = true;
232 this.prevMouseX = e.pageX;
233 this.prevMouseY = e.pageY;
235 var startX = e.pageX;
236 var startY = e.pageY;
237 var startTop = $('#GBcontainer').attr('scrollTop');
238 var startLeft = $('#GBcontainer').attr('scrollLeft');
243 $(div).bind('mousemove', function(ee) {
244 //console.log('mousemove ' + startY);
246 var offsetX = ee.pageX - this.prevMouseX;
247 var offsetY = ee.pageY - this.prevMouseY;
250 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
251 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
254 this.prevMouseX = ee.pageX;
255 this.prevMouseY = ee.pageY;
260 $(div).bind('mouseup', function(ee) {
261 //console.log('mouseup');
263 this.dragging = false;
267 $(div).bind('mouseleave', function(e) {
268 //console.log('mouseleave');
270 //$(this).unbind('mousemove mouseup');
271 this.dragging = false;
276 // drawLeafsOnePage()
277 //______________________________________________________________________________
278 GnuBook.prototype.drawLeafsOnePage = function() {
279 //alert('drawing leafs!');
283 var scrollTop = $('#GBcontainer').attr('scrollTop');
284 var scrollBottom = scrollTop + $('#GBcontainer').height();
285 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
287 var indicesToDisplay = [];
292 for (i=0; i<this.numLeafs; i++) {
293 var height = parseInt(this.getPageHeight(i)/this.reduce);
295 leafBottom += height;
296 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
297 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
298 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
299 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
300 if (topInView | bottomInView | middleInView) {
301 //console.log('displayed: ' + this.displayedIndices);
302 //console.log('to display: ' + i);
303 indicesToDisplay.push(i);
305 leafTop += height +10;
309 var firstIndexToDraw = indicesToDisplay[0];
310 this.firstIndex = firstIndexToDraw;
312 // Update hash, but only if we're currently displaying a leaf
313 // Hack that fixes #365790
314 if (this.displayedIndices.length > 0) {
315 this.updateLocationHash();
318 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
320 indicesToDisplay.unshift(firstIndexToDraw);
323 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
324 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
325 indicesToDisplay.push(lastIndexToDraw+1);
330 for (i=0; i<firstIndexToDraw; i++) {
331 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
334 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
335 var viewWidth = $('#GBcontainer').attr('scrollWidth');
338 for (i=0; i<indicesToDisplay.length; i++) {
339 var index = indicesToDisplay[i];
340 var height = parseInt(this.getPageHeight(index)/this.reduce);
342 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
343 var width = parseInt(this.getPageWidth(index)/this.reduce);
344 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
345 var div = document.createElement("div");
346 div.className = 'GBpagediv1up';
347 div.id = 'pagediv'+index;
348 div.style.position = "absolute";
349 $(div).css('top', leafTop + 'px');
350 var left = (viewWidth-width)>>1;
351 if (left<0) left = 0;
352 $(div).css('left', left+'px');
353 $(div).css('width', width+'px');
354 $(div).css('height', height+'px');
355 //$(div).text('loading...');
357 this.setDragHandler1up(div);
359 $('#GBpageview').append(div);
361 var img = document.createElement("img");
362 img.src = this.getPageURI(index);
363 $(img).css('width', width+'px');
364 $(img).css('height', height+'px');
368 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
371 leafTop += height +10;
375 for (i=0; i<this.displayedIndices.length; i++) {
376 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
377 var index = this.displayedIndices[i];
378 //console.log('Removing leaf ' + index);
379 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
380 $('#pagediv'+index).remove();
382 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
386 this.displayedIndices = indicesToDisplay.slice();
387 this.updateSearchHilites();
389 if (null != this.getPageNum(firstIndexToDraw)) {
390 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
392 $("#GBpagenum").val('');
396 // drawLeafsTwoPage()
397 //______________________________________________________________________________
398 GnuBook.prototype.drawLeafsTwoPage = function() {
399 //alert('drawing two leafs!');
401 var scrollTop = $('#GBcontainer').attr('scrollTop');
402 var scrollBottom = scrollTop + $('#GBcontainer').height();
404 //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentIndexL);
406 var index = this.currentIndexL;
407 var height = this.getPageHeight(index);
408 var width = this.getPageWidth(index);
409 var handSide= this.getPageSide(index);
411 var leafEdgeWidthL = this.leafEdgeWidth(index);
412 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
413 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
414 var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
415 //console.log(leafEdgeWidthL);
417 var middle = ($('#GBcontainer').width() >> 1);
418 var left = middle - this.twoPageW;
419 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
421 var scaledW = parseInt(this.twoPageH*width/height);
422 left = 10+leafEdgeWidthL;
423 //var right = left+scaledW;
424 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
426 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
428 this.prefetchImg(index);
429 $(this.prefetchedImgs[index]).css({
430 position: 'absolute',
431 /*right: gutter+'px',*/
432 left: gutter-scaledW+'px',
435 backgroundColor: 'rgb(234, 226, 205)',
436 height: this.twoPageH +'px',
437 width: scaledW + 'px',
438 borderRight: '1px solid black',
440 }).appendTo('#GBcontainer');
441 //$('#GBcontainer').append(this.prefetchedImgs[index]);
444 var index = this.currentIndexR;
445 var height = this.getPageHeight(index);
446 var width = this.getPageWidth(index);
447 // var left = ($('#GBcontainer').width() >> 1);
450 var scaledW = this.twoPageH*width/height;
451 this.prefetchImg(index);
452 $(this.prefetchedImgs[index]).css({
453 position: 'absolute',
457 backgroundColor: 'rgb(234, 226, 205)',
458 height: this.twoPageH + 'px',
459 width: scaledW + 'px',
460 borderLeft: '1px solid black',
462 }).appendTo('#GBcontainer');
463 //$('#GBcontainer').append(this.prefetchedImgs[index]);
466 this.displayedIndices = [this.currentIndexL, this.currentIndexR];
467 this.setClickHandlers();
469 this.updatePageNumBox2UP();
472 // updatePageNumBox2UP
473 //______________________________________________________________________________
474 GnuBook.prototype.updatePageNumBox2UP = function() {
475 if (null != this.getPageNum(this.currentIndexL)) {
476 $("#GBpagenum").val(this.getPageNum(this.currentIndexL));
478 $("#GBpagenum").val('');
480 this.updateLocationHash();
484 //______________________________________________________________________________
485 GnuBook.prototype.loadLeafs = function() {
489 if (null == this.timer) {
490 this.timer=setTimeout(function(){self.drawLeafs()},250);
492 clearTimeout(this.timer);
493 this.timer=setTimeout(function(){self.drawLeafs()},250);
499 //______________________________________________________________________________
500 GnuBook.prototype.zoom1up = function(dir) {
501 if (2 == this.mode) { //can only zoom in 1-page mode
507 if (this.reduce <= 0.5) return;
508 this.reduce*=0.5; //zoom in
510 if (this.reduce >= 8) return;
511 this.reduce*=2; //zoom out
514 this.resizePageView();
516 $('#GBpageview').empty()
517 this.displayedIndices = [];
520 $('#GBzoom').text(100/this.reduce);
524 //______________________________________________________________________________
525 GnuBook.prototype.resizePageView = function() {
528 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
529 var viewWidth = $('#GBcontainer').attr('clientWidth');
531 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
532 var oldViewHeight = $('#GBpageview').height();
533 if (0 != oldViewHeight) {
534 var scrollRatio = oldScrollTop / oldViewHeight;
539 for (i=0; i<this.numLeafs; i++) {
540 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
541 var width = parseInt(this.getPageWidth(i)/this.reduce);
542 if (width>viewWidth) viewWidth=width;
544 $('#GBpageview').height(viewHeight);
545 $('#GBpageview').width(viewWidth);
547 $('#GBcontainer').attr('scrollTop', Math.floor(scrollRatio*viewHeight));
549 this.centerPageView();
555 //______________________________________________________________________________
556 GnuBook.prototype.centerPageView = function() {
558 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
559 var clientWidth = $('#GBcontainer').attr('clientWidth');
560 //console.log('sW='+scrollWidth+' cW='+clientWidth);
561 if (scrollWidth > clientWidth) {
562 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
568 //______________________________________________________________________________
569 // Attempts to jump to page. Returns true if page could be found, false otherwise.
570 GnuBook.prototype.jumpToPage = function(pageNum) {
572 var pageIndex = this.getPageIndex(pageNum);
574 if ('undefined' != typeof(pageIndex)) {
577 this.jumpToIndex(pageIndex);
578 $('#GBcontainer').attr('scrollTop', leafTop);
587 //______________________________________________________________________________
588 GnuBook.prototype.jumpToIndex = function(index) {
590 if (2 == this.mode) {
593 // By checking against min/max we do nothing if requested index
595 if (index < Math.min(this.currentIndexL, this.currentIndexR)) {
596 this.flipBackToIndex(index);
597 } else if (index > Math.max(this.currentIndexL, this.currentIndexR)) {
598 this.flipFwdToIndex(index);
605 for (i=0; i<index; i++) {
606 h = parseInt(this.getPageHeight(i)/this.reduce);
607 leafTop += h + this.padding;
609 //$('#GBcontainer').attr('scrollTop', leafTop);
610 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
617 //______________________________________________________________________________
618 GnuBook.prototype.switchMode = function(mode) {
620 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
622 if (mode == this.mode) return;
625 this.removeSearchHilites();
629 this.switchToolbarMode(mode);
632 this.prepareOnePageView();
634 this.prepareTwoPageView();
639 //prepareOnePageView()
640 //______________________________________________________________________________
641 GnuBook.prototype.prepareOnePageView = function() {
643 // var startLeaf = this.displayedIndices[0];
644 var startLeaf = this.currentIndex();
646 $('#GBcontainer').empty();
647 $('#GBcontainer').css({
652 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
653 this.resizePageView();
655 this.jumpToIndex(startLeaf);
656 this.displayedIndices = [];
658 this.drawLeafsOnePage();
659 $('#GBzoom').text(100/this.reduce);
661 // Bind mouse handlers
662 // Disable mouse click to avoid selected/highlighted page images - bug 354239
663 gbPageView.bind('mousedown', function(e) {
666 // Special hack for IE7
667 gbPageView[0].onselectstart = function(e) { return false; };
670 // prepareTwoPageView()
671 //______________________________________________________________________________
672 GnuBook.prototype.prepareTwoPageView = function() {
673 $('#GBcontainer').empty();
675 // We want to display two facing pages. We may be missing
676 // one side of the spread because it is the first/last leaf,
677 // foldouts, missing pages, etc
679 //var targetLeaf = this.displayedIndices[0];
680 var targetLeaf = this.firstIndex;
682 if (targetLeaf < this.firstDisplayableIndex()) {
683 targetLeaf = this.firstDisplayableIndex();
686 if (targetLeaf > this.lastDisplayableIndex()) {
687 targetLeaf = this.lastDisplayableIndex();
690 this.currentIndexL = null;
691 this.currentIndexR = null;
692 this.pruneUnusedImgs();
694 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
695 this.currentIndexL = currentSpreadIndices[0];
696 this.currentIndexR = currentSpreadIndices[1];
697 this.firstIndex = this.currentIndexL;
699 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
701 // We want to minimize the unused space in two-up mode (maximize the amount of page
702 // shown). We give width to the leaf edges and these widths change (though the sum
703 // of the two remains constant) as we flip through the book. With the book
704 // cover centered and fixed in the GBcontainer div the page images will meet
705 // at the "gutter" which is generally offset from the center.
706 var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
707 //var gutter = middle+parseInt((2*this.currentIndexL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
709 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
711 var scaledWL = this.getPageWidth2UP(this.currentIndexL);
712 var scaledWR = this.getPageWidth2UP(this.currentIndexR);
713 var leafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
714 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
716 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
717 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
719 // The width of the book cover div. The combined width of both pages, twice the width
720 // of the book cover internal padding (2*10) and the page edges
721 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
723 // The height of the book cover div
724 var bookCoverDivHeight = this.twoPageH+20;
726 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
727 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
728 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
729 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
731 this.twoPageDiv = document.createElement('div');
732 $(this.twoPageDiv).attr('id', 'book_div_1').css({
733 border: '1px solid rgb(68, 25, 17)',
734 width: bookCoverDivWidth + 'px',
735 height: bookCoverDivHeight+'px',
736 visibility: 'visible',
737 position: 'absolute',
738 backgroundColor: '#663929',
739 left: bookCoverDivLeft + 'px',
740 top: bookCoverDivTop+'px',
741 MozBorderRadiusTopleft: '7px',
742 MozBorderRadiusTopright: '7px',
743 MozBorderRadiusBottomright: '7px',
744 MozBorderRadiusBottomleft: '7px'
745 }).appendTo('#GBcontainer');
746 //$('#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;"/>');
749 var height = this.getPageHeight(this.currentIndexR);
750 var width = this.getPageWidth(this.currentIndexR);
751 var scaledW = this.twoPageH*width/height;
753 this.leafEdgeR = document.createElement('div');
754 this.leafEdgeR.className = 'leafEdgeR';
755 $(this.leafEdgeR).css({
756 borderStyle: 'solid solid solid none',
757 borderColor: 'rgb(51, 51, 34)',
758 borderWidth: '1px 1px 1px 0px',
759 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
760 width: leafEdgeWidthR + 'px',
761 height: this.twoPageH-1 + 'px',
763 left: gutter+scaledW+'px',
764 top: bookCoverDivTop+10+'px',
766 }).appendTo('#GBcontainer');
768 this.leafEdgeL = document.createElement('div');
769 this.leafEdgeL.className = 'leafEdgeL';
770 $(this.leafEdgeL).css({
771 borderStyle: 'solid none solid solid',
772 borderColor: 'rgb(51, 51, 34)',
773 borderWidth: '1px 0px 1px 1px',
774 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
775 width: leafEdgeWidthL + 'px',
776 height: this.twoPageH-1 + 'px',
777 left: bookCoverDivLeft+10+'px',
778 top: bookCoverDivTop+10+'px',
780 }).appendTo('#GBcontainer');
784 bookCoverDivWidth = 30;
785 bookCoverDivHeight = this.twoPageH+20;
786 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
787 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
789 div = document.createElement('div');
790 $(div).attr('id', 'book_div_2').css({
791 border: '1px solid rgb(68, 25, 17)',
792 width: bookCoverDivWidth+'px',
793 height: bookCoverDivHeight+'px',
794 position: 'absolute',
795 backgroundColor: 'rgb(68, 25, 17)',
796 left: bookCoverDivLeft+'px',
797 top: bookCoverDivTop+'px'
798 }).appendTo('#GBcontainer');
799 //$('#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;"/>');
801 bookCoverDivWidth = this.twoPageW*2;
802 bookCoverDivHeight = this.twoPageH;
803 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
804 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
807 this.prepareTwoPagePopUp();
809 this.displayedIndices = [];
811 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
812 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
814 this.drawLeafsTwoPage();
815 this.updateSearchHilites2UP();
818 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentIndexL)).toString().substr(0,4));
821 // prepareTwoPagePopUp()
823 // This function prepares the "View Page n" popup that shows while the mouse is
824 // over the left/right "stack of sheets" edges. It also binds the mouse
825 // events for these divs.
826 //______________________________________________________________________________
827 GnuBook.prototype.prepareTwoPagePopUp = function() {
828 this.twoPagePopUp = document.createElement('div');
829 $(this.twoPagePopUp).css({
830 border: '1px solid black',
832 position: 'absolute',
833 fontFamily: 'sans-serif',
836 backgroundColor: 'rgb(255, 255, 238)',
838 }).appendTo('#GBcontainer');
839 $(this.twoPagePopUp).hide();
841 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
842 $(e.data.twoPagePopUp).show();
845 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
846 $(e.data.twoPagePopUp).hide();
849 $(this.leafEdgeL).bind('click', this, function(e) {
851 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
852 e.data.jumpToIndex(jumpIndex);
855 $(this.leafEdgeR).bind('click', this, function(e) {
857 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
858 e.data.jumpToIndex(jumpIndex);
861 $(this.leafEdgeR).bind('mousemove', this, function(e) {
863 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
864 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
866 $(e.data.twoPagePopUp).css({
867 left: e.pageX +5+ 'px',
868 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
872 $(this.leafEdgeL).bind('mousemove', this, function(e) {
874 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
875 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
877 $(e.data.twoPagePopUp).css({
878 left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
879 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
884 // calculateSpreadSize()
885 //______________________________________________________________________________
886 // Calculates 2-page spread dimensions based on this.currentIndexL and
887 // this.currentIndexR
888 // This function sets this.twoPageH, twoPageW, and twoPageRatio
890 GnuBook.prototype.calculateSpreadSize = function() {
891 var firstIndex = this.currentIndexL;
892 var secondIndex = this.currentIndexR;
893 //console.log('first page is ' + firstIndex);
895 var canon5Dratio = 1.5;
897 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
898 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
899 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
902 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
903 ratio = firstIndexRatio;
904 //console.log('using firstIndexRatio ' + ratio);
906 ratio = secondIndexRatio;
907 //console.log('using secondIndexRatio ' + ratio);
910 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
911 var maxLeafEdgeWidth = parseInt($('#GBcontainer').width() * 0.1);
912 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
914 $('#GBcontainer').css('overflow', 'hidden');
916 var idealWidth = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
917 var idealHeight = $('#GBcontainer').height() - 30;
918 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
920 if (idealHeight/ratio <= idealWidth) {
922 idealWidth = parseInt(idealHeight/ratio);
925 idealHeight = parseInt(idealWidth*ratio);
928 this.twoPageH = idealHeight;
929 this.twoPageW = idealWidth;
930 this.twoPageRatio = ratio;
931 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
936 //______________________________________________________________________________
937 // Returns the currently active index.
938 GnuBook.prototype.currentIndex = function() {
939 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
940 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
941 return this.firstIndex;
943 throw 'currentIndex called for unimplemented mode ' + this.mode;
948 //______________________________________________________________________________
949 // Flip the right page over onto the left
950 GnuBook.prototype.right = function() {
951 if ('rl' != this.pageProgression) {
961 //______________________________________________________________________________
962 // Flip to the rightmost page
963 GnuBook.prototype.rightmost = function() {
964 if ('rl' != this.pageProgression) {
972 //______________________________________________________________________________
973 // Flip the left page over onto the right.
974 GnuBook.prototype.left = function() {
975 if ('rl' != this.pageProgression) {
985 //______________________________________________________________________________
986 // Flip to the leftmost page
987 GnuBook.prototype.leftmost = function() {
988 if ('rl' != this.pageProgression) {
996 //______________________________________________________________________________
997 GnuBook.prototype.next = function() {
998 if (2 == this.mode) {
1000 this.flipFwdToIndex(null);
1002 if (this.firstIndex < this.lastDisplayableIndex()) {
1003 this.jumpToIndex(this.firstIndex+1);
1009 //______________________________________________________________________________
1010 GnuBook.prototype.prev = function() {
1011 if (2 == this.mode) {
1013 this.flipBackToIndex(null);
1015 if (this.firstIndex >= 1) {
1016 this.jumpToIndex(this.firstIndex-1);
1021 GnuBook.prototype.first = function() {
1022 if (2 == this.mode) {
1023 this.jumpToIndex(2);
1026 this.jumpToIndex(0);
1030 GnuBook.prototype.last = function() {
1031 if (2 == this.mode) {
1032 this.jumpToIndex(this.lastDisplayableIndex());
1035 this.jumpToIndex(this.lastDisplayableIndex());
1039 // flipBackToIndex()
1040 //______________________________________________________________________________
1041 // to flip back one spread, pass index=null
1042 GnuBook.prototype.flipBackToIndex = function(index) {
1043 if (1 == this.mode) return;
1045 var leftIndex = this.currentIndexL;
1047 // $$$ Need to change this to be able to see first spread.
1048 // See https://bugs.launchpad.net/gnubook/+bug/296788
1049 if (leftIndex <= 2) return;
1050 if (this.animating) return;
1052 if (null != this.leafEdgeTmp) {
1053 alert('error: leafEdgeTmp should be null!');
1057 if (null == index) {
1058 index = leftIndex-2;
1060 //if (index<0) return;
1062 var previousIndices = this.getSpreadIndices(index);
1064 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1068 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1070 this.animating = true;
1072 if ('rl' != this.pageProgression) {
1073 // Assume LTR and we are going backward
1074 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1075 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1078 // RTL and going backward
1079 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1080 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1084 // flipLeftToRight()
1085 //______________________________________________________________________________
1086 // Flips the page on the left towards the page on the right
1087 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1089 var leftLeaf = this.currentIndexL;
1091 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1092 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1093 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1095 var currWidthL = this.getPageWidth2UP(leftLeaf);
1096 var newWidthL = this.getPageWidth2UP(newIndexL);
1097 var newWidthR = this.getPageWidth2UP(newIndexR);
1099 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1101 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1102 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1104 //animation strategy:
1105 // 0. remove search highlight, if any.
1106 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1107 // of the left leaf and where the user clicked in the leaf edge.
1108 // Note that if this function was triggered by left() and not a
1109 // mouse click, the width of leafEdgeTmp is very small (zero px).
1110 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1111 // leftLeaf to width=0.
1112 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1113 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1114 // its new full width.
1115 // 4. After step 3 is finished, do the following:
1116 // - remove leafEdgeTmp from the dom.
1117 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1118 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1119 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1120 // and width=newLeafEdgeWidthL.
1121 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1122 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1123 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1124 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1125 // - prefetch new adjacent leafs.
1126 // - set up click handlers for both new left and right leafs.
1127 // - redraw the search highlight.
1128 // - update the pagenum box and the url.
1131 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1133 this.leafEdgeTmp = document.createElement('div');
1134 $(this.leafEdgeTmp).css({
1135 borderStyle: 'solid none solid solid',
1136 borderColor: 'rgb(51, 51, 34)',
1137 borderWidth: '1px 0px 1px 1px',
1138 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1139 width: leafEdgeTmpW + 'px',
1140 height: this.twoPageH-1 + 'px',
1141 left: leftEdgeTmpLeft + 'px',
1143 position: 'absolute',
1145 }).appendTo('#GBcontainer');
1147 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1148 $(this.leafEdgeL).css({
1149 width: newLeafEdgeWidthL+'px',
1150 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1153 // Left gets the offset of the current left leaf from the document
1154 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1155 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1156 var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1157 // We change the left leaf to right positioning
1158 $(this.prefetchedImgs[leftLeaf]).css({
1163 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1165 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1167 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1168 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1172 this.removeSearchHilites();
1174 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1175 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1177 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1178 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1180 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1181 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1182 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1184 $(self.leafEdgeR).css({
1185 // Moves the right leaf edge
1186 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1187 left: gutter+newWidthR+'px'
1190 $(self.leafEdgeL).css({
1191 // Moves and resizes the left leaf edge
1192 width: newLeafEdgeWidthL+'px',
1193 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1197 $(self.twoPageDiv).css({
1198 // Resizes the brown border div
1199 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1200 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1203 $(self.leafEdgeTmp).remove();
1204 self.leafEdgeTmp = null;
1206 self.currentIndexL = newIndexL;
1207 self.currentIndexR = newIndexR;
1208 self.firstIndex = self.currentIndexL;
1209 self.displayedIndices = [newIndexL, newIndexR];
1210 self.setClickHandlers();
1211 self.pruneUnusedImgs();
1213 self.animating = false;
1215 self.updateSearchHilites2UP();
1216 self.updatePageNumBox2UP();
1217 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1219 if (self.animationFinishedCallback) {
1220 self.animationFinishedCallback();
1221 self.animationFinishedCallback = null;
1229 //______________________________________________________________________________
1230 // Whether we flip left or right is dependent on the page progression
1231 // to flip forward one spread, pass index=null
1232 GnuBook.prototype.flipFwdToIndex = function(index) {
1234 if (this.animating) return;
1236 if (null != this.leafEdgeTmp) {
1237 alert('error: leafEdgeTmp should be null!');
1241 if (null == index) {
1242 index = this.currentIndexR+2; // $$$ assumes indices are continuous
1244 if (index > this.lastDisplayableIndex()) return;
1246 this.animating = true;
1248 var nextIndices = this.getSpreadIndices(index);
1250 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1252 if ('rl' != this.pageProgression) {
1253 // We did not specify RTL
1254 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1255 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1258 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1259 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1263 // flipRightToLeft(nextL, nextR, gutter)
1264 // $$$ better not to have to pass gutter in
1265 //______________________________________________________________________________
1266 // Flip from left to right and show the nextL and nextR indices on those sides
1267 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1268 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1269 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1270 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1271 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1273 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1275 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1277 var scaledW = this.getPageWidth2UP(this.currentIndexR);
1279 var middle = ($('#GBcontainer').width() >> 1);
1280 var currGutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1282 this.leafEdgeTmp = document.createElement('div');
1283 $(this.leafEdgeTmp).css({
1284 borderStyle: 'solid none solid solid',
1285 borderColor: 'rgb(51, 51, 34)',
1286 borderWidth: '1px 0px 1px 1px',
1287 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1288 width: leafEdgeTmpW + 'px',
1289 height: this.twoPageH-1 + 'px',
1290 left: currGutter+scaledW+'px',
1292 position: 'absolute',
1294 }).appendTo('#GBcontainer');
1296 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1297 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1299 var currWidthL = this.getPageWidth2UP(this.currentIndexL);
1300 var currWidthR = this.getPageWidth2UP(this.currentIndexR);
1301 var newWidthL = this.getPageWidth2UP(newIndexL);
1302 var newWidthR = this.getPageWidth2UP(newIndexR);
1304 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1306 var self = this; // closure-tastic!
1308 var speed = this.flipSpeed;
1310 this.removeSearchHilites();
1312 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1313 $(this.prefetchedImgs[this.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1314 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1315 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1316 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1318 $(self.leafEdgeL).css({
1319 width: newLeafEdgeWidthL+'px',
1320 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1323 $(self.twoPageDiv).css({
1324 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1325 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1328 $(self.leafEdgeTmp).remove();
1329 self.leafEdgeTmp = null;
1331 self.currentIndexL = newIndexL;
1332 self.currentIndexR = newIndexR;
1333 self.firstIndex = self.currentIndexL;
1334 self.displayedIndices = [newIndexL, newIndexR];
1335 self.setClickHandlers();
1336 self.pruneUnusedImgs();
1338 self.animating = false;
1341 self.updateSearchHilites2UP();
1342 self.updatePageNumBox2UP();
1343 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1345 if (self.animationFinishedCallback) {
1346 self.animationFinishedCallback();
1347 self.animationFinishedCallback = null;
1354 //______________________________________________________________________________
1355 GnuBook.prototype.setClickHandlers = function() {
1357 $(this.prefetchedImgs[this.currentIndexL]).click(function() {
1362 $(this.prefetchedImgs[this.currentIndexR]).click(function() {
1370 //______________________________________________________________________________
1371 GnuBook.prototype.prefetchImg = function(index) {
1372 if (undefined == this.prefetchedImgs[index]) {
1373 //console.log('prefetching ' + index);
1374 var img = document.createElement("img");
1375 img.src = this.getPageURI(index);
1376 this.prefetchedImgs[index] = img;
1381 // prepareFlipLeftToRight()
1383 //______________________________________________________________________________
1385 // Prepare to flip the left page towards the right. This corresponds to moving
1386 // backward when the page progression is left to right.
1387 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1389 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1391 this.prefetchImg(prevL);
1392 this.prefetchImg(prevR);
1394 var height = this.getPageHeight(prevL);
1395 var width = this.getPageWidth(prevL);
1396 var middle = ($('#GBcontainer').width() >> 1);
1397 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1398 var scaledW = this.twoPageH*width/height;
1400 // The gutter is the dividing line between the left and right pages.
1401 // It is offset from the middle to create the illusion of thickness to the pages
1402 var gutter = middle + this.gutterOffsetForIndex(prevL);
1404 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1405 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1406 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1408 $(this.prefetchedImgs[prevL]).css({
1409 position: 'absolute',
1410 /*right: middle+'px',*/
1411 left: gutter-scaledW+'px',
1414 backgroundColor: 'rgb(234, 226, 205)',
1415 height: this.twoPageH,
1416 width: scaledW+'px',
1417 borderRight: '1px solid black',
1421 $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1423 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1425 $(this.prefetchedImgs[prevR]).css({
1426 position: 'absolute',
1430 backgroundColor: 'rgb(234, 226, 205)',
1431 height: this.twoPageH,
1433 borderLeft: '1px solid black',
1437 $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1444 // prepareFlipRightToLeft()
1445 //______________________________________________________________________________
1446 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1448 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1450 this.prefetchImg(nextL);
1451 this.prefetchImg(nextR);
1453 var height = this.getPageHeight(nextR);
1454 var width = this.getPageWidth(nextR);
1455 var middle = ($('#GBcontainer').width() >> 1);
1456 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1457 var scaledW = this.twoPageH*width/height;
1459 var gutter = middle + this.gutterOffsetForIndex(nextL);
1461 //console.log('right to left to %d gutter is %d', nextL, gutter);
1463 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1464 $(this.prefetchedImgs[nextR]).css({
1465 position: 'absolute',
1468 backgroundColor: 'rgb(234, 226, 205)',
1469 height: this.twoPageH,
1470 width: scaledW+'px',
1471 borderLeft: '1px solid black',
1475 $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1477 height = this.getPageHeight(nextL);
1478 width = this.getPageWidth(nextL);
1479 scaledW = this.twoPageH*width/height;
1481 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1482 $(this.prefetchedImgs[nextL]).css({
1483 position: 'absolute',
1484 right: $('#GBcontainer').width()-gutter+'px',
1486 backgroundColor: 'rgb(234, 226, 205)',
1487 height: this.twoPageH,
1489 borderRight: '1px solid black',
1493 $('#GBcontainer').append(this.prefetchedImgs[nextL]);
1499 // getNextLeafs() -- NOT RTL AWARE
1500 //______________________________________________________________________________
1501 // GnuBook.prototype.getNextLeafs = function(o) {
1502 // //TODO: we might have two left or two right leafs in a row (damaged book)
1503 // //For now, assume that leafs are contiguous.
1505 // //return [this.currentIndexL+2, this.currentIndexL+3];
1506 // o.L = this.currentIndexL+2;
1507 // o.R = this.currentIndexL+3;
1510 // getprevLeafs() -- NOT RTL AWARE
1511 //______________________________________________________________________________
1512 // GnuBook.prototype.getPrevLeafs = function(o) {
1513 // //TODO: we might have two left or two right leafs in a row (damaged book)
1514 // //For now, assume that leafs are contiguous.
1516 // //return [this.currentIndexL-2, this.currentIndexL-1];
1517 // o.L = this.currentIndexL-2;
1518 // o.R = this.currentIndexL-1;
1521 // pruneUnusedImgs()
1522 //______________________________________________________________________________
1523 GnuBook.prototype.pruneUnusedImgs = function() {
1524 //console.log('current: ' + this.currentIndexL + ' ' + this.currentIndexR);
1525 for (var key in this.prefetchedImgs) {
1526 //console.log('key is ' + key);
1527 if ((key != this.currentIndexL) && (key != this.currentIndexR)) {
1528 //console.log('removing key '+ key);
1529 $(this.prefetchedImgs[key]).remove();
1531 if ((key < this.currentIndexL-4) || (key > this.currentIndexR+4)) {
1532 //console.log('deleting key '+ key);
1533 delete this.prefetchedImgs[key];
1539 //______________________________________________________________________________
1540 GnuBook.prototype.prefetch = function() {
1542 var lim = this.currentIndexL-4;
1544 lim = Math.max(lim, 0);
1545 for (i = lim; i < this.currentIndexL; i++) {
1546 this.prefetchImg(i);
1549 if (this.numLeafs > (this.currentIndexR+1)) {
1550 lim = Math.min(this.currentIndexR+4, this.numLeafs-1);
1551 for (i=this.currentIndexR+1; i<=lim; i++) {
1552 this.prefetchImg(i);
1557 // getPageWidth2UP()
1558 //______________________________________________________________________________
1559 GnuBook.prototype.getPageWidth2UP = function(index) {
1560 var height = this.getPageHeight(index);
1561 var width = this.getPageWidth(index);
1562 return Math.floor(this.twoPageH*width/height);
1566 //______________________________________________________________________________
1567 GnuBook.prototype.search = function(term) {
1568 $('#GnuBookSearchScript').remove();
1569 var script = document.createElement("script");
1570 script.setAttribute('id', 'GnuBookSearchScript');
1571 script.setAttribute("type", "text/javascript");
1572 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath+'/'+this.bookId+'_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1573 document.getElementsByTagName('head')[0].appendChild(script);
1574 $('#GnuBookSearchResults').html('Searching...');
1577 // GBSearchCallback()
1578 //______________________________________________________________________________
1579 GnuBook.prototype.GBSearchCallback = function(txt) {
1581 if (jQuery.browser.msie) {
1582 var dom=new ActiveXObject("Microsoft.XMLDOM");
1586 var parser = new DOMParser();
1587 var dom = parser.parseFromString(txt, "text/xml");
1590 $('#GnuBookSearchResults').empty();
1591 $('#GnuBookSearchResults').append('<ul>');
1593 for (var key in this.searchResults) {
1594 if (null != this.searchResults[key].div) {
1595 $(this.searchResults[key].div).remove();
1597 delete this.searchResults[key];
1600 var pages = dom.getElementsByTagName('PAGE');
1602 if (0 == pages.length) {
1603 // $$$ it would be nice to echo the (sanitized) search result here
1604 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1606 for (var i = 0; i < pages.length; i++){
1607 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1610 var re = new RegExp (/_(\d{4})/);
1611 var reMatch = re.exec(pages[i].getAttribute('file'));
1612 var index = parseInt(reMatch[1], 10);
1613 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1615 var children = pages[i].childNodes;
1617 for (var j=0; j<children.length; j++) {
1618 //console.log(j + ' - ' + children[j].nodeName);
1619 //console.log(children[j].firstChild.nodeValue);
1620 if ('CONTEXT' == children[j].nodeName) {
1621 context += children[j].firstChild.nodeValue;
1622 } else if ('WORD' == children[j].nodeName) {
1623 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1625 var index = this.leafNumToIndex(index);
1626 if (null != index) {
1627 //coordinates are [left, bottom, right, top, [baseline]]
1628 //we'll skip baseline for now...
1629 var coords = children[j].getAttribute('coords').split(',',4);
1630 if (4 == coords.length) {
1631 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1636 var pageName = this.getPageName(index);
1637 //TODO: remove hardcoded instance name
1638 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1641 $('#GnuBookSearchResults').append('</ul>');
1643 this.updateSearchHilites();
1646 // updateSearchHilites()
1647 //______________________________________________________________________________
1648 GnuBook.prototype.updateSearchHilites = function() {
1649 if (2 == this.mode) {
1650 this.updateSearchHilites2UP();
1652 this.updateSearchHilites1UP();
1656 // showSearchHilites1UP()
1657 //______________________________________________________________________________
1658 GnuBook.prototype.updateSearchHilites1UP = function() {
1660 for (var key in this.searchResults) {
1662 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1663 var result = this.searchResults[key];
1664 if(null == result.div) {
1665 result.div = document.createElement('div');
1666 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1667 //console.log('appending ' + key);
1670 width: (result.r-result.l)/this.reduce + 'px',
1671 height: (result.b-result.t)/this.reduce + 'px',
1672 left: (result.l)/this.reduce + 'px',
1673 top: (result.t)/this.reduce +'px'
1677 //console.log(key + ' not displayed');
1678 this.searchResults[key].div=null;
1683 // showSearchHilites2UP()
1684 //______________________________________________________________________________
1685 GnuBook.prototype.updateSearchHilites2UP = function() {
1687 var middle = ($('#GBcontainer').width() >> 1);
1689 for (var key in this.searchResults) {
1690 key = parseInt(key, 10);
1691 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1692 var result = this.searchResults[key];
1693 if(null == result.div) {
1694 result.div = document.createElement('div');
1695 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1696 //console.log('appending ' + key);
1699 var height = this.getPageHeight(key);
1700 var width = this.getPageWidth(key)
1701 var reduce = this.twoPageH/height;
1702 var scaledW = parseInt(width*reduce);
1704 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1706 if ('L' == this.getPageSide(key)) {
1707 var pageL = gutter-scaledW;
1711 var pageT = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1714 width: (result.r-result.l)*reduce + 'px',
1715 height: (result.b-result.t)*reduce + 'px',
1716 left: pageL+(result.l)*reduce + 'px',
1717 top: pageT+(result.t)*reduce +'px'
1721 //console.log(key + ' not displayed');
1722 if (null != this.searchResults[key].div) {
1723 //console.log('removing ' + key);
1724 $(this.searchResults[key].div).remove();
1726 this.searchResults[key].div=null;
1731 // removeSearchHilites()
1732 //______________________________________________________________________________
1733 GnuBook.prototype.removeSearchHilites = function() {
1734 for (var key in this.searchResults) {
1735 if (null != this.searchResults[key].div) {
1736 $(this.searchResults[key].div).remove();
1737 this.searchResults[key].div=null;
1743 //______________________________________________________________________________
1744 GnuBook.prototype.showEmbedCode = function() {
1745 if (null != this.embedPopup) { // check if already showing
1749 this.embedPopup = document.createElement("div");
1750 $(this.embedPopup).css({
1751 position: 'absolute',
1753 left: ($('#GBcontainer').width()-400)/2 + 'px',
1756 border: "3px double #999999",
1758 backgroundColor: "#fff"
1759 }).appendTo('#GnuBook');
1761 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1762 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>';
1763 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1764 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1766 this.embedPopup.innerHTML = htmlStr;
1767 $(this.embedPopup).find('input').bind('click', function() {
1773 //______________________________________________________________________________
1774 GnuBook.prototype.autoToggle = function() {
1776 var bComingFrom1up = false;
1777 if (2 != this.mode) {
1778 bComingFrom1up = true;
1783 if (null == this.autoTimer) {
1784 this.flipSpeed = 2000;
1786 // $$$ Draw events currently cause layout problems when they occur during animation.
1787 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1788 // we workaround for now by not triggering immediate animation in that case.
1789 // See https://bugs.launchpad.net/gnubook/+bug/328327
1790 if (('rl' == this.pageProgression) && bComingFrom1up) {
1791 // don't flip immediately -- wait until timer fires
1794 this.flipFwdToIndex();
1797 $('#GBtoolbar .play').hide();
1798 $('#GBtoolbar .pause').show();
1799 this.autoTimer=setInterval(function(){
1800 if (self.animating) {return;}
1802 if (Math.max(self.currentIndexL, self.currentIndexR) >= self.lastDisplayableIndex()) {
1803 self.flipBackToIndex(1); // $$$ really what we want?
1805 self.flipFwdToIndex();
1814 //______________________________________________________________________________
1815 GnuBook.prototype.autoStop = function() {
1816 if (null != this.autoTimer) {
1817 clearInterval(this.autoTimer);
1818 this.flipSpeed = 'fast';
1819 $('#GBtoolbar .pause').hide();
1820 $('#GBtoolbar .play').show();
1821 this.autoTimer = null;
1825 // keyboardNavigationIsDisabled(event)
1826 // - returns true if keyboard navigation should be disabled for the event
1827 //______________________________________________________________________________
1828 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1829 if (event.target.tagName == "INPUT") {
1835 // gutterOffsetForIndex
1836 //______________________________________________________________________________
1838 // Returns the gutter offset for the spread containing the given index.
1839 // This function supports RTL
1840 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1842 // To find the offset of the gutter from the middle we calculate our percentage distance
1843 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1844 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1846 // But then again for RTL it's the opposite
1847 if ('rl' == this.pageProgression) {
1855 //______________________________________________________________________________
1856 // Returns the width of the leaf edge div for the page with index given
1857 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1858 // $$$ could there be single pixel rounding errors for L vs R?
1859 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1860 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1862 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1866 // jumpIndexForLeftEdgePageX
1867 //______________________________________________________________________________
1868 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1869 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1870 if ('rl' != this.pageProgression) {
1871 // LTR - flipping backward
1872 var jumpIndex = this.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1874 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1875 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexL - 2);
1879 var jumpIndex = this.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1880 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexL + 2, this.lastDisplayableIndex());
1885 // jumpIndexForRightEdgePageX
1886 //______________________________________________________________________________
1887 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1888 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1889 if ('rl' != this.pageProgression) {
1891 var jumpIndex = this.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1892 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexR + 2, this.lastDisplayableIndex());
1895 var jumpIndex = this.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1896 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexR - 2);
1901 GnuBook.prototype.initToolbar = function(mode, ui) {
1902 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1903 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1904 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1905 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1906 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
1907 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1908 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1909 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1912 if (ui == "embed") {
1913 $("#GnuBook a.logo").attr("target","_blank");
1916 // $$$ turn this into a member variable
1917 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1919 // We build in mode 2
1920 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1921 + "<button class='GBicon rollover embed' />"
1922 + "<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>"
1923 + "<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>"
1924 + "<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>"
1925 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1927 this.bindToolbarNavHandlers(jToolbar);
1929 // Setup tooltips -- later we could load these from a file for i18n
1930 var titles = { '.logo': 'Go to Archive.org',
1931 '.zoom_in': 'Zoom in',
1932 '.zoom_out': 'Zoom out',
1933 '.one_page_mode': 'One-page view',
1934 '.two_page_mode': 'Two-page view',
1935 '.embed': 'Embed bookreader',
1936 '.book_left': 'Flip left',
1937 '.book_right': 'Flip right',
1938 '.book_up': 'Page up',
1939 '.book_down': 'Page down',
1942 '.book_top': 'First page',
1943 '.book_bottom': 'Last page'
1945 if ('rl' == this.pageProgression) {
1946 titles['.book_leftmost'] = 'Last page';
1947 titles['.book_rightmost'] = 'First page';
1949 titles['.book_leftmost'] = 'First page';
1950 titles['.book_rightmost'] = 'Last page';
1953 for (var icon in titles) {
1954 jToolbar.find(icon).attr('title', titles[icon]);
1957 // Switch to requested mode -- binds other click handlers
1958 this.switchToolbarMode(mode);
1963 // switchToolbarMode
1964 //______________________________________________________________________________
1965 // Update the toolbar for the given mode (changes navigation buttons)
1966 // $$$ we should soon split the toolbar out into its own module
1967 GnuBook.prototype.switchToolbarMode = function(mode) {
1970 $('#GBtoolbar .GBtoolbarmode2').hide();
1971 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
1974 $('#GBtoolbar .GBtoolbarmode1').hide();
1975 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
1979 // bindToolbarNavHandlers
1980 //______________________________________________________________________________
1981 // Binds the toolbar handlers
1982 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
1984 jToolbar.find('.book_left').bind('click', function(e) {
1989 jToolbar.find('.book_right').bind('click', function(e) {
1994 jToolbar.find('.book_up').bind('click', function(e) {
1999 jToolbar.find('.book_down').bind('click', function(e) {
2004 jToolbar.find('.embed').bind('click', function(e) {
2009 jToolbar.find('.play').bind('click', function(e) {
2014 jToolbar.find('.pause').bind('click', function(e) {
2019 jToolbar.find('.book_top').bind('click', function(e) {
2024 jToolbar.find('.book_bottom').bind('click', function(e) {
2029 jToolbar.find('.book_leftmost').bind('click', function(e) {
2034 jToolbar.find('.book_rightmost').bind('click', function(e) {
2040 // firstDisplayableIndex
2041 //______________________________________________________________________________
2042 // Returns the index of the first visible page, dependent on the mode.
2043 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2044 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2045 GnuBook.prototype.firstDisplayableIndex = function() {
2046 if (this.mode == 0) {
2049 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2053 // lastDisplayableIndex
2054 //______________________________________________________________________________
2055 // Returns the index of the last visible page, dependent on the mode.
2056 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2057 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2058 GnuBook.prototype.lastDisplayableIndex = function() {
2059 if (this.mode == 2) {
2060 if (this.lastDisplayableIndex2up === null) {
2061 // Calculate and cache
2062 var candidate = this.numLeafs - 1;
2063 for ( ; candidate >= 0; candidate--) {
2064 var spreadIndices = this.getSpreadIndices(candidate);
2065 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2069 this.lastDisplayableIndex2up = candidate;
2071 return this.lastDisplayableIndex2up;
2073 return this.numLeafs - 1;
2077 // shortTitle(maximumCharacters)
2079 // Returns a shortened version of the title with the maximum number of characters
2080 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2081 if (this.bookTitle.length < maximumCharacters) {
2082 return this.bookTitle;
2085 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2092 // Parameter related functions
2094 // updateFromParams(params)
2096 // Update ourselves from the params object.
2098 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2099 GnuBook.prototype.updateFromParams = function(params) {
2100 if ('undefined' != typeof(params.mode)) {
2101 this.switchMode(params.mode);
2104 // $$$ process /search
2105 // $$$ process /zoom
2107 // We only respect page if index is not set
2108 if ('undefined' != typeof(params.index)) {
2109 if (params.index != this.currentIndex()) {
2110 this.jumpToIndex(params.index);
2112 } else if ('undefined' != typeof(params.page)) {
2113 // $$$ this assumes page numbers are unique
2114 if (params.page != this.getPageNum(this.currentIndex())) {
2115 this.jumpToPage(params.page);
2119 // $$$ process /region
2120 // $$$ process /highlight
2123 // paramsFromFragment(urlFragment)
2125 // Returns a object with configuration parametes from a URL fragment.
2127 // E.g paramsFromFragment(window.location.hash)
2128 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2129 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2133 // For convenience we allow an initial # character (as from window.location.hash)
2134 // but don't require it
2135 if (urlFragment.substr(0,1) == '#') {
2136 urlFragment = urlFragment.substr(1);
2139 // Simple #nn syntax
2140 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2141 if ( !isNaN(oldStyleLeafNum) ) {
2142 params.index = oldStyleLeafNum;
2144 // Done processing if using old-style syntax
2148 // Split into key-value pairs
2149 var urlArray = urlFragment.split('/');
2151 for (var i = 0; i < urlArray.length; i += 2) {
2152 urlHash[urlArray[i]] = urlArray[i+1];
2156 if ('1up' == urlHash['mode']) {
2157 params.mode = this.constMode1up;
2158 } else if ('2up' == urlHash['mode']) {
2159 params.mode = this.constMode2up;
2163 if ('undefined' != typeof(urlHash['page'])) {
2164 // page was set -- may not be int
2165 params.page = urlHash['page'];
2168 // $$$ process /region
2169 // $$$ process /search
2170 // $$$ process /highlight
2175 // paramsFromCurrent()
2177 // Create a params object from the current parameters.
2178 GnuBook.prototype.paramsFromCurrent = function() {
2182 var pageNum = this.getPageNum(this.currentIndex());
2183 if ((pageNum === 0) || pageNum) {
2184 params.page = pageNum;
2187 params.index = this.currentIndex();
2188 params.mode = this.mode;
2197 // fragmentFromParams(params)
2199 // Create a fragment string from the params object.
2200 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2201 GnuBook.prototype.fragmentFromParams = function(params) {
2202 var separator = '/';
2206 if ('undefined' != typeof(params.page)) {
2207 fragments.push('page', params.page);
2209 // Don't have page numbering -- use index instead
2210 fragments.push('page', 'n' + params.index);
2218 if ('undefined' != typeof(params.mode)) {
2219 if (params.mode == this.constMode1up) {
2220 fragments.push('mode', '1up');
2221 } else if (params.mode == this.constMode2up) {
2222 fragments.push('mode', '2up');
2224 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2228 return fragments.join(separator);
2231 // getPageIndex(pageNum)
2233 // Returns the *highest* index the given page number, or undefined
2234 GnuBook.prototype.getPageIndex = function(pageNum) {
2235 var pageIndices = this.getPageIndices(pageNum);
2237 if (pageIndices.length > 0) {
2238 return pageIndices[pageIndices.length - 1];
2244 // getPageIndices(pageNum)
2246 // Returns an array (possibly empty) of the indices with the given page number
2247 GnuBook.prototype.getPageIndices = function(pageNum) {
2250 // Check for special "nXX" page number
2251 if (pageNum.slice(0,1) == 'n') {
2253 var pageIntStr = pageNum.slice(1, pageNum.length);
2254 var pageIndex = parseInt(pageIntStr);
2255 indices.append(pageIndex);
2258 // Do nothing... will run through page names and see if one matches
2263 for (i=0; i<this.numLeafs; i++) {
2264 if (this.getPageNum(i) == pageNum) {
2272 // getPageName(index)
2274 // Returns the name of the page as it should be displayed in the user interface
2275 GnuBook.prototype.getPageName = function(index) {
2276 return 'Page ' + this.getPageNum(index);
2279 // updateLocationHash
2281 // Update the location hash from the current parameters. Call this instead of manually
2282 // using window.location.replace
2283 GnuBook.prototype.updateLocationHash = function() {
2284 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2285 window.location.replace(newHash);
2287 // This is the variable checked in the timer. Only user-generated changes
2288 // to the URL will trigger the event.
2289 this.oldLocationHash = newHash;
2292 // startLocationPolling
2294 // Starts polling of window.location to see hash fragment changes
2295 GnuBook.prototype.startLocationPolling = function() {
2296 var self = this; // remember who I am
2297 self.oldLocationHash = window.location.hash;
2299 if (this.locationPollId) {
2300 clearInterval(this.locationPollID);
2301 this.locationPollId = null;
2304 this.locationPollId = setInterval(function() {
2305 var newHash = window.location.hash;
2306 if (newHash != self.oldLocationHash) {
2307 if (newHash != self.oldUserHash) { // Only process new user hash once
2308 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2310 // Queue change if animating
2311 if (self.animating) {
2313 self.animationFinishedCallback = function() {
2314 self.updateFromParams(self.paramsFromFragment(newHash));
2316 } else { // update immediately
2317 self.updateFromParams(self.paramsFromFragment(newHash));
2319 self.oldUserHash = newHash;
2327 // Returns a URL for an embedded version of the current book
2328 GnuBook.prototype.getEmbedURL = function() {
2329 // We could generate a URL hash fragment here but for now we just leave at defaults
2330 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2335 // Returns the embed code HTML fragment suitable for copy and paste
2336 GnuBook.prototype.getEmbedCode = function() {
2337 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2341 // Library functions
2343 clamp: function(value, min, max) {
2344 return Math.min(Math.max(value, min), max);