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('');
400 //var centerY = this.centerY1up();
401 //var centerX = this.centerX1up();
402 //console.log('draw center ' + centerY + ',' + centerX);
403 //console.log('scroll left ' + $('#GBcontainer').attr('scrollLeft'));
407 // drawLeafsTwoPage()
408 //______________________________________________________________________________
409 GnuBook.prototype.drawLeafsTwoPage = function() {
410 //alert('drawing two leafs!');
412 var scrollTop = $('#GBcontainer').attr('scrollTop');
413 var scrollBottom = scrollTop + $('#GBcontainer').height();
415 //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentIndexL);
417 var index = this.currentIndexL;
418 var height = this.getPageHeight(index);
419 var width = this.getPageWidth(index);
420 var handSide= this.getPageSide(index);
422 var leafEdgeWidthL = this.leafEdgeWidth(index);
423 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
424 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
425 var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
426 //console.log(leafEdgeWidthL);
428 var middle = ($('#GBcontainer').width() >> 1);
429 var left = middle - this.twoPageW;
430 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
432 var scaledW = parseInt(this.twoPageH*width/height);
433 left = 10+leafEdgeWidthL;
434 //var right = left+scaledW;
435 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
437 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
439 this.prefetchImg(index);
440 $(this.prefetchedImgs[index]).css({
441 position: 'absolute',
442 /*right: gutter+'px',*/
443 left: gutter-scaledW+'px',
446 backgroundColor: 'rgb(234, 226, 205)',
447 height: this.twoPageH +'px',
448 width: scaledW + 'px',
449 borderRight: '1px solid black',
451 }).appendTo('#GBcontainer');
452 //$('#GBcontainer').append(this.prefetchedImgs[index]);
455 var index = this.currentIndexR;
456 var height = this.getPageHeight(index);
457 var width = this.getPageWidth(index);
458 // var left = ($('#GBcontainer').width() >> 1);
461 var scaledW = this.twoPageH*width/height;
462 this.prefetchImg(index);
463 $(this.prefetchedImgs[index]).css({
464 position: 'absolute',
468 backgroundColor: 'rgb(234, 226, 205)',
469 height: this.twoPageH + 'px',
470 width: scaledW + 'px',
471 borderLeft: '1px solid black',
473 }).appendTo('#GBcontainer');
474 //$('#GBcontainer').append(this.prefetchedImgs[index]);
477 this.displayedIndices = [this.currentIndexL, this.currentIndexR];
478 this.setClickHandlers();
480 this.updatePageNumBox2UP();
483 // updatePageNumBox2UP
484 //______________________________________________________________________________
485 GnuBook.prototype.updatePageNumBox2UP = function() {
486 if (null != this.getPageNum(this.currentIndexL)) {
487 $("#GBpagenum").val(this.getPageNum(this.currentIndexL));
489 $("#GBpagenum").val('');
491 this.updateLocationHash();
495 //______________________________________________________________________________
496 GnuBook.prototype.loadLeafs = function() {
500 if (null == this.timer) {
501 this.timer=setTimeout(function(){self.drawLeafs()},250);
503 clearTimeout(this.timer);
504 this.timer=setTimeout(function(){self.drawLeafs()},250);
510 //______________________________________________________________________________
511 GnuBook.prototype.zoom1up = function(dir) {
512 if (2 == this.mode) { //can only zoom in 1-page mode
517 // $$$ with flexible zoom we could "snap" to /2 page reductions
518 // for better scaling
520 if (this.reduce <= 0.5) return;
521 this.reduce*=0.5; //zoom in
523 if (this.reduce >= 8) return;
524 this.reduce*=2; //zoom out
527 this.resizePageView();
529 $('#GBpageview').empty()
530 this.displayedIndices = [];
533 $('#GBzoom').text(100/this.reduce);
537 //______________________________________________________________________________
538 GnuBook.prototype.resizePageView = function() {
541 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
542 var viewWidth = $('#GBcontainer').attr('clientWidth');
544 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
545 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
546 var oldPageViewHeight = $('#GBpageview').height();
547 var oldPageViewWidth = $('#GBpageview').width();
549 var oldCenterY = this.centerY1up();
550 var oldCenterX = this.centerX1up();
552 if (0 != oldPageViewHeight) {
553 var scrollRatio = oldCenterY / oldPageViewHeight;
558 for (i=0; i<this.numLeafs; i++) {
559 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
560 var width = parseInt(this.getPageWidth(i)/this.reduce);
561 if (width>viewWidth) viewWidth=width;
563 $('#GBpageview').height(viewHeight);
564 $('#GBpageview').width(viewWidth);
566 var newCenterY = scrollRatio*viewHeight;
567 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
568 $('#GBcontainer').attr('scrollTop', newTop);
570 // We use clientWidth here to avoid miscalculating due to scroll bar
571 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
572 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
573 newLeft = Math.max(newLeft, 0);
574 $('#GBcontainer').attr('scrollLeft', newLeft);
575 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
577 //this.centerPageView();
583 //______________________________________________________________________________
584 // Returns the current offset of the viewport center in scaled document coordinates.
585 GnuBook.prototype.centerX1up = function() {
587 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
588 centerX = $('#GBpageview').width();
590 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
592 centerX = Math.floor(centerX);
597 //______________________________________________________________________________
598 // Returns the current offset of the viewport center in scaled document coordinates.
599 GnuBook.prototype.centerY1up = function() {
600 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
601 return Math.floor(centerY);
605 //______________________________________________________________________________
606 GnuBook.prototype.centerPageView = function() {
608 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
609 var clientWidth = $('#GBcontainer').attr('clientWidth');
610 //console.log('sW='+scrollWidth+' cW='+clientWidth);
611 if (scrollWidth > clientWidth) {
612 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
618 //______________________________________________________________________________
619 // Attempts to jump to page. Returns true if page could be found, false otherwise.
620 GnuBook.prototype.jumpToPage = function(pageNum) {
622 var pageIndex = this.getPageIndex(pageNum);
624 if ('undefined' != typeof(pageIndex)) {
627 this.jumpToIndex(pageIndex);
628 $('#GBcontainer').attr('scrollTop', leafTop);
637 //______________________________________________________________________________
638 GnuBook.prototype.jumpToIndex = function(index) {
640 if (2 == this.mode) {
643 // By checking against min/max we do nothing if requested index
645 if (index < Math.min(this.currentIndexL, this.currentIndexR)) {
646 this.flipBackToIndex(index);
647 } else if (index > Math.max(this.currentIndexL, this.currentIndexR)) {
648 this.flipFwdToIndex(index);
655 for (i=0; i<index; i++) {
656 h = parseInt(this.getPageHeight(i)/this.reduce);
657 leafTop += h + this.padding;
659 //$('#GBcontainer').attr('scrollTop', leafTop);
660 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
667 //______________________________________________________________________________
668 GnuBook.prototype.switchMode = function(mode) {
670 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
672 if (mode == this.mode) return;
674 if (!this.canSwitchToMode(mode)) {
679 this.removeSearchHilites();
683 this.switchToolbarMode(mode);
686 this.prepareOnePageView();
688 this.prepareTwoPageView();
693 //prepareOnePageView()
694 //______________________________________________________________________________
695 GnuBook.prototype.prepareOnePageView = function() {
697 // var startLeaf = this.displayedIndices[0];
698 var startLeaf = this.currentIndex();
700 $('#GBcontainer').empty();
701 $('#GBcontainer').css({
706 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
708 this.resizePageView();
710 this.jumpToIndex(startLeaf);
711 this.displayedIndices = [];
713 this.drawLeafsOnePage();
714 $('#GBzoom').text(100/this.reduce);
716 // Bind mouse handlers
717 // Disable mouse click to avoid selected/highlighted page images - bug 354239
718 gbPageView.bind('mousedown', function(e) {
721 // Special hack for IE7
722 gbPageView[0].onselectstart = function(e) { return false; };
725 // prepareTwoPageView()
726 //______________________________________________________________________________
727 GnuBook.prototype.prepareTwoPageView = function() {
728 $('#GBcontainer').empty();
730 // We want to display two facing pages. We may be missing
731 // one side of the spread because it is the first/last leaf,
732 // foldouts, missing pages, etc
734 //var targetLeaf = this.displayedIndices[0];
735 var targetLeaf = this.firstIndex;
737 if (targetLeaf < this.firstDisplayableIndex()) {
738 targetLeaf = this.firstDisplayableIndex();
741 if (targetLeaf > this.lastDisplayableIndex()) {
742 targetLeaf = this.lastDisplayableIndex();
745 this.currentIndexL = null;
746 this.currentIndexR = null;
747 this.pruneUnusedImgs();
749 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
750 this.currentIndexL = currentSpreadIndices[0];
751 this.currentIndexR = currentSpreadIndices[1];
752 this.firstIndex = this.currentIndexL;
754 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
756 // We want to minimize the unused space in two-up mode (maximize the amount of page
757 // shown). We give width to the leaf edges and these widths change (though the sum
758 // of the two remains constant) as we flip through the book. With the book
759 // cover centered and fixed in the GBcontainer div the page images will meet
760 // at the "gutter" which is generally offset from the center.
761 var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
762 //var gutter = middle+parseInt((2*this.currentIndexL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
764 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
766 var scaledWL = this.getPageWidth2UP(this.currentIndexL);
767 var scaledWR = this.getPageWidth2UP(this.currentIndexR);
768 var leafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
769 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
771 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
772 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
774 // The width of the book cover div. The combined width of both pages, twice the width
775 // of the book cover internal padding (2*10) and the page edges
776 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
778 // The height of the book cover div
779 var bookCoverDivHeight = this.twoPageH+20;
781 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
782 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
783 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
784 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
786 this.twoPageDiv = document.createElement('div');
787 $(this.twoPageDiv).attr('id', 'book_div_1').css({
788 border: '1px solid rgb(68, 25, 17)',
789 width: bookCoverDivWidth + 'px',
790 height: bookCoverDivHeight+'px',
791 visibility: 'visible',
792 position: 'absolute',
793 backgroundColor: '#663929',
794 left: bookCoverDivLeft + 'px',
795 top: bookCoverDivTop+'px',
796 MozBorderRadiusTopleft: '7px',
797 MozBorderRadiusTopright: '7px',
798 MozBorderRadiusBottomright: '7px',
799 MozBorderRadiusBottomleft: '7px'
800 }).appendTo('#GBcontainer');
801 //$('#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;"/>');
804 var height = this.getPageHeight(this.currentIndexR);
805 var width = this.getPageWidth(this.currentIndexR);
806 var scaledW = this.twoPageH*width/height;
808 this.leafEdgeR = document.createElement('div');
809 this.leafEdgeR.className = 'leafEdgeR';
810 $(this.leafEdgeR).css({
811 borderStyle: 'solid solid solid none',
812 borderColor: 'rgb(51, 51, 34)',
813 borderWidth: '1px 1px 1px 0px',
814 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
815 width: leafEdgeWidthR + 'px',
816 height: this.twoPageH-1 + 'px',
818 left: gutter+scaledW+'px',
819 top: bookCoverDivTop+10+'px',
821 }).appendTo('#GBcontainer');
823 this.leafEdgeL = document.createElement('div');
824 this.leafEdgeL.className = 'leafEdgeL';
825 $(this.leafEdgeL).css({
826 borderStyle: 'solid none solid solid',
827 borderColor: 'rgb(51, 51, 34)',
828 borderWidth: '1px 0px 1px 1px',
829 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
830 width: leafEdgeWidthL + 'px',
831 height: this.twoPageH-1 + 'px',
832 left: bookCoverDivLeft+10+'px',
833 top: bookCoverDivTop+10+'px',
835 }).appendTo('#GBcontainer');
839 bookCoverDivWidth = 30;
840 bookCoverDivHeight = this.twoPageH+20;
841 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
842 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
844 div = document.createElement('div');
845 $(div).attr('id', 'book_div_2').css({
846 border: '1px solid rgb(68, 25, 17)',
847 width: bookCoverDivWidth+'px',
848 height: bookCoverDivHeight+'px',
849 position: 'absolute',
850 backgroundColor: 'rgb(68, 25, 17)',
851 left: bookCoverDivLeft+'px',
852 top: bookCoverDivTop+'px'
853 }).appendTo('#GBcontainer');
854 //$('#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;"/>');
856 bookCoverDivWidth = this.twoPageW*2;
857 bookCoverDivHeight = this.twoPageH;
858 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
859 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
862 this.prepareTwoPagePopUp();
864 this.displayedIndices = [];
866 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
867 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
869 this.drawLeafsTwoPage();
870 this.updateSearchHilites2UP();
873 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentIndexL)).toString().substr(0,4));
876 // prepareTwoPagePopUp()
878 // This function prepares the "View Page n" popup that shows while the mouse is
879 // over the left/right "stack of sheets" edges. It also binds the mouse
880 // events for these divs.
881 //______________________________________________________________________________
882 GnuBook.prototype.prepareTwoPagePopUp = function() {
883 this.twoPagePopUp = document.createElement('div');
884 $(this.twoPagePopUp).css({
885 border: '1px solid black',
887 position: 'absolute',
888 fontFamily: 'sans-serif',
891 backgroundColor: 'rgb(255, 255, 238)',
893 }).appendTo('#GBcontainer');
894 $(this.twoPagePopUp).hide();
896 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
897 $(e.data.twoPagePopUp).show();
900 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
901 $(e.data.twoPagePopUp).hide();
904 $(this.leafEdgeL).bind('click', this, function(e) {
906 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
907 e.data.jumpToIndex(jumpIndex);
910 $(this.leafEdgeR).bind('click', this, function(e) {
912 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
913 e.data.jumpToIndex(jumpIndex);
916 $(this.leafEdgeR).bind('mousemove', this, function(e) {
918 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
919 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
921 $(e.data.twoPagePopUp).css({
922 left: e.pageX +5+ 'px',
923 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
927 $(this.leafEdgeL).bind('mousemove', this, function(e) {
929 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
930 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
932 $(e.data.twoPagePopUp).css({
933 left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
934 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
939 // calculateSpreadSize()
940 //______________________________________________________________________________
941 // Calculates 2-page spread dimensions based on this.currentIndexL and
942 // this.currentIndexR
943 // This function sets this.twoPageH, twoPageW, and twoPageRatio
945 GnuBook.prototype.calculateSpreadSize = function() {
946 var firstIndex = this.currentIndexL;
947 var secondIndex = this.currentIndexR;
948 //console.log('first page is ' + firstIndex);
950 var canon5Dratio = 1.5;
952 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
953 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
954 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
957 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
958 ratio = firstIndexRatio;
959 //console.log('using firstIndexRatio ' + ratio);
961 ratio = secondIndexRatio;
962 //console.log('using secondIndexRatio ' + ratio);
965 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
966 var maxLeafEdgeWidth = parseInt($('#GBcontainer').width() * 0.1);
967 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
969 $('#GBcontainer').css('overflow', 'hidden');
971 var idealWidth = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
972 var idealHeight = $('#GBcontainer').height() - 30;
973 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
975 if (idealHeight/ratio <= idealWidth) {
977 idealWidth = parseInt(idealHeight/ratio);
980 idealHeight = parseInt(idealWidth*ratio);
983 this.twoPageH = idealHeight;
984 this.twoPageW = idealWidth;
985 this.twoPageRatio = ratio;
986 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
991 //______________________________________________________________________________
992 // Returns the currently active index.
993 GnuBook.prototype.currentIndex = function() {
994 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
995 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
996 return this.firstIndex;
998 throw 'currentIndex called for unimplemented mode ' + this.mode;
1003 //______________________________________________________________________________
1004 // Flip the right page over onto the left
1005 GnuBook.prototype.right = function() {
1006 if ('rl' != this.pageProgression) {
1016 //______________________________________________________________________________
1017 // Flip to the rightmost page
1018 GnuBook.prototype.rightmost = function() {
1019 if ('rl' != this.pageProgression) {
1027 //______________________________________________________________________________
1028 // Flip the left page over onto the right.
1029 GnuBook.prototype.left = function() {
1030 if ('rl' != this.pageProgression) {
1040 //______________________________________________________________________________
1041 // Flip to the leftmost page
1042 GnuBook.prototype.leftmost = function() {
1043 if ('rl' != this.pageProgression) {
1051 //______________________________________________________________________________
1052 GnuBook.prototype.next = function() {
1053 if (2 == this.mode) {
1055 this.flipFwdToIndex(null);
1057 if (this.firstIndex < this.lastDisplayableIndex()) {
1058 this.jumpToIndex(this.firstIndex+1);
1064 //______________________________________________________________________________
1065 GnuBook.prototype.prev = function() {
1066 if (2 == this.mode) {
1068 this.flipBackToIndex(null);
1070 if (this.firstIndex >= 1) {
1071 this.jumpToIndex(this.firstIndex-1);
1076 GnuBook.prototype.first = function() {
1077 if (2 == this.mode) {
1078 this.jumpToIndex(2);
1081 this.jumpToIndex(0);
1085 GnuBook.prototype.last = function() {
1086 if (2 == this.mode) {
1087 this.jumpToIndex(this.lastDisplayableIndex());
1090 this.jumpToIndex(this.lastDisplayableIndex());
1094 // flipBackToIndex()
1095 //______________________________________________________________________________
1096 // to flip back one spread, pass index=null
1097 GnuBook.prototype.flipBackToIndex = function(index) {
1098 if (1 == this.mode) return;
1100 var leftIndex = this.currentIndexL;
1102 // $$$ Need to change this to be able to see first spread.
1103 // See https://bugs.launchpad.net/gnubook/+bug/296788
1104 if (leftIndex <= 2) return;
1105 if (this.animating) return;
1107 if (null != this.leafEdgeTmp) {
1108 alert('error: leafEdgeTmp should be null!');
1112 if (null == index) {
1113 index = leftIndex-2;
1115 //if (index<0) return;
1117 var previousIndices = this.getSpreadIndices(index);
1119 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1123 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1125 this.animating = true;
1127 if ('rl' != this.pageProgression) {
1128 // Assume LTR and we are going backward
1129 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1130 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1133 // RTL and going backward
1134 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1135 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1139 // flipLeftToRight()
1140 //______________________________________________________________________________
1141 // Flips the page on the left towards the page on the right
1142 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1144 var leftLeaf = this.currentIndexL;
1146 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1147 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1148 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1150 var currWidthL = this.getPageWidth2UP(leftLeaf);
1151 var newWidthL = this.getPageWidth2UP(newIndexL);
1152 var newWidthR = this.getPageWidth2UP(newIndexR);
1154 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1156 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1157 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1159 //animation strategy:
1160 // 0. remove search highlight, if any.
1161 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1162 // of the left leaf and where the user clicked in the leaf edge.
1163 // Note that if this function was triggered by left() and not a
1164 // mouse click, the width of leafEdgeTmp is very small (zero px).
1165 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1166 // leftLeaf to width=0.
1167 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1168 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1169 // its new full width.
1170 // 4. After step 3 is finished, do the following:
1171 // - remove leafEdgeTmp from the dom.
1172 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1173 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1174 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1175 // and width=newLeafEdgeWidthL.
1176 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1177 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1178 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1179 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1180 // - prefetch new adjacent leafs.
1181 // - set up click handlers for both new left and right leafs.
1182 // - redraw the search highlight.
1183 // - update the pagenum box and the url.
1186 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1188 this.leafEdgeTmp = document.createElement('div');
1189 $(this.leafEdgeTmp).css({
1190 borderStyle: 'solid none solid solid',
1191 borderColor: 'rgb(51, 51, 34)',
1192 borderWidth: '1px 0px 1px 1px',
1193 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1194 width: leafEdgeTmpW + 'px',
1195 height: this.twoPageH-1 + 'px',
1196 left: leftEdgeTmpLeft + 'px',
1198 position: 'absolute',
1200 }).appendTo('#GBcontainer');
1202 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1203 $(this.leafEdgeL).css({
1204 width: newLeafEdgeWidthL+'px',
1205 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1208 // Left gets the offset of the current left leaf from the document
1209 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1210 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1211 var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1212 // We change the left leaf to right positioning
1213 $(this.prefetchedImgs[leftLeaf]).css({
1218 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1220 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1222 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1223 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1227 this.removeSearchHilites();
1229 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1230 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1232 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1233 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1235 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1236 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1237 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1239 $(self.leafEdgeR).css({
1240 // Moves the right leaf edge
1241 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1242 left: gutter+newWidthR+'px'
1245 $(self.leafEdgeL).css({
1246 // Moves and resizes the left leaf edge
1247 width: newLeafEdgeWidthL+'px',
1248 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1252 $(self.twoPageDiv).css({
1253 // Resizes the brown border div
1254 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1255 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1258 $(self.leafEdgeTmp).remove();
1259 self.leafEdgeTmp = null;
1261 self.currentIndexL = newIndexL;
1262 self.currentIndexR = newIndexR;
1263 self.firstIndex = self.currentIndexL;
1264 self.displayedIndices = [newIndexL, newIndexR];
1265 self.setClickHandlers();
1266 self.pruneUnusedImgs();
1268 self.animating = false;
1270 self.updateSearchHilites2UP();
1271 self.updatePageNumBox2UP();
1272 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1274 if (self.animationFinishedCallback) {
1275 self.animationFinishedCallback();
1276 self.animationFinishedCallback = null;
1284 //______________________________________________________________________________
1285 // Whether we flip left or right is dependent on the page progression
1286 // to flip forward one spread, pass index=null
1287 GnuBook.prototype.flipFwdToIndex = function(index) {
1289 if (this.animating) return;
1291 if (null != this.leafEdgeTmp) {
1292 alert('error: leafEdgeTmp should be null!');
1296 if (null == index) {
1297 index = this.currentIndexR+2; // $$$ assumes indices are continuous
1299 if (index > this.lastDisplayableIndex()) return;
1301 this.animating = true;
1303 var nextIndices = this.getSpreadIndices(index);
1305 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1307 if ('rl' != this.pageProgression) {
1308 // We did not specify RTL
1309 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1310 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1313 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1314 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1318 // flipRightToLeft(nextL, nextR, gutter)
1319 // $$$ better not to have to pass gutter in
1320 //______________________________________________________________________________
1321 // Flip from left to right and show the nextL and nextR indices on those sides
1322 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1323 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1324 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1325 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1326 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1328 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1330 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1332 var scaledW = this.getPageWidth2UP(this.currentIndexR);
1334 var middle = ($('#GBcontainer').width() >> 1);
1335 var currGutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1337 this.leafEdgeTmp = document.createElement('div');
1338 $(this.leafEdgeTmp).css({
1339 borderStyle: 'solid none solid solid',
1340 borderColor: 'rgb(51, 51, 34)',
1341 borderWidth: '1px 0px 1px 1px',
1342 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1343 width: leafEdgeTmpW + 'px',
1344 height: this.twoPageH-1 + 'px',
1345 left: currGutter+scaledW+'px',
1347 position: 'absolute',
1349 }).appendTo('#GBcontainer');
1351 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1352 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1354 var currWidthL = this.getPageWidth2UP(this.currentIndexL);
1355 var currWidthR = this.getPageWidth2UP(this.currentIndexR);
1356 var newWidthL = this.getPageWidth2UP(newIndexL);
1357 var newWidthR = this.getPageWidth2UP(newIndexR);
1359 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1361 var self = this; // closure-tastic!
1363 var speed = this.flipSpeed;
1365 this.removeSearchHilites();
1367 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1368 $(this.prefetchedImgs[this.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1369 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1370 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1371 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1373 $(self.leafEdgeL).css({
1374 width: newLeafEdgeWidthL+'px',
1375 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1378 $(self.twoPageDiv).css({
1379 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1380 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1383 $(self.leafEdgeTmp).remove();
1384 self.leafEdgeTmp = null;
1386 self.currentIndexL = newIndexL;
1387 self.currentIndexR = newIndexR;
1388 self.firstIndex = self.currentIndexL;
1389 self.displayedIndices = [newIndexL, newIndexR];
1390 self.setClickHandlers();
1391 self.pruneUnusedImgs();
1393 self.animating = false;
1396 self.updateSearchHilites2UP();
1397 self.updatePageNumBox2UP();
1398 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1400 if (self.animationFinishedCallback) {
1401 self.animationFinishedCallback();
1402 self.animationFinishedCallback = null;
1409 //______________________________________________________________________________
1410 GnuBook.prototype.setClickHandlers = function() {
1412 $(this.prefetchedImgs[this.currentIndexL]).click(function() {
1417 $(this.prefetchedImgs[this.currentIndexR]).click(function() {
1425 //______________________________________________________________________________
1426 GnuBook.prototype.prefetchImg = function(index) {
1427 if (undefined == this.prefetchedImgs[index]) {
1428 //console.log('prefetching ' + index);
1429 var img = document.createElement("img");
1430 img.src = this.getPageURI(index);
1431 this.prefetchedImgs[index] = img;
1436 // prepareFlipLeftToRight()
1438 //______________________________________________________________________________
1440 // Prepare to flip the left page towards the right. This corresponds to moving
1441 // backward when the page progression is left to right.
1442 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1444 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1446 this.prefetchImg(prevL);
1447 this.prefetchImg(prevR);
1449 var height = this.getPageHeight(prevL);
1450 var width = this.getPageWidth(prevL);
1451 var middle = ($('#GBcontainer').width() >> 1);
1452 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1453 var scaledW = this.twoPageH*width/height;
1455 // The gutter is the dividing line between the left and right pages.
1456 // It is offset from the middle to create the illusion of thickness to the pages
1457 var gutter = middle + this.gutterOffsetForIndex(prevL);
1459 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1460 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1461 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1463 $(this.prefetchedImgs[prevL]).css({
1464 position: 'absolute',
1465 /*right: middle+'px',*/
1466 left: gutter-scaledW+'px',
1469 backgroundColor: 'rgb(234, 226, 205)',
1470 height: this.twoPageH,
1471 width: scaledW+'px',
1472 borderRight: '1px solid black',
1476 $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1478 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1480 $(this.prefetchedImgs[prevR]).css({
1481 position: 'absolute',
1485 backgroundColor: 'rgb(234, 226, 205)',
1486 height: this.twoPageH,
1488 borderLeft: '1px solid black',
1492 $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1499 // prepareFlipRightToLeft()
1500 //______________________________________________________________________________
1501 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1503 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1505 this.prefetchImg(nextL);
1506 this.prefetchImg(nextR);
1508 var height = this.getPageHeight(nextR);
1509 var width = this.getPageWidth(nextR);
1510 var middle = ($('#GBcontainer').width() >> 1);
1511 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1512 var scaledW = this.twoPageH*width/height;
1514 var gutter = middle + this.gutterOffsetForIndex(nextL);
1516 //console.log('right to left to %d gutter is %d', nextL, gutter);
1518 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1519 $(this.prefetchedImgs[nextR]).css({
1520 position: 'absolute',
1523 backgroundColor: 'rgb(234, 226, 205)',
1524 height: this.twoPageH,
1525 width: scaledW+'px',
1526 borderLeft: '1px solid black',
1530 $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1532 height = this.getPageHeight(nextL);
1533 width = this.getPageWidth(nextL);
1534 scaledW = this.twoPageH*width/height;
1536 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1537 $(this.prefetchedImgs[nextL]).css({
1538 position: 'absolute',
1539 right: $('#GBcontainer').width()-gutter+'px',
1541 backgroundColor: 'rgb(234, 226, 205)',
1542 height: this.twoPageH,
1544 borderRight: '1px solid black',
1548 $('#GBcontainer').append(this.prefetchedImgs[nextL]);
1554 // getNextLeafs() -- NOT RTL AWARE
1555 //______________________________________________________________________________
1556 // GnuBook.prototype.getNextLeafs = function(o) {
1557 // //TODO: we might have two left or two right leafs in a row (damaged book)
1558 // //For now, assume that leafs are contiguous.
1560 // //return [this.currentIndexL+2, this.currentIndexL+3];
1561 // o.L = this.currentIndexL+2;
1562 // o.R = this.currentIndexL+3;
1565 // getprevLeafs() -- NOT RTL AWARE
1566 //______________________________________________________________________________
1567 // GnuBook.prototype.getPrevLeafs = function(o) {
1568 // //TODO: we might have two left or two right leafs in a row (damaged book)
1569 // //For now, assume that leafs are contiguous.
1571 // //return [this.currentIndexL-2, this.currentIndexL-1];
1572 // o.L = this.currentIndexL-2;
1573 // o.R = this.currentIndexL-1;
1576 // pruneUnusedImgs()
1577 //______________________________________________________________________________
1578 GnuBook.prototype.pruneUnusedImgs = function() {
1579 //console.log('current: ' + this.currentIndexL + ' ' + this.currentIndexR);
1580 for (var key in this.prefetchedImgs) {
1581 //console.log('key is ' + key);
1582 if ((key != this.currentIndexL) && (key != this.currentIndexR)) {
1583 //console.log('removing key '+ key);
1584 $(this.prefetchedImgs[key]).remove();
1586 if ((key < this.currentIndexL-4) || (key > this.currentIndexR+4)) {
1587 //console.log('deleting key '+ key);
1588 delete this.prefetchedImgs[key];
1594 //______________________________________________________________________________
1595 GnuBook.prototype.prefetch = function() {
1597 var lim = this.currentIndexL-4;
1599 lim = Math.max(lim, 0);
1600 for (i = lim; i < this.currentIndexL; i++) {
1601 this.prefetchImg(i);
1604 if (this.numLeafs > (this.currentIndexR+1)) {
1605 lim = Math.min(this.currentIndexR+4, this.numLeafs-1);
1606 for (i=this.currentIndexR+1; i<=lim; i++) {
1607 this.prefetchImg(i);
1612 // getPageWidth2UP()
1613 //______________________________________________________________________________
1614 GnuBook.prototype.getPageWidth2UP = function(index) {
1615 var height = this.getPageHeight(index);
1616 var width = this.getPageWidth(index);
1617 return Math.floor(this.twoPageH*width/height);
1621 //______________________________________________________________________________
1622 GnuBook.prototype.search = function(term) {
1623 $('#GnuBookSearchScript').remove();
1624 var script = document.createElement("script");
1625 script.setAttribute('id', 'GnuBookSearchScript');
1626 script.setAttribute("type", "text/javascript");
1627 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1628 document.getElementsByTagName('head')[0].appendChild(script);
1629 $('#GnuBookSearchResults').html('Searching...');
1632 // GBSearchCallback()
1633 //______________________________________________________________________________
1634 GnuBook.prototype.GBSearchCallback = function(txt) {
1636 if (jQuery.browser.msie) {
1637 var dom=new ActiveXObject("Microsoft.XMLDOM");
1641 var parser = new DOMParser();
1642 var dom = parser.parseFromString(txt, "text/xml");
1645 $('#GnuBookSearchResults').empty();
1646 $('#GnuBookSearchResults').append('<ul>');
1648 for (var key in this.searchResults) {
1649 if (null != this.searchResults[key].div) {
1650 $(this.searchResults[key].div).remove();
1652 delete this.searchResults[key];
1655 var pages = dom.getElementsByTagName('PAGE');
1657 if (0 == pages.length) {
1658 // $$$ it would be nice to echo the (sanitized) search result here
1659 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1661 for (var i = 0; i < pages.length; i++){
1662 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1665 var re = new RegExp (/_(\d{4})/);
1666 var reMatch = re.exec(pages[i].getAttribute('file'));
1667 var index = parseInt(reMatch[1], 10);
1668 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1670 var children = pages[i].childNodes;
1672 for (var j=0; j<children.length; j++) {
1673 //console.log(j + ' - ' + children[j].nodeName);
1674 //console.log(children[j].firstChild.nodeValue);
1675 if ('CONTEXT' == children[j].nodeName) {
1676 context += children[j].firstChild.nodeValue;
1677 } else if ('WORD' == children[j].nodeName) {
1678 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1680 var index = this.leafNumToIndex(index);
1681 if (null != index) {
1682 //coordinates are [left, bottom, right, top, [baseline]]
1683 //we'll skip baseline for now...
1684 var coords = children[j].getAttribute('coords').split(',',4);
1685 if (4 == coords.length) {
1686 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1691 var pageName = this.getPageName(index);
1692 //TODO: remove hardcoded instance name
1693 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1696 $('#GnuBookSearchResults').append('</ul>');
1698 this.updateSearchHilites();
1701 // updateSearchHilites()
1702 //______________________________________________________________________________
1703 GnuBook.prototype.updateSearchHilites = function() {
1704 if (2 == this.mode) {
1705 this.updateSearchHilites2UP();
1707 this.updateSearchHilites1UP();
1711 // showSearchHilites1UP()
1712 //______________________________________________________________________________
1713 GnuBook.prototype.updateSearchHilites1UP = function() {
1715 for (var key in this.searchResults) {
1717 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1718 var result = this.searchResults[key];
1719 if(null == result.div) {
1720 result.div = document.createElement('div');
1721 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1722 //console.log('appending ' + key);
1725 width: (result.r-result.l)/this.reduce + 'px',
1726 height: (result.b-result.t)/this.reduce + 'px',
1727 left: (result.l)/this.reduce + 'px',
1728 top: (result.t)/this.reduce +'px'
1732 //console.log(key + ' not displayed');
1733 this.searchResults[key].div=null;
1738 // showSearchHilites2UP()
1739 //______________________________________________________________________________
1740 GnuBook.prototype.updateSearchHilites2UP = function() {
1742 var middle = ($('#GBcontainer').width() >> 1);
1744 for (var key in this.searchResults) {
1745 key = parseInt(key, 10);
1746 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1747 var result = this.searchResults[key];
1748 if(null == result.div) {
1749 result.div = document.createElement('div');
1750 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1751 //console.log('appending ' + key);
1754 var height = this.getPageHeight(key);
1755 var width = this.getPageWidth(key)
1756 var reduce = this.twoPageH/height;
1757 var scaledW = parseInt(width*reduce);
1759 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1761 if ('L' == this.getPageSide(key)) {
1762 var pageL = gutter-scaledW;
1766 var pageT = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1769 width: (result.r-result.l)*reduce + 'px',
1770 height: (result.b-result.t)*reduce + 'px',
1771 left: pageL+(result.l)*reduce + 'px',
1772 top: pageT+(result.t)*reduce +'px'
1776 //console.log(key + ' not displayed');
1777 if (null != this.searchResults[key].div) {
1778 //console.log('removing ' + key);
1779 $(this.searchResults[key].div).remove();
1781 this.searchResults[key].div=null;
1786 // removeSearchHilites()
1787 //______________________________________________________________________________
1788 GnuBook.prototype.removeSearchHilites = function() {
1789 for (var key in this.searchResults) {
1790 if (null != this.searchResults[key].div) {
1791 $(this.searchResults[key].div).remove();
1792 this.searchResults[key].div=null;
1798 //______________________________________________________________________________
1799 GnuBook.prototype.showEmbedCode = function() {
1800 if (null != this.embedPopup) { // check if already showing
1804 this.embedPopup = document.createElement("div");
1805 $(this.embedPopup).css({
1806 position: 'absolute',
1808 left: ($('#GBcontainer').width()-400)/2 + 'px',
1811 border: "3px double #999999",
1813 backgroundColor: "#fff"
1814 }).appendTo('#GnuBook');
1816 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1817 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>';
1818 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1819 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1821 this.embedPopup.innerHTML = htmlStr;
1822 $(this.embedPopup).find('input').bind('click', function() {
1828 //______________________________________________________________________________
1829 GnuBook.prototype.autoToggle = function() {
1831 var bComingFrom1up = false;
1832 if (2 != this.mode) {
1833 bComingFrom1up = true;
1838 if (null == this.autoTimer) {
1839 this.flipSpeed = 2000;
1841 // $$$ Draw events currently cause layout problems when they occur during animation.
1842 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1843 // we workaround for now by not triggering immediate animation in that case.
1844 // See https://bugs.launchpad.net/gnubook/+bug/328327
1845 if (('rl' == this.pageProgression) && bComingFrom1up) {
1846 // don't flip immediately -- wait until timer fires
1849 this.flipFwdToIndex();
1852 $('#GBtoolbar .play').hide();
1853 $('#GBtoolbar .pause').show();
1854 this.autoTimer=setInterval(function(){
1855 if (self.animating) {return;}
1857 if (Math.max(self.currentIndexL, self.currentIndexR) >= self.lastDisplayableIndex()) {
1858 self.flipBackToIndex(1); // $$$ really what we want?
1860 self.flipFwdToIndex();
1869 //______________________________________________________________________________
1870 GnuBook.prototype.autoStop = function() {
1871 if (null != this.autoTimer) {
1872 clearInterval(this.autoTimer);
1873 this.flipSpeed = 'fast';
1874 $('#GBtoolbar .pause').hide();
1875 $('#GBtoolbar .play').show();
1876 this.autoTimer = null;
1880 // keyboardNavigationIsDisabled(event)
1881 // - returns true if keyboard navigation should be disabled for the event
1882 //______________________________________________________________________________
1883 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1884 if (event.target.tagName == "INPUT") {
1890 // gutterOffsetForIndex
1891 //______________________________________________________________________________
1893 // Returns the gutter offset for the spread containing the given index.
1894 // This function supports RTL
1895 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1897 // To find the offset of the gutter from the middle we calculate our percentage distance
1898 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1899 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1901 // But then again for RTL it's the opposite
1902 if ('rl' == this.pageProgression) {
1910 //______________________________________________________________________________
1911 // Returns the width of the leaf edge div for the page with index given
1912 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1913 // $$$ could there be single pixel rounding errors for L vs R?
1914 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1915 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1917 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1921 // jumpIndexForLeftEdgePageX
1922 //______________________________________________________________________________
1923 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1924 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1925 if ('rl' != this.pageProgression) {
1926 // LTR - flipping backward
1927 var jumpIndex = this.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1929 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1930 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexL - 2);
1934 var jumpIndex = this.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1935 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexL + 2, this.lastDisplayableIndex());
1940 // jumpIndexForRightEdgePageX
1941 //______________________________________________________________________________
1942 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1943 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1944 if ('rl' != this.pageProgression) {
1946 var jumpIndex = this.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1947 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexR + 2, this.lastDisplayableIndex());
1950 var jumpIndex = this.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1951 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexR - 2);
1956 GnuBook.prototype.initToolbar = function(mode, ui) {
1958 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1959 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1960 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1961 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1962 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
1963 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1964 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1965 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1968 if (ui == "embed") {
1969 $("#GnuBook a.logo").attr("target","_blank");
1972 // $$$ turn this into a member variable
1973 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1975 // We build in mode 2
1976 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1977 + "<button class='GBicon rollover embed' />"
1978 + "<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>"
1979 + "<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>"
1980 + "<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>"
1981 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1983 this.bindToolbarNavHandlers(jToolbar);
1985 // Setup tooltips -- later we could load these from a file for i18n
1986 var titles = { '.logo': 'Go to Archive.org',
1987 '.zoom_in': 'Zoom in',
1988 '.zoom_out': 'Zoom out',
1989 '.one_page_mode': 'One-page view',
1990 '.two_page_mode': 'Two-page view',
1991 '.embed': 'Embed bookreader',
1992 '.book_left': 'Flip left',
1993 '.book_right': 'Flip right',
1994 '.book_up': 'Page up',
1995 '.book_down': 'Page down',
1998 '.book_top': 'First page',
1999 '.book_bottom': 'Last page'
2001 if ('rl' == this.pageProgression) {
2002 titles['.book_leftmost'] = 'Last page';
2003 titles['.book_rightmost'] = 'First page';
2005 titles['.book_leftmost'] = 'First page';
2006 titles['.book_rightmost'] = 'Last page';
2009 for (var icon in titles) {
2010 jToolbar.find(icon).attr('title', titles[icon]);
2013 // Hide mode buttons and autoplay if 2up is not available
2014 // $$$ if we end up with more than two modes we should show the applicable buttons
2015 if ( !this.canSwitchToMode(this.constMode2up) ) {
2016 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2019 // Switch to requested mode -- binds other click handlers
2020 this.switchToolbarMode(mode);
2025 // switchToolbarMode
2026 //______________________________________________________________________________
2027 // Update the toolbar for the given mode (changes navigation buttons)
2028 // $$$ we should soon split the toolbar out into its own module
2029 GnuBook.prototype.switchToolbarMode = function(mode) {
2032 $('#GBtoolbar .GBtoolbarmode2').hide();
2033 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2036 $('#GBtoolbar .GBtoolbarmode1').hide();
2037 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2041 // bindToolbarNavHandlers
2042 //______________________________________________________________________________
2043 // Binds the toolbar handlers
2044 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2046 jToolbar.find('.book_left').bind('click', function(e) {
2051 jToolbar.find('.book_right').bind('click', function(e) {
2056 jToolbar.find('.book_up').bind('click', function(e) {
2061 jToolbar.find('.book_down').bind('click', function(e) {
2066 jToolbar.find('.embed').bind('click', function(e) {
2071 jToolbar.find('.play').bind('click', function(e) {
2076 jToolbar.find('.pause').bind('click', function(e) {
2081 jToolbar.find('.book_top').bind('click', function(e) {
2086 jToolbar.find('.book_bottom').bind('click', function(e) {
2091 jToolbar.find('.book_leftmost').bind('click', function(e) {
2096 jToolbar.find('.book_rightmost').bind('click', function(e) {
2102 // firstDisplayableIndex
2103 //______________________________________________________________________________
2104 // Returns the index of the first visible page, dependent on the mode.
2105 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2106 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2107 GnuBook.prototype.firstDisplayableIndex = function() {
2108 if (this.mode == 0) {
2111 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2115 // lastDisplayableIndex
2116 //______________________________________________________________________________
2117 // Returns the index of the last visible page, dependent on the mode.
2118 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2119 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2120 GnuBook.prototype.lastDisplayableIndex = function() {
2121 if (this.mode == 2) {
2122 if (this.lastDisplayableIndex2up === null) {
2123 // Calculate and cache
2124 var candidate = this.numLeafs - 1;
2125 for ( ; candidate >= 0; candidate--) {
2126 var spreadIndices = this.getSpreadIndices(candidate);
2127 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2131 this.lastDisplayableIndex2up = candidate;
2133 return this.lastDisplayableIndex2up;
2135 return this.numLeafs - 1;
2139 // shortTitle(maximumCharacters)
2141 // Returns a shortened version of the title with the maximum number of characters
2142 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2143 if (this.bookTitle.length < maximumCharacters) {
2144 return this.bookTitle;
2147 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2154 // Parameter related functions
2156 // updateFromParams(params)
2158 // Update ourselves from the params object.
2160 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2161 GnuBook.prototype.updateFromParams = function(params) {
2162 if ('undefined' != typeof(params.mode)) {
2163 this.switchMode(params.mode);
2166 // $$$ process /search
2167 // $$$ process /zoom
2169 // We only respect page if index is not set
2170 if ('undefined' != typeof(params.index)) {
2171 if (params.index != this.currentIndex()) {
2172 this.jumpToIndex(params.index);
2174 } else if ('undefined' != typeof(params.page)) {
2175 // $$$ this assumes page numbers are unique
2176 if (params.page != this.getPageNum(this.currentIndex())) {
2177 this.jumpToPage(params.page);
2181 // $$$ process /region
2182 // $$$ process /highlight
2185 // paramsFromFragment(urlFragment)
2187 // Returns a object with configuration parametes from a URL fragment.
2189 // E.g paramsFromFragment(window.location.hash)
2190 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2191 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2195 // For convenience we allow an initial # character (as from window.location.hash)
2196 // but don't require it
2197 if (urlFragment.substr(0,1) == '#') {
2198 urlFragment = urlFragment.substr(1);
2201 // Simple #nn syntax
2202 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2203 if ( !isNaN(oldStyleLeafNum) ) {
2204 params.index = oldStyleLeafNum;
2206 // Done processing if using old-style syntax
2210 // Split into key-value pairs
2211 var urlArray = urlFragment.split('/');
2213 for (var i = 0; i < urlArray.length; i += 2) {
2214 urlHash[urlArray[i]] = urlArray[i+1];
2218 if ('1up' == urlHash['mode']) {
2219 params.mode = this.constMode1up;
2220 } else if ('2up' == urlHash['mode']) {
2221 params.mode = this.constMode2up;
2225 if ('undefined' != typeof(urlHash['page'])) {
2226 // page was set -- may not be int
2227 params.page = urlHash['page'];
2230 // $$$ process /region
2231 // $$$ process /search
2232 // $$$ process /highlight
2237 // paramsFromCurrent()
2239 // Create a params object from the current parameters.
2240 GnuBook.prototype.paramsFromCurrent = function() {
2244 var pageNum = this.getPageNum(this.currentIndex());
2245 if ((pageNum === 0) || pageNum) {
2246 params.page = pageNum;
2249 params.index = this.currentIndex();
2250 params.mode = this.mode;
2259 // fragmentFromParams(params)
2261 // Create a fragment string from the params object.
2262 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2263 GnuBook.prototype.fragmentFromParams = function(params) {
2264 var separator = '/';
2268 if ('undefined' != typeof(params.page)) {
2269 fragments.push('page', params.page);
2271 // Don't have page numbering -- use index instead
2272 fragments.push('page', 'n' + params.index);
2280 if ('undefined' != typeof(params.mode)) {
2281 if (params.mode == this.constMode1up) {
2282 fragments.push('mode', '1up');
2283 } else if (params.mode == this.constMode2up) {
2284 fragments.push('mode', '2up');
2286 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2290 return fragments.join(separator);
2293 // getPageIndex(pageNum)
2295 // Returns the *highest* index the given page number, or undefined
2296 GnuBook.prototype.getPageIndex = function(pageNum) {
2297 var pageIndices = this.getPageIndices(pageNum);
2299 if (pageIndices.length > 0) {
2300 return pageIndices[pageIndices.length - 1];
2306 // getPageIndices(pageNum)
2308 // Returns an array (possibly empty) of the indices with the given page number
2309 GnuBook.prototype.getPageIndices = function(pageNum) {
2312 // Check for special "nXX" page number
2313 if (pageNum.slice(0,1) == 'n') {
2315 var pageIntStr = pageNum.slice(1, pageNum.length);
2316 var pageIndex = parseInt(pageIntStr);
2317 indices.append(pageIndex);
2320 // Do nothing... will run through page names and see if one matches
2325 for (i=0; i<this.numLeafs; i++) {
2326 if (this.getPageNum(i) == pageNum) {
2334 // getPageName(index)
2336 // Returns the name of the page as it should be displayed in the user interface
2337 GnuBook.prototype.getPageName = function(index) {
2338 return 'Page ' + this.getPageNum(index);
2341 // updateLocationHash
2343 // Update the location hash from the current parameters. Call this instead of manually
2344 // using window.location.replace
2345 GnuBook.prototype.updateLocationHash = function() {
2346 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2347 window.location.replace(newHash);
2349 // This is the variable checked in the timer. Only user-generated changes
2350 // to the URL will trigger the event.
2351 this.oldLocationHash = newHash;
2354 // startLocationPolling
2356 // Starts polling of window.location to see hash fragment changes
2357 GnuBook.prototype.startLocationPolling = function() {
2358 var self = this; // remember who I am
2359 self.oldLocationHash = window.location.hash;
2361 if (this.locationPollId) {
2362 clearInterval(this.locationPollID);
2363 this.locationPollId = null;
2366 this.locationPollId = setInterval(function() {
2367 var newHash = window.location.hash;
2368 if (newHash != self.oldLocationHash) {
2369 if (newHash != self.oldUserHash) { // Only process new user hash once
2370 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2372 // Queue change if animating
2373 if (self.animating) {
2375 self.animationFinishedCallback = function() {
2376 self.updateFromParams(self.paramsFromFragment(newHash));
2378 } else { // update immediately
2379 self.updateFromParams(self.paramsFromFragment(newHash));
2381 self.oldUserHash = newHash;
2389 // Returns a URL for an embedded version of the current book
2390 GnuBook.prototype.getEmbedURL = function() {
2391 // We could generate a URL hash fragment here but for now we just leave at defaults
2392 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2397 // Returns the embed code HTML fragment suitable for copy and paste
2398 GnuBook.prototype.getEmbedCode = function() {
2399 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2404 // Returns true if we can switch to the requested mode
2405 GnuBook.prototype.canSwitchToMode = function(mode) {
2406 if (mode == this.constMode2up) {
2407 // check there are enough pages to display
2408 // $$$ this is a workaround for the mis-feature that we can't display
2409 // short books in 2up mode
2410 if (this.numLeafs < 6) {
2418 // Library functions
2420 clamp: function(value, min, max) {
2421 return Math.min(Math.max(value, min), max);