2 Copyright(c)2008 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.displayedLeafs = [];
40 //this.leafsToDisplay = [];
42 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to leafNum
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 startIndex = this.leafNumToIndex(this.titleLeaf);
91 if ('undefined' == typeof(startIndex)) {
95 if ('undefined' != typeof(params.mode)) {
96 this.mode = params.mode;
99 // Set document title -- may have already been set in enclosing html for
100 // search engine visibility
101 document.title = this.shortTitle(50);
103 $("#GnuBook").empty();
104 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
105 $("#GnuBook").append("<div id='GBcontainer'></div>");
106 $("#GBcontainer").append("<div id='GBpageview'></div>");
108 $("#GBcontainer").bind('scroll', this, function(e) {
112 this.setupKeyListeners();
113 this.startLocationPolling();
115 $(window).bind('resize', this, function(e) {
116 //console.log('resize!');
117 if (1 == e.data.mode) {
118 //console.log('centering 1page view');
119 e.data.centerPageView();
120 $('#GBpageview').empty()
121 e.data.displayedLeafs = [];
122 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
125 //console.log('drawing 2 page view');
126 e.data.prepareTwoPageView();
130 $('.GBpagediv1up').bind('mousedown', this, function(e) {
131 //console.log('mousedown!');
134 if (1 == this.mode) {
135 this.resizePageView();
136 this.firstIndex = startIndex;
137 this.jumpToIndex(startIndex);
139 //this.resizePageView();
141 this.displayedLeafs=[0];
142 this.firstIndex = startIndex;
143 this.displayedLeafs = [this.firstIndex];
144 //console.log('titleLeaf: %d', this.titleLeaf);
145 //console.log('displayedLeafs: %s', this.displayedLeafs);
146 this.prepareTwoPageView();
147 //if (this.auto) this.nextPage();
150 // Enact other parts of initial params
151 this.updateFromParams(params);
154 GnuBook.prototype.setupKeyListeners = function() {
167 // We use document here instead of window to avoid a bug in jQuery on IE7
168 $(document).keydown(function(e) {
170 // Keyboard navigation
174 // In 1up mode page scrolling is handled by browser
175 if (2 == self.mode) {
181 if (2 == self.mode) {
192 if (self.keyboardNavigationIsDisabled(e)) {
195 if (2 == self.mode) {
200 if (self.keyboardNavigationIsDisabled(e)) {
203 if (2 == self.mode) {
212 //______________________________________________________________________________
213 GnuBook.prototype.drawLeafs = function() {
214 if (1 == this.mode) {
215 this.drawLeafsOnePage();
217 this.drawLeafsTwoPage();
221 // setDragHandler1up()
222 //______________________________________________________________________________
223 GnuBook.prototype.setDragHandler1up = function(div) {
224 div.dragging = false;
226 $(div).bind('mousedown', function(e) {
227 //console.log('mousedown at ' + e.pageY);
229 this.dragging = true;
230 this.prevMouseX = e.pageX;
231 this.prevMouseY = e.pageY;
233 var startX = e.pageX;
234 var startY = e.pageY;
235 var startTop = $('#GBcontainer').attr('scrollTop');
236 var startLeft = $('#GBcontainer').attr('scrollLeft');
241 $(div).bind('mousemove', function(ee) {
242 //console.log('mousemove ' + startY);
244 var offsetX = ee.pageX - this.prevMouseX;
245 var offsetY = ee.pageY - this.prevMouseY;
248 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
249 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
252 this.prevMouseX = ee.pageX;
253 this.prevMouseY = ee.pageY;
258 $(div).bind('mouseup', function(ee) {
259 //console.log('mouseup');
261 this.dragging = false;
265 $(div).bind('mouseleave', function(e) {
266 //console.log('mouseleave');
268 //$(this).unbind('mousemove mouseup');
269 this.dragging = false;
274 // drawLeafsOnePage()
275 //______________________________________________________________________________
276 GnuBook.prototype.drawLeafsOnePage = function() {
277 //alert('drawing leafs!');
281 var scrollTop = $('#GBcontainer').attr('scrollTop');
282 var scrollBottom = scrollTop + $('#GBcontainer').height();
283 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
285 var leafsToDisplay = [];
290 for (i=0; i<this.numLeafs; i++) {
291 var height = parseInt(this.getPageHeight(i)/this.reduce);
293 leafBottom += height;
294 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
295 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
296 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
297 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
298 if (topInView | bottomInView | middleInView) {
299 //console.log('displayed: ' + this.displayedLeafs);
300 //console.log('to display: ' + i);
301 leafsToDisplay.push(i);
303 leafTop += height +10;
307 var firstLeafToDraw = leafsToDisplay[0];
308 this.firstIndex = firstLeafToDraw;
310 // Update hash, but only if we're currently displaying a leaf
311 // Hack that fixes #365790
312 if (this.displayedLeafs.length > 0) {
313 this.updateLocationHash();
316 if ((0 != firstLeafToDraw) && (1 < this.reduce)) {
318 leafsToDisplay.unshift(firstLeafToDraw);
321 var lastLeafToDraw = leafsToDisplay[leafsToDisplay.length-1];
322 if ( ((this.numLeafs-1) != lastLeafToDraw) && (1 < this.reduce) ) {
323 leafsToDisplay.push(lastLeafToDraw+1);
328 for (i=0; i<firstLeafToDraw; i++) {
329 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
332 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
333 var viewWidth = $('#GBcontainer').attr('scrollWidth');
336 for (i=0; i<leafsToDisplay.length; i++) {
337 var leafNum = leafsToDisplay[i];
338 var height = parseInt(this.getPageHeight(leafNum)/this.reduce);
340 if(-1 == jQuery.inArray(leafsToDisplay[i], this.displayedLeafs)) {
341 var width = parseInt(this.getPageWidth(leafNum)/this.reduce);
342 //console.log("displaying leaf " + leafsToDisplay[i] + ' leafTop=' +leafTop);
343 var div = document.createElement("div");
344 div.className = 'GBpagediv1up';
345 div.id = 'pagediv'+leafNum;
346 div.style.position = "absolute";
347 $(div).css('top', leafTop + 'px');
348 var left = (viewWidth-width)>>1;
349 if (left<0) left = 0;
350 $(div).css('left', left+'px');
351 $(div).css('width', width+'px');
352 $(div).css('height', height+'px');
353 //$(div).text('loading...');
355 this.setDragHandler1up(div);
357 $('#GBpageview').append(div);
359 var img = document.createElement("img");
360 img.src = this.getPageURI(leafNum);
361 $(img).css('width', width+'px');
362 $(img).css('height', height+'px');
366 //console.log("not displaying " + leafsToDisplay[i] + ' score=' + jQuery.inArray(leafsToDisplay[i], this.displayedLeafs));
369 leafTop += height +10;
373 for (i=0; i<this.displayedLeafs.length; i++) {
374 if (-1 == jQuery.inArray(this.displayedLeafs[i], leafsToDisplay)) {
375 var leafNum = this.displayedLeafs[i];
376 //console.log('Removing leaf ' + leafNum);
377 //console.log('id='+'#pagediv'+leafNum+ ' top = ' +$('#pagediv'+leafNum).css('top'));
378 $('#pagediv'+leafNum).remove();
380 //console.log('NOT Removing leaf ' + this.displayedLeafs[i]);
384 this.displayedLeafs = leafsToDisplay.slice();
385 this.updateSearchHilites();
387 if (null != this.getPageNum(firstLeafToDraw)) {
388 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
390 $("#GBpagenum").val('');
394 // drawLeafsTwoPage()
395 //______________________________________________________________________________
396 GnuBook.prototype.drawLeafsTwoPage = function() {
397 //alert('drawing two leafs!');
399 var scrollTop = $('#GBcontainer').attr('scrollTop');
400 var scrollBottom = scrollTop + $('#GBcontainer').height();
402 //console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentLeafL);
404 var leafNum = this.currentLeafL;
405 var height = this.getPageHeight(leafNum);
406 var width = this.getPageWidth(leafNum);
407 var handSide= this.getPageSide(leafNum);
409 var leafEdgeWidthL = this.leafEdgeWidth(leafNum);
410 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
411 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
412 var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
413 //console.log(leafEdgeWidthL);
415 var middle = ($('#GBcontainer').width() >> 1);
416 var left = middle - this.twoPageW;
417 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
419 var scaledW = parseInt(this.twoPageH*width/height);
420 left = 10+leafEdgeWidthL;
421 //var right = left+scaledW;
422 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
424 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
426 this.prefetchImg(leafNum);
427 $(this.prefetchedImgs[leafNum]).css({
428 position: 'absolute',
429 /*right: gutter+'px',*/
430 left: gutter-scaledW+'px',
433 backgroundColor: 'rgb(234, 226, 205)',
434 height: this.twoPageH +'px',
435 width: scaledW + 'px',
436 borderRight: '1px solid black',
438 }).appendTo('#GBcontainer');
439 //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
442 var leafNum = this.currentLeafR;
443 var height = this.getPageHeight(leafNum);
444 var width = this.getPageWidth(leafNum);
445 // var left = ($('#GBcontainer').width() >> 1);
448 var scaledW = this.twoPageH*width/height;
449 this.prefetchImg(leafNum);
450 $(this.prefetchedImgs[leafNum]).css({
451 position: 'absolute',
455 backgroundColor: 'rgb(234, 226, 205)',
456 height: this.twoPageH + 'px',
457 width: scaledW + 'px',
458 borderLeft: '1px solid black',
460 }).appendTo('#GBcontainer');
461 //$('#GBcontainer').append(this.prefetchedImgs[leafNum]);
464 this.displayedLeafs = [this.currentLeafL, this.currentLeafR];
465 this.setClickHandlers();
467 this.updatePageNumBox2UP();
470 // updatePageNumBox2UP
471 //______________________________________________________________________________
472 GnuBook.prototype.updatePageNumBox2UP = function() {
473 if (null != this.getPageNum(this.currentLeafL)) {
474 $("#GBpagenum").val(this.getPageNum(this.currentLeafL));
476 $("#GBpagenum").val('');
478 this.updateLocationHash();
482 //______________________________________________________________________________
483 GnuBook.prototype.loadLeafs = function() {
487 if (null == this.timer) {
488 this.timer=setTimeout(function(){self.drawLeafs()},250);
490 clearTimeout(this.timer);
491 this.timer=setTimeout(function(){self.drawLeafs()},250);
497 //______________________________________________________________________________
498 GnuBook.prototype.zoom1up = function(dir) {
499 if (2 == this.mode) { //can only zoom in 1-page mode
505 if (this.reduce <= 0.5) return;
506 this.reduce*=0.5; //zoom in
508 if (this.reduce >= 8) return;
509 this.reduce*=2; //zoom out
512 this.resizePageView();
514 $('#GBpageview').empty()
515 this.displayedLeafs = [];
518 $('#GBzoom').text(100/this.reduce);
522 //______________________________________________________________________________
523 GnuBook.prototype.resizePageView = function() {
526 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
527 var viewWidth = $('#GBcontainer').attr('clientWidth');
529 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
530 var oldViewHeight = $('#GBpageview').height();
531 if (0 != oldViewHeight) {
532 var scrollRatio = oldScrollTop / oldViewHeight;
537 for (i=0; i<this.numLeafs; i++) {
538 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
539 var width = parseInt(this.getPageWidth(i)/this.reduce);
540 if (width>viewWidth) viewWidth=width;
542 $('#GBpageview').height(viewHeight);
543 $('#GBpageview').width(viewWidth);
545 $('#GBcontainer').attr('scrollTop', Math.floor(scrollRatio*viewHeight));
547 this.centerPageView();
553 //______________________________________________________________________________
554 GnuBook.prototype.centerPageView = function() {
556 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
557 var clientWidth = $('#GBcontainer').attr('clientWidth');
558 //console.log('sW='+scrollWidth+' cW='+clientWidth);
559 if (scrollWidth > clientWidth) {
560 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
566 //______________________________________________________________________________
567 // Attempts to jump to page. Returns true if page could be found, false otherwise.
568 GnuBook.prototype.jumpToPage = function(pageNum) {
570 var pageIndex = this.getPageIndex(pageNum);
572 if ('undefined' != typeof(pageIndex)) {
575 this.jumpToIndex(pageIndex);
576 $('#GBcontainer').attr('scrollTop', leafTop);
585 //______________________________________________________________________________
586 GnuBook.prototype.jumpToIndex = function(index) {
588 if (2 == this.mode) {
591 // By checking against min/max we do nothing if requested index
593 if (index < Math.min(this.currentLeafL, this.currentLeafR)) {
594 this.flipBackToIndex(index);
595 } else if (index > Math.max(this.currentLeafL, this.currentLeafR)) {
596 this.flipFwdToIndex(index);
603 for (i=0; i<index; i++) {
604 h = parseInt(this.getPageHeight(i)/this.reduce);
605 leafTop += h + this.padding;
607 //$('#GBcontainer').attr('scrollTop', leafTop);
608 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
615 //______________________________________________________________________________
616 GnuBook.prototype.switchMode = function(mode) {
618 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
620 if (mode == this.mode) return;
623 this.removeSearchHilites();
627 this.switchToolbarMode(mode);
630 this.prepareOnePageView();
632 this.prepareTwoPageView();
637 //prepareOnePageView()
638 //______________________________________________________________________________
639 GnuBook.prototype.prepareOnePageView = function() {
641 // var startLeaf = this.displayedLeafs[0];
642 var startLeaf = this.currentIndex();
644 $('#GBcontainer').empty();
645 $('#GBcontainer').css({
650 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
651 this.resizePageView();
653 this.jumpToIndex(startLeaf);
654 this.displayedLeafs = [];
656 this.drawLeafsOnePage();
657 $('#GBzoom').text(100/this.reduce);
659 // Bind mouse handlers
660 // Disable mouse click to avoid selected/highlighted page images - bug 354239
661 gbPageView.bind('mousedown', function(e) {
664 // Special hack for IE7
665 gbPageView[0].onselectstart = function(e) { return false; };
668 // prepareTwoPageView()
669 //______________________________________________________________________________
670 GnuBook.prototype.prepareTwoPageView = function() {
671 $('#GBcontainer').empty();
673 // We want to display two facing pages. We may be missing
674 // one side of the spread because it is the first/last leaf,
675 // foldouts, missing pages, etc
677 //var targetLeaf = this.displayedLeafs[0];
678 var targetLeaf = this.firstIndex;
680 if (targetLeaf < this.firstDisplayableIndex()) {
681 targetLeaf = this.firstDisplayableIndex();
684 if (targetLeaf > this.lastDisplayableIndex()) {
685 targetLeaf = this.lastDisplayableIndex();
688 this.currentLeafL = null;
689 this.currentLeafR = null;
690 this.pruneUnusedImgs();
692 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
693 this.currentLeafL = currentSpreadIndices[0];
694 this.currentLeafR = currentSpreadIndices[1];
695 this.firstIndex = this.currentLeafL;
697 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
699 // We want to minimize the unused space in two-up mode (maximize the amount of page
700 // shown). We give width to the leaf edges and these widths change (though the sum
701 // of the two remains constant) as we flip through the book. With the book
702 // cover centered and fixed in the GBcontainer div the page images will meet
703 // at the "gutter" which is generally offset from the center.
704 var middle = ($('#GBcontainer').width() >> 1); // Middle of the GBcontainer div
705 //var gutter = middle+parseInt((2*this.currentLeafL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
707 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
709 var scaledWL = this.getPageWidth2UP(this.currentLeafL);
710 var scaledWR = this.getPageWidth2UP(this.currentLeafR);
711 var leafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
712 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
714 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
715 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
717 // The width of the book cover div. The combined width of both pages, twice the width
718 // of the book cover internal padding (2*10) and the page edges
719 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
721 // The height of the book cover div
722 var bookCoverDivHeight = this.twoPageH+20;
724 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
725 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
726 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
727 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
729 this.twoPageDiv = document.createElement('div');
730 $(this.twoPageDiv).attr('id', 'book_div_1').css({
731 border: '1px solid rgb(68, 25, 17)',
732 width: bookCoverDivWidth + 'px',
733 height: bookCoverDivHeight+'px',
734 visibility: 'visible',
735 position: 'absolute',
736 backgroundColor: '#663929',
737 left: bookCoverDivLeft + 'px',
738 top: bookCoverDivTop+'px',
739 MozBorderRadiusTopleft: '7px',
740 MozBorderRadiusTopright: '7px',
741 MozBorderRadiusBottomright: '7px',
742 MozBorderRadiusBottomleft: '7px'
743 }).appendTo('#GBcontainer');
744 //$('#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;"/>');
747 var height = this.getPageHeight(this.currentLeafR);
748 var width = this.getPageWidth(this.currentLeafR);
749 var scaledW = this.twoPageH*width/height;
751 this.leafEdgeR = document.createElement('div');
752 this.leafEdgeR.className = 'leafEdgeR';
753 $(this.leafEdgeR).css({
754 borderStyle: 'solid solid solid none',
755 borderColor: 'rgb(51, 51, 34)',
756 borderWidth: '1px 1px 1px 0px',
757 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
758 width: leafEdgeWidthR + 'px',
759 height: this.twoPageH-1 + 'px',
761 left: gutter+scaledW+'px',
762 top: bookCoverDivTop+10+'px',
764 }).appendTo('#GBcontainer');
766 this.leafEdgeL = document.createElement('div');
767 this.leafEdgeL.className = 'leafEdgeL';
768 $(this.leafEdgeL).css({
769 borderStyle: 'solid none solid solid',
770 borderColor: 'rgb(51, 51, 34)',
771 borderWidth: '1px 0px 1px 1px',
772 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
773 width: leafEdgeWidthL + 'px',
774 height: this.twoPageH-1 + 'px',
775 left: bookCoverDivLeft+10+'px',
776 top: bookCoverDivTop+10+'px',
778 }).appendTo('#GBcontainer');
782 bookCoverDivWidth = 30;
783 bookCoverDivHeight = this.twoPageH+20;
784 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
785 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
787 div = document.createElement('div');
788 $(div).attr('id', 'book_div_2').css({
789 border: '1px solid rgb(68, 25, 17)',
790 width: bookCoverDivWidth+'px',
791 height: bookCoverDivHeight+'px',
792 position: 'absolute',
793 backgroundColor: 'rgb(68, 25, 17)',
794 left: bookCoverDivLeft+'px',
795 top: bookCoverDivTop+'px'
796 }).appendTo('#GBcontainer');
797 //$('#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;"/>');
799 bookCoverDivWidth = this.twoPageW*2;
800 bookCoverDivHeight = this.twoPageH;
801 bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
802 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
805 this.prepareTwoPagePopUp();
807 this.displayedLeafs = [];
809 //this.leafsToDisplay=[firstLeaf, firstLeaf+1];
810 //console.log('leafsToDisplay: ' + this.leafsToDisplay[0] + ' ' + this.leafsToDisplay[1]);
812 this.drawLeafsTwoPage();
813 this.updateSearchHilites2UP();
816 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentLeafL)).toString().substr(0,4));
819 // prepareTwoPagePopUp()
821 // This function prepares the "View leaf n" popup that shows while the mouse is
822 // over the left/right "stack of sheets" edges. It also binds the mouse
823 // events for these divs.
824 //______________________________________________________________________________
825 GnuBook.prototype.prepareTwoPagePopUp = function() {
826 this.twoPagePopUp = document.createElement('div');
827 $(this.twoPagePopUp).css({
828 border: '1px solid black',
830 position: 'absolute',
831 fontFamily: 'sans-serif',
834 backgroundColor: 'rgb(255, 255, 238)',
836 }).appendTo('#GBcontainer');
837 $(this.twoPagePopUp).hide();
839 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
840 $(e.data.twoPagePopUp).show();
843 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
844 $(e.data.twoPagePopUp).hide();
847 $(this.leafEdgeL).bind('click', this, function(e) {
849 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
850 e.data.jumpToIndex(jumpIndex);
853 $(this.leafEdgeR).bind('click', this, function(e) {
855 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
856 e.data.jumpToIndex(jumpIndex);
859 $(this.leafEdgeR).bind('mousemove', this, function(e) {
861 var jumpLeaf = e.data.jumpIndexForRightEdgePageX(e.pageX);
862 $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
864 $(e.data.twoPagePopUp).css({
865 left: e.pageX +5+ 'px',
866 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
870 $(this.leafEdgeL).bind('mousemove', this, function(e) {
872 var jumpLeaf = e.data.jumpIndexForLeftEdgePageX(e.pageX);
873 $(e.data.twoPagePopUp).text('View Leaf '+jumpLeaf);
875 $(e.data.twoPagePopUp).css({
876 left: e.pageX - $(e.data.twoPagePopUp).width() - 30 + 'px',
877 top: e.pageY-$('#GBcontainer').offset().top+ 'px'
882 // calculateSpreadSize()
883 //______________________________________________________________________________
884 // Calculates 2-page spread dimensions based on this.currentLeafL and
886 // This function sets this.twoPageH, twoPageW, and twoPageRatio
888 GnuBook.prototype.calculateSpreadSize = function() {
889 var firstLeaf = this.currentLeafL;
890 var secondLeaf = this.currentLeafR;
891 //console.log('first page is ' + firstLeaf);
893 var canon5Dratio = 1.5;
895 var firstLeafRatio = this.getPageHeight(firstLeaf) / this.getPageWidth(firstLeaf);
896 var secondLeafRatio = this.getPageHeight(secondLeaf) / this.getPageWidth(secondLeaf);
897 //console.log('firstLeafRatio = ' + firstLeafRatio + ' secondLeafRatio = ' + secondLeafRatio);
900 if (Math.abs(firstLeafRatio - canon5Dratio) < Math.abs(secondLeafRatio - canon5Dratio)) {
901 ratio = firstLeafRatio;
902 //console.log('using firstLeafRatio ' + ratio);
904 ratio = secondLeafRatio;
905 //console.log('using secondLeafRatio ' + ratio);
908 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
909 var maxLeafEdgeWidth = parseInt($('#GBcontainer').width() * 0.1);
910 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
912 $('#GBcontainer').css('overflow', 'hidden');
914 var idealWidth = ($('#GBcontainer').width() - 30 - totalLeafEdgeWidth)>>1;
915 var idealHeight = $('#GBcontainer').height() - 30;
916 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
918 if (idealHeight/ratio <= idealWidth) {
920 idealWidth = parseInt(idealHeight/ratio);
923 idealHeight = parseInt(idealWidth*ratio);
926 this.twoPageH = idealHeight;
927 this.twoPageW = idealWidth;
928 this.twoPageRatio = ratio;
929 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
934 //______________________________________________________________________________
935 // Returns the currently active index.
936 GnuBook.prototype.currentIndex = function() {
937 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
938 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
939 return this.firstIndex;
941 throw 'currentIndex called for unimplemented mode ' + this.mode;
946 //______________________________________________________________________________
947 // Flip the right page over onto the left
948 GnuBook.prototype.right = function() {
949 if ('rl' != this.pageProgression) {
959 //______________________________________________________________________________
960 // Flip to the rightmost page
961 GnuBook.prototype.rightmost = function() {
962 if ('rl' != this.pageProgression) {
970 //______________________________________________________________________________
971 // Flip the left page over onto the right.
972 GnuBook.prototype.left = function() {
973 if ('rl' != this.pageProgression) {
983 //______________________________________________________________________________
984 // Flip to the leftmost page
985 GnuBook.prototype.leftmost = function() {
986 if ('rl' != this.pageProgression) {
994 //______________________________________________________________________________
995 GnuBook.prototype.next = function() {
996 if (2 == this.mode) {
998 this.flipFwdToIndex(null);
1000 if (this.firstIndex < this.lastDisplayableIndex()) {
1001 this.jumpToIndex(this.firstIndex+1);
1007 //______________________________________________________________________________
1008 GnuBook.prototype.prev = function() {
1009 if (2 == this.mode) {
1011 this.flipBackToIndex(null);
1013 if (this.firstIndex >= 1) {
1014 this.jumpToIndex(this.firstIndex-1);
1019 GnuBook.prototype.first = function() {
1020 if (2 == this.mode) {
1021 this.jumpToIndex(2);
1024 this.jumpToIndex(0);
1028 GnuBook.prototype.last = function() {
1029 if (2 == this.mode) {
1030 this.jumpToIndex(this.lastDisplayableIndex());
1033 this.jumpToIndex(this.lastDisplayableIndex());
1037 // flipBackToIndex()
1038 //______________________________________________________________________________
1039 // to flip back one spread, pass index=null
1040 GnuBook.prototype.flipBackToIndex = function(index) {
1041 if (1 == this.mode) return;
1043 var leftIndex = this.currentLeafL;
1045 // $$$ Need to change this to be able to see first spread.
1046 // See https://bugs.launchpad.net/gnubook/+bug/296788
1047 if (leftIndex <= 2) return;
1048 if (this.animating) return;
1050 if (null != this.leafEdgeTmp) {
1051 alert('error: leafEdgeTmp should be null!');
1055 if (null == index) {
1056 index = leftIndex-2;
1058 //if (index<0) return;
1060 var previousIndices = this.getSpreadIndices(index);
1062 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1066 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1068 this.animating = true;
1070 if ('rl' != this.pageProgression) {
1071 // Assume LTR and we are going backward
1072 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1073 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1076 // RTL and going backward
1077 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1078 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1082 // flipLeftToRight()
1083 //______________________________________________________________________________
1084 // Flips the page on the left towards the page on the right
1085 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1087 var leftLeaf = this.currentLeafL;
1089 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1090 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1091 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1093 var currWidthL = this.getPageWidth2UP(leftLeaf);
1094 var newWidthL = this.getPageWidth2UP(newIndexL);
1095 var newWidthR = this.getPageWidth2UP(newIndexR);
1097 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1099 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1100 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1102 //animation strategy:
1103 // 0. remove search highlight, if any.
1104 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1105 // of the left leaf and where the user clicked in the leaf edge.
1106 // Note that if this function was triggered by left() and not a
1107 // mouse click, the width of leafEdgeTmp is very small (zero px).
1108 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1109 // leftLeaf to width=0.
1110 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1111 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1112 // its new full width.
1113 // 4. After step 3 is finished, do the following:
1114 // - remove leafEdgeTmp from the dom.
1115 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1116 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1117 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1118 // and width=newLeafEdgeWidthL.
1119 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1120 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1121 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1122 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1123 // - prefetch new adjacent leafs.
1124 // - set up click handlers for both new left and right leafs.
1125 // - redraw the search highlight.
1126 // - update the pagenum box and the url.
1129 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1131 this.leafEdgeTmp = document.createElement('div');
1132 $(this.leafEdgeTmp).css({
1133 borderStyle: 'solid none solid solid',
1134 borderColor: 'rgb(51, 51, 34)',
1135 borderWidth: '1px 0px 1px 1px',
1136 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1137 width: leafEdgeTmpW + 'px',
1138 height: this.twoPageH-1 + 'px',
1139 left: leftEdgeTmpLeft + 'px',
1141 position: 'absolute',
1143 }).appendTo('#GBcontainer');
1145 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1146 $(this.leafEdgeL).css({
1147 width: newLeafEdgeWidthL+'px',
1148 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1151 // Left gets the offset of the current left leaf from the document
1152 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1153 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1154 var right = $('#GBcontainer').width()-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBcontainer').offset().left-2+'px';
1155 // We change the left leaf to right positioning
1156 $(this.prefetchedImgs[leftLeaf]).css({
1161 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1163 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1165 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1166 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1170 this.removeSearchHilites();
1172 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1173 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1175 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1176 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1178 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1179 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1180 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1182 $(self.leafEdgeR).css({
1183 // Moves the right leaf edge
1184 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1185 left: gutter+newWidthR+'px'
1188 $(self.leafEdgeL).css({
1189 // Moves and resizes the left leaf edge
1190 width: newLeafEdgeWidthL+'px',
1191 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1195 $(self.twoPageDiv).css({
1196 // Resizes the brown border div
1197 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1198 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1201 $(self.leafEdgeTmp).remove();
1202 self.leafEdgeTmp = null;
1204 self.currentLeafL = newIndexL;
1205 self.currentLeafR = newIndexR;
1206 self.firstIndex = self.currentLeafL;
1207 self.displayedLeafs = [newIndexL, newIndexR];
1208 self.setClickHandlers();
1209 self.pruneUnusedImgs();
1211 self.animating = false;
1213 self.updateSearchHilites2UP();
1214 self.updatePageNumBox2UP();
1215 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1217 if (self.animationFinishedCallback) {
1218 self.animationFinishedCallback();
1219 self.animationFinishedCallback = null;
1227 //______________________________________________________________________________
1228 // Whether we flip left or right is dependent on the page progression
1229 // to flip forward one spread, pass index=null
1230 GnuBook.prototype.flipFwdToIndex = function(index) {
1232 if (this.animating) return;
1234 if (null != this.leafEdgeTmp) {
1235 alert('error: leafEdgeTmp should be null!');
1239 if (null == index) {
1240 index = this.currentLeafR+2; // $$$ assumes indices are continuous
1242 if (index > this.lastDisplayableIndex()) return;
1244 this.animating = true;
1246 var nextIndices = this.getSpreadIndices(index);
1248 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1250 if ('rl' != this.pageProgression) {
1251 // We did not specify RTL
1252 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1253 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1256 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1257 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1261 // flipRightToLeft(nextL, nextR, gutter)
1262 // $$$ better not to have to pass gutter in
1263 //______________________________________________________________________________
1264 // Flip from left to right and show the nextL and nextR indices on those sides
1265 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1266 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentLeafL);
1267 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1268 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1269 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1271 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1273 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1275 var scaledW = this.getPageWidth2UP(this.currentLeafR);
1277 var middle = ($('#GBcontainer').width() >> 1);
1278 var currGutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1280 this.leafEdgeTmp = document.createElement('div');
1281 $(this.leafEdgeTmp).css({
1282 borderStyle: 'solid none solid solid',
1283 borderColor: 'rgb(51, 51, 34)',
1284 borderWidth: '1px 0px 1px 1px',
1285 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1286 width: leafEdgeTmpW + 'px',
1287 height: this.twoPageH-1 + 'px',
1288 left: currGutter+scaledW+'px',
1290 position: 'absolute',
1292 }).appendTo('#GBcontainer');
1294 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1295 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1297 var currWidthL = this.getPageWidth2UP(this.currentLeafL);
1298 var currWidthR = this.getPageWidth2UP(this.currentLeafR);
1299 var newWidthL = this.getPageWidth2UP(newIndexL);
1300 var newWidthR = this.getPageWidth2UP(newIndexR);
1302 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1304 var self = this; // closure-tastic!
1306 var speed = this.flipSpeed;
1308 this.removeSearchHilites();
1310 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1311 $(this.prefetchedImgs[this.currentLeafR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1312 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1313 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1314 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1316 $(self.leafEdgeL).css({
1317 width: newLeafEdgeWidthL+'px',
1318 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1321 $(self.twoPageDiv).css({
1322 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1323 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1326 $(self.leafEdgeTmp).remove();
1327 self.leafEdgeTmp = null;
1329 self.currentLeafL = newIndexL;
1330 self.currentLeafR = newIndexR;
1331 self.firstIndex = self.currentLeafL;
1332 self.displayedLeafs = [newIndexL, newIndexR];
1333 self.setClickHandlers();
1334 self.pruneUnusedImgs();
1336 self.animating = false;
1339 self.updateSearchHilites2UP();
1340 self.updatePageNumBox2UP();
1341 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1343 if (self.animationFinishedCallback) {
1344 self.animationFinishedCallback();
1345 self.animationFinishedCallback = null;
1352 //______________________________________________________________________________
1353 GnuBook.prototype.setClickHandlers = function() {
1355 $(this.prefetchedImgs[this.currentLeafL]).click(function() {
1360 $(this.prefetchedImgs[this.currentLeafR]).click(function() {
1368 //______________________________________________________________________________
1369 GnuBook.prototype.prefetchImg = function(leafNum) {
1370 if (undefined == this.prefetchedImgs[leafNum]) {
1371 //console.log('prefetching ' + leafNum);
1372 var img = document.createElement("img");
1373 img.src = this.getPageURI(leafNum);
1374 this.prefetchedImgs[leafNum] = img;
1379 // prepareFlipLeftToRight()
1381 //______________________________________________________________________________
1383 // Prepare to flip the left page towards the right. This corresponds to moving
1384 // backward when the page progression is left to right.
1385 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1387 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1389 this.prefetchImg(prevL);
1390 this.prefetchImg(prevR);
1392 var height = this.getPageHeight(prevL);
1393 var width = this.getPageWidth(prevL);
1394 var middle = ($('#GBcontainer').width() >> 1);
1395 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1396 var scaledW = this.twoPageH*width/height;
1398 // The gutter is the dividing line between the left and right pages.
1399 // It is offset from the middle to create the illusion of thickness to the pages
1400 var gutter = middle + this.gutterOffsetForIndex(prevL);
1402 //console.log(' gutter for ' + prevL + ' is ' + gutter);
1403 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1404 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1406 $(this.prefetchedImgs[prevL]).css({
1407 position: 'absolute',
1408 /*right: middle+'px',*/
1409 left: gutter-scaledW+'px',
1412 backgroundColor: 'rgb(234, 226, 205)',
1413 height: this.twoPageH,
1414 width: scaledW+'px',
1415 borderRight: '1px solid black',
1419 $('#GBcontainer').append(this.prefetchedImgs[prevL]);
1421 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1423 $(this.prefetchedImgs[prevR]).css({
1424 position: 'absolute',
1428 backgroundColor: 'rgb(234, 226, 205)',
1429 height: this.twoPageH,
1431 borderLeft: '1px solid black',
1435 $('#GBcontainer').append(this.prefetchedImgs[prevR]);
1442 // prepareFlipRightToLeft()
1443 //______________________________________________________________________________
1444 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1446 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1448 this.prefetchImg(nextL);
1449 this.prefetchImg(nextR);
1451 var height = this.getPageHeight(nextR);
1452 var width = this.getPageWidth(nextR);
1453 var middle = ($('#GBcontainer').width() >> 1);
1454 var top = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1455 var scaledW = this.twoPageH*width/height;
1457 var gutter = middle + this.gutterOffsetForIndex(nextL);
1459 //console.log('right to left to %d gutter is %d', nextL, gutter);
1461 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1462 $(this.prefetchedImgs[nextR]).css({
1463 position: 'absolute',
1466 backgroundColor: 'rgb(234, 226, 205)',
1467 height: this.twoPageH,
1468 width: scaledW+'px',
1469 borderLeft: '1px solid black',
1473 $('#GBcontainer').append(this.prefetchedImgs[nextR]);
1475 height = this.getPageHeight(nextL);
1476 width = this.getPageWidth(nextL);
1477 scaledW = this.twoPageH*width/height;
1479 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1480 $(this.prefetchedImgs[nextL]).css({
1481 position: 'absolute',
1482 right: $('#GBcontainer').width()-gutter+'px',
1484 backgroundColor: 'rgb(234, 226, 205)',
1485 height: this.twoPageH,
1487 borderRight: '1px solid black',
1491 $('#GBcontainer').append(this.prefetchedImgs[nextL]);
1497 // getNextLeafs() -- NOT RTL AWARE
1498 //______________________________________________________________________________
1499 // GnuBook.prototype.getNextLeafs = function(o) {
1500 // //TODO: we might have two left or two right leafs in a row (damaged book)
1501 // //For now, assume that leafs are contiguous.
1503 // //return [this.currentLeafL+2, this.currentLeafL+3];
1504 // o.L = this.currentLeafL+2;
1505 // o.R = this.currentLeafL+3;
1508 // getprevLeafs() -- NOT RTL AWARE
1509 //______________________________________________________________________________
1510 // GnuBook.prototype.getPrevLeafs = function(o) {
1511 // //TODO: we might have two left or two right leafs in a row (damaged book)
1512 // //For now, assume that leafs are contiguous.
1514 // //return [this.currentLeafL-2, this.currentLeafL-1];
1515 // o.L = this.currentLeafL-2;
1516 // o.R = this.currentLeafL-1;
1519 // pruneUnusedImgs()
1520 //______________________________________________________________________________
1521 GnuBook.prototype.pruneUnusedImgs = function() {
1522 //console.log('current: ' + this.currentLeafL + ' ' + this.currentLeafR);
1523 for (var key in this.prefetchedImgs) {
1524 //console.log('key is ' + key);
1525 if ((key != this.currentLeafL) && (key != this.currentLeafR)) {
1526 //console.log('removing key '+ key);
1527 $(this.prefetchedImgs[key]).remove();
1529 if ((key < this.currentLeafL-4) || (key > this.currentLeafR+4)) {
1530 //console.log('deleting key '+ key);
1531 delete this.prefetchedImgs[key];
1537 //______________________________________________________________________________
1538 GnuBook.prototype.prefetch = function() {
1540 var lim = this.currentLeafL-4;
1542 lim = Math.max(lim, 0);
1543 for (i = lim; i < this.currentLeafL; i++) {
1544 this.prefetchImg(i);
1547 if (this.numLeafs > (this.currentLeafR+1)) {
1548 lim = Math.min(this.currentLeafR+4, this.numLeafs-1);
1549 for (i=this.currentLeafR+1; i<=lim; i++) {
1550 this.prefetchImg(i);
1555 // getPageWidth2UP()
1556 //______________________________________________________________________________
1557 GnuBook.prototype.getPageWidth2UP = function(index) {
1558 var height = this.getPageHeight(index);
1559 var width = this.getPageWidth(index);
1560 return Math.floor(this.twoPageH*width/height);
1564 //______________________________________________________________________________
1565 GnuBook.prototype.search = function(term) {
1566 $('#GnuBookSearchScript').remove();
1567 var script = document.createElement("script");
1568 script.setAttribute('id', 'GnuBookSearchScript');
1569 script.setAttribute("type", "text/javascript");
1570 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');
1571 document.getElementsByTagName('head')[0].appendChild(script);
1574 // GBSearchCallback()
1575 //______________________________________________________________________________
1576 GnuBook.prototype.GBSearchCallback = function(txt) {
1578 if (jQuery.browser.msie) {
1579 var dom=new ActiveXObject("Microsoft.XMLDOM");
1583 var parser = new DOMParser();
1584 var dom = parser.parseFromString(txt, "text/xml");
1587 $('#GnuBookSearchResults').empty();
1588 $('#GnuBookSearchResults').append('<ul>');
1590 for (var key in this.searchResults) {
1591 if (null != this.searchResults[key].div) {
1592 $(this.searchResults[key].div).remove();
1594 delete this.searchResults[key];
1597 var pages = dom.getElementsByTagName('PAGE');
1599 if (0 == pages.length) {
1600 // $$$ it would be nice to echo the (sanitized) search result here
1601 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1603 for (var i = 0; i < pages.length; i++){
1604 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1607 var re = new RegExp (/_(\d{4})/);
1608 var reMatch = re.exec(pages[i].getAttribute('file'));
1609 var leafNum = parseInt(reMatch[1], 10);
1610 //var leafNum = parseInt(pages[i].getAttribute('file').substr(1), 10);
1612 var children = pages[i].childNodes;
1614 for (var j=0; j<children.length; j++) {
1615 //console.log(j + ' - ' + children[j].nodeName);
1616 //console.log(children[j].firstChild.nodeValue);
1617 if ('CONTEXT' == children[j].nodeName) {
1618 context += children[j].firstChild.nodeValue;
1619 } else if ('WORD' == children[j].nodeName) {
1620 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1622 var index = this.leafNumToIndex(leafNum);
1623 if (null != index) {
1624 //coordinates are [left, bottom, right, top, [baseline]]
1625 //we'll skip baseline for now...
1626 var coords = children[j].getAttribute('coords').split(',',4);
1627 if (4 == coords.length) {
1628 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1633 //TODO: remove hardcoded instance name
1634 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">Leaf ' + leafNum + '</a></b> - ' + context+'</li>');
1637 $('#GnuBookSearchResults').append('</ul>');
1639 this.updateSearchHilites();
1642 // updateSearchHilites()
1643 //______________________________________________________________________________
1644 GnuBook.prototype.updateSearchHilites = function() {
1645 if (2 == this.mode) {
1646 this.updateSearchHilites2UP();
1648 this.updateSearchHilites1UP();
1652 // showSearchHilites1UP()
1653 //______________________________________________________________________________
1654 GnuBook.prototype.updateSearchHilites1UP = function() {
1656 for (var key in this.searchResults) {
1658 if (-1 != jQuery.inArray(parseInt(key), this.displayedLeafs)) {
1659 var result = this.searchResults[key];
1660 if(null == result.div) {
1661 result.div = document.createElement('div');
1662 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1663 //console.log('appending ' + key);
1666 width: (result.r-result.l)/this.reduce + 'px',
1667 height: (result.b-result.t)/this.reduce + 'px',
1668 left: (result.l)/this.reduce + 'px',
1669 top: (result.t)/this.reduce +'px'
1673 //console.log(key + ' not displayed');
1674 this.searchResults[key].div=null;
1679 // showSearchHilites2UP()
1680 //______________________________________________________________________________
1681 GnuBook.prototype.updateSearchHilites2UP = function() {
1683 var middle = ($('#GBcontainer').width() >> 1);
1685 for (var key in this.searchResults) {
1686 key = parseInt(key, 10);
1687 if (-1 != jQuery.inArray(key, this.displayedLeafs)) {
1688 var result = this.searchResults[key];
1689 if(null == result.div) {
1690 result.div = document.createElement('div');
1691 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBcontainer');
1692 //console.log('appending ' + key);
1695 var height = this.getPageHeight(key);
1696 var width = this.getPageWidth(key)
1697 var reduce = this.twoPageH/height;
1698 var scaledW = parseInt(width*reduce);
1700 var gutter = middle + this.gutterOffsetForIndex(this.currentLeafL);
1702 if ('L' == this.getPageSide(key)) {
1703 var pageL = gutter-scaledW;
1707 var pageT = ($('#GBcontainer').height() - this.twoPageH) >> 1;
1710 width: (result.r-result.l)*reduce + 'px',
1711 height: (result.b-result.t)*reduce + 'px',
1712 left: pageL+(result.l)*reduce + 'px',
1713 top: pageT+(result.t)*reduce +'px'
1717 //console.log(key + ' not displayed');
1718 if (null != this.searchResults[key].div) {
1719 //console.log('removing ' + key);
1720 $(this.searchResults[key].div).remove();
1722 this.searchResults[key].div=null;
1727 // removeSearchHilites()
1728 //______________________________________________________________________________
1729 GnuBook.prototype.removeSearchHilites = function() {
1730 for (var key in this.searchResults) {
1731 if (null != this.searchResults[key].div) {
1732 $(this.searchResults[key].div).remove();
1733 this.searchResults[key].div=null;
1739 //______________________________________________________________________________
1740 GnuBook.prototype.showEmbedCode = function() {
1741 if (null != this.embedPopup) { // check if already showing
1745 this.embedPopup = document.createElement("div");
1746 $(this.embedPopup).css({
1747 position: 'absolute',
1749 left: ($('#GBcontainer').width()-400)/2 + 'px',
1752 border: "3px double #999999",
1754 backgroundColor: "#fff"
1755 }).appendTo('#GnuBook');
1757 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1758 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>';
1759 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1760 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1762 this.embedPopup.innerHTML = htmlStr;
1763 $(this.embedPopup).find('input').bind('click', function() {
1769 //______________________________________________________________________________
1770 GnuBook.prototype.autoToggle = function() {
1772 var bComingFrom1up = false;
1773 if (2 != this.mode) {
1774 bComingFrom1up = true;
1779 if (null == this.autoTimer) {
1780 this.flipSpeed = 2000;
1782 // $$$ Draw events currently cause layout problems when they occur during animation.
1783 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1784 // we workaround for now by not triggering immediate animation in that case.
1785 // See https://bugs.launchpad.net/gnubook/+bug/328327
1786 if (('rl' == this.pageProgression) && bComingFrom1up) {
1787 // don't flip immediately -- wait until timer fires
1790 this.flipFwdToIndex();
1793 $('#GBtoolbar .play').hide();
1794 $('#GBtoolbar .pause').show();
1795 this.autoTimer=setInterval(function(){
1796 if (self.animating) {return;}
1798 if (Math.max(self.currentLeafL, self.currentLeafR) >= self.lastDisplayableIndex()) {
1799 self.flipBackToIndex(1); // $$$ really what we want?
1801 self.flipFwdToIndex();
1810 //______________________________________________________________________________
1811 GnuBook.prototype.autoStop = function() {
1812 if (null != this.autoTimer) {
1813 clearInterval(this.autoTimer);
1814 this.flipSpeed = 'fast';
1815 $('#GBtoolbar .pause').hide();
1816 $('#GBtoolbar .play').show();
1817 this.autoTimer = null;
1821 // keyboardNavigationIsDisabled(event)
1822 // - returns true if keyboard navigation should be disabled for the event
1823 //______________________________________________________________________________
1824 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1825 if (event.target.tagName == "INPUT") {
1831 // gutterOffsetForIndex
1832 //______________________________________________________________________________
1834 // Returns the gutter offset for the spread containing the given index.
1835 // This function supports RTL
1836 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1838 // To find the offset of the gutter from the middle we calculate our percentage distance
1839 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1840 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1842 // But then again for RTL it's the opposite
1843 if ('rl' == this.pageProgression) {
1851 //______________________________________________________________________________
1852 // Returns the width of the leaf edge div for the page with index given
1853 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1854 // $$$ could there be single pixel rounding errors for L vs R?
1855 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1856 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1858 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1862 // jumpIndexForLeftEdgePageX
1863 //______________________________________________________________________________
1864 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1865 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1866 if ('rl' != this.pageProgression) {
1867 // LTR - flipping backward
1868 var jumpLeaf = this.currentLeafL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1869 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1870 jumpLeaf = Math.min(jumpLeaf, this.currentLeafL - 2);
1871 jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1874 var jumpLeaf = this.currentLeafL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1875 jumpLeaf = Math.max(jumpLeaf, this.currentLeafL + 2);
1876 jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1881 // jumpIndexForRightEdgePageX
1882 //______________________________________________________________________________
1883 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1884 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1885 if ('rl' != this.pageProgression) {
1887 var jumpLeaf = this.currentLeafR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1888 jumpLeaf = Math.max(jumpLeaf, this.currentLeafR + 2);
1889 jumpLeaf = Math.min(jumpLeaf, this.lastDisplayableIndex());
1892 var jumpLeaf = this.currentLeafR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1893 jumpLeaf = Math.min(jumpLeaf, this.currentLeafR - 2);
1894 jumpLeaf = Math.max(jumpLeaf, this.firstDisplayableIndex());
1899 GnuBook.prototype.initToolbar = function(mode, ui) {
1900 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1901 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1902 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1903 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1904 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
1905 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1906 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1907 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1910 if (ui == "embed") {
1911 $("#GnuBook a.logo").attr("target","_blank");
1914 // $$$ turn this into a member variable
1915 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
1917 // We build in mode 2
1918 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
1919 + "<button class='GBicon rollover embed' />"
1920 + "<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>"
1921 + "<div class='GBtoolbarmode2' style='display: inline'><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>"
1922 + "<div class='GBtoolbarmode1' style='display: hidden'><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>"
1923 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
1925 this.bindToolbarNavHandlers(jToolbar);
1927 // Setup tooltips -- later we could load these from a file for i18n
1928 var titles = { '.logo': 'Go to Archive.org',
1929 '.zoom_in': 'Zoom in',
1930 '.zoom_out': 'Zoom out',
1931 '.one_page_mode': 'One-page view',
1932 '.two_page_mode': 'Two-page view',
1933 '.embed': 'Embed bookreader',
1934 '.book_left': 'Flip left',
1935 '.book_right': 'Flip right',
1936 '.book_up': 'Page up',
1937 '.book_down': 'Page down',
1940 '.book_top': 'First page',
1941 '.book_bottom': 'Last page'
1943 if ('rl' == this.pageProgression) {
1944 titles['.book_leftmost'] = 'Last page';
1945 titles['.book_rightmost'] = 'First page';
1947 titles['.book_leftmost'] = 'First page';
1948 titles['.book_rightmost'] = 'Last page';
1951 for (var icon in titles) {
1952 jToolbar.find(icon).attr('title', titles[icon]);
1955 // Switch to requested mode -- binds other click handlers
1956 this.switchToolbarMode(mode);
1961 // switchToolbarMode
1962 //______________________________________________________________________________
1963 // Update the toolbar for the given mode (changes navigation buttons)
1964 // $$$ we should soon split the toolbar out into its own module
1965 GnuBook.prototype.switchToolbarMode = function(mode) {
1968 $('#GBtoolbar .GBtoolbarmode2').hide();
1969 $('#GBtoolbar .GBtoolbarmode1').css('display', 'inline').show();
1972 $('#GBtoolbar .GBtoolbarmode1').hide();
1973 $('#GBtoolbar .GBtoolbarmode2').css('display', 'inline').show();
1977 // bindToolbarNavHandlers
1978 //______________________________________________________________________________
1979 // Binds the toolbar handlers
1980 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
1982 jToolbar.find('.book_left').bind('click', function(e) {
1987 jToolbar.find('.book_right').bind('click', function(e) {
1992 jToolbar.find('.book_up').bind('click', function(e) {
1997 jToolbar.find('.book_down').bind('click', function(e) {
2002 jToolbar.find('.embed').bind('click', function(e) {
2007 jToolbar.find('.play').bind('click', function(e) {
2012 jToolbar.find('.pause').bind('click', function(e) {
2017 jToolbar.find('.book_top').bind('click', function(e) {
2022 jToolbar.find('.book_bottom').bind('click', function(e) {
2027 jToolbar.find('.book_leftmost').bind('click', function(e) {
2032 jToolbar.find('.book_rightmost').bind('click', function(e) {
2038 // firstDisplayableIndex
2039 //______________________________________________________________________________
2040 // Returns the index of the first visible page, dependent on the mode.
2041 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2042 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2043 GnuBook.prototype.firstDisplayableIndex = function() {
2044 if (this.mode == 0) {
2047 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2051 // lastDisplayableIndex
2052 //______________________________________________________________________________
2053 // Returns the index of the last visible page, dependent on the mode.
2054 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2055 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2056 GnuBook.prototype.lastDisplayableIndex = function() {
2057 if (this.mode == 2) {
2058 if (this.lastDisplayableIndex2up === null) {
2059 // Calculate and cache
2060 var candidate = this.numLeafs - 1;
2061 for ( ; candidate >= 0; candidate--) {
2062 var spreadIndices = this.getSpreadIndices(candidate);
2063 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2067 this.lastDisplayableIndex2up = candidate;
2069 return this.lastDisplayableIndex2up;
2071 return this.numLeafs - 1;
2075 // shortTitle(maximumCharacters)
2077 // Returns a shortened version of the title with the maximum number of characters
2078 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2079 if (this.bookTitle.length < maximumCharacters) {
2080 return this.bookTitle;
2083 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2090 // Parameter related functions
2092 // updateFromParams(params)
2094 // Update ourselves from the params object.
2096 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2097 GnuBook.prototype.updateFromParams = function(params) {
2098 if ('undefined' != typeof(params.mode)) {
2099 this.switchMode(params.mode);
2102 // $$$ process /search
2103 // $$$ process /zoom
2105 // We only respect page if index is not set
2106 if ('undefined' != typeof(params.index)) {
2107 if (params.index != this.currentIndex()) {
2108 this.jumpToIndex(params.index);
2110 } else if ('undefined' != typeof(params.page)) {
2111 if (params.page != this.getPageNum(this.currentIndex())) {
2112 this.jumpToPage(params.page);
2116 // $$$ process /region
2117 // $$$ process /highlight
2120 // paramsFromFragment(urlFragment)
2122 // Returns a object with configuration parametes from a URL fragment.
2124 // E.g paramsFromFragment(window.location.hash)
2125 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2126 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2130 // For convenience we allow an initial # character (as from window.location.hash)
2131 // but don't require it
2132 if (urlFragment.substr(0,1) == '#') {
2133 urlFragment = urlFragment.substr(1);
2136 // Simple #nn syntax
2137 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2138 if ( !isNaN(oldStyleLeafNum) ) {
2139 params.index = oldStyleLeafNum;
2141 // Done processing if using old-style syntax
2145 // Split into key-value pairs
2146 var urlArray = urlFragment.split('/');
2148 for (var i = 0; i < urlArray.length; i += 2) {
2149 urlHash[urlArray[i]] = urlArray[i+1];
2153 if ('1up' == urlHash['mode']) {
2154 params.mode = this.constMode1up;
2155 } else if ('2up' == urlHash['mode']) {
2156 params.mode = this.constMode2up;
2160 if ('undefined' != typeof(urlHash['page'])) {
2161 // page was set -- may not be int
2162 params.page = urlHash['page'];
2165 // $$$ process /region
2166 // $$$ process /search
2167 // $$$ process /highlight
2172 // paramsFromCurrent()
2174 // Create a params object from the current parameters.
2175 GnuBook.prototype.paramsFromCurrent = function() {
2179 var pageNum = this.getPageNum(this.currentIndex());
2180 if ((pageNum === 0) || pageNum) {
2181 params.page = pageNum;
2184 params.index = this.currentIndex();
2185 params.mode = this.mode;
2194 // fragmentFromParams(params)
2196 // Create a fragment string from the params object.
2197 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2198 GnuBook.prototype.fragmentFromParams = function(params) {
2199 var separator = '/';
2203 if ('undefined' != typeof(params.page)) {
2204 fragments.push('page', params.page);
2206 // Don't have page numbering -- use index instead
2207 fragments.push('page', 'n' + params.index);
2215 if ('undefined' != typeof(params.mode)) {
2216 if (params.mode == this.constMode1up) {
2217 fragments.push('mode', '1up');
2218 } else if (params.mode == this.constMode2up) {
2219 fragments.push('mode', '2up');
2221 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2225 return fragments.join(separator);
2228 // getPageIndex(pageNum)
2230 // Returns the index of the given page number, or undefined
2231 GnuBook.prototype.getPageIndex = function(pageNum) {
2232 var pageIndex = undefined;
2234 // Check for special "nXX" page number
2235 if (pageNum.slice(0,1) == 'n') {
2237 var pageIntStr = pageNum.slice(1, pageNum.length);
2238 pageIndex = parseInt(pageIntStr);
2241 // Do nothing... will run through page names and see if one matches
2246 for (i=0; i<this.numLeafs; i++) {
2247 if (this.getPageNum(i) == pageNum) {
2256 // updateLocationHash
2258 // Update the location hash from the current parameters. Call this instead of manually
2259 // using window.location.replace
2260 GnuBook.prototype.updateLocationHash = function() {
2261 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2262 window.location.replace(newHash);
2264 // This is the variable checked in the timer. Only user-generated changes
2265 // to the URL will trigger the event.
2266 this.oldLocationHash = newHash;
2269 // startLocationPolling
2271 // Starts polling of window.location to see hash fragment changes
2272 GnuBook.prototype.startLocationPolling = function() {
2273 var self = this; // remember who I am
2274 self.oldLocationHash = window.location.hash;
2276 if (this.locationPollId) {
2277 clearInterval(this.locationPollID);
2278 this.locationPollId = null;
2281 this.locationPollId = setInterval(function() {
2282 var newHash = window.location.hash;
2283 if (newHash != self.oldLocationHash) {
2284 if (newHash != self.oldUserHash) { // Only process new user hash once
2285 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2287 // Queue change if animating
2288 if (self.animating) {
2290 self.animationFinishedCallback = function() {
2291 self.updateFromParams(self.paramsFromFragment(newHash));
2293 } else { // update immediately
2294 self.updateFromParams(self.paramsFromFragment(newHash));
2296 self.oldUserHash = newHash;
2304 // Returns a URL for an embedded version of the current book
2305 GnuBook.prototype.getEmbedURL = function() {
2306 // We could generate a URL hash fragment here but for now we just leave at defaults
2307 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2312 // Returns the embed code HTML fragment suitable for copy and paste
2313 GnuBook.prototype.getEmbedCode = function() {
2314 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";