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().
34 if (typeof(console) == 'undefined') {
35 console = { log: function(msg) { } };
41 this.mode = 1; //1 or 2
42 this.ui = 'full'; // UI mode
44 this.displayedIndices = [];
45 //this.indicesToDisplay = [];
47 this.prefetchedImgs = {}; //an object with numeric keys cooresponding to page index
50 this.animating = false;
52 this.autoTimer = null;
53 this.flipSpeed = 'fast';
55 this.twoPagePopUp = null;
56 this.leafEdgeTmp = null;
57 this.embedPopup = null;
59 this.searchResults = {};
61 this.firstIndex = null;
63 this.lastDisplayableIndex2up = null;
65 // We link to index.php to avoid redirect which breaks back button
66 this.logoURL = 'http://www.archive.org/index.php';
68 // Base URL for images
69 this.imagesBaseURL = '/bookreader/images/';
72 this.constMode1up = 1;
73 this.constMode2up = 2;
78 //______________________________________________________________________________
79 GnuBook.prototype.init = function() {
81 var startIndex = undefined;
83 // Find start index and mode if set in location hash
84 var params = this.paramsFromFragment(window.location.hash);
86 if ('undefined' != typeof(params.index)) {
87 startIndex = params.index;
88 } else if ('undefined' != typeof(params.page)) {
89 startIndex = this.getPageIndex(params.page);
92 if ('undefined' == typeof(startIndex)) {
93 if ('undefined' != typeof(this.titleLeaf)) {
94 startIndex = this.leafNumToIndex(this.titleLeaf);
98 if ('undefined' == typeof(startIndex)) {
102 if ('undefined' != typeof(params.mode)) {
103 this.mode = params.mode;
106 // Set document title -- may have already been set in enclosing html for
107 // search engine visibility
108 document.title = this.shortTitle(50);
110 // Sanitize parameters
111 if ( !this.canSwitchToMode( this.mode ) ) {
112 this.mode = this.constMode1up;
115 $("#GnuBook").empty();
116 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
117 $("#GnuBook").append("<div id='GBcontainer'></div>");
118 $("#GBcontainer").append("<div id='GBpageview'></div>");
120 $("#GBcontainer").bind('scroll', this, function(e) {
124 this.setupKeyListeners();
125 this.startLocationPolling();
127 $(window).bind('resize', this, function(e) {
128 //console.log('resize!');
129 if (1 == e.data.mode) {
130 //console.log('centering 1page view');
131 e.data.centerPageView();
132 $('#GBpageview').empty()
133 e.data.displayedIndices = [];
134 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
137 //console.log('drawing 2 page view');
138 e.data.prepareTwoPageView();
142 $('.GBpagediv1up').bind('mousedown', this, function(e) {
143 //console.log('mousedown!');
146 if (1 == this.mode) {
147 this.resizePageView();
148 this.firstIndex = startIndex;
149 this.jumpToIndex(startIndex);
151 //this.resizePageView();
153 this.displayedIndices=[0];
154 this.firstIndex = startIndex;
155 this.displayedIndices = [this.firstIndex];
156 //console.log('titleLeaf: %d', this.titleLeaf);
157 //console.log('displayedIndices: %s', this.displayedIndices);
158 this.prepareTwoPageView();
159 //if (this.auto) this.nextPage();
162 // Enact other parts of initial params
163 this.updateFromParams(params);
166 GnuBook.prototype.setupKeyListeners = function() {
179 // We use document here instead of window to avoid a bug in jQuery on IE7
180 $(document).keydown(function(e) {
182 // Keyboard navigation
186 // In 1up mode page scrolling is handled by browser
187 if (2 == self.mode) {
193 if (2 == self.mode) {
204 if (self.keyboardNavigationIsDisabled(e)) {
207 if (2 == self.mode) {
212 if (self.keyboardNavigationIsDisabled(e)) {
215 if (2 == self.mode) {
224 //______________________________________________________________________________
225 GnuBook.prototype.drawLeafs = function() {
226 if (1 == this.mode) {
227 this.drawLeafsOnePage();
229 this.drawLeafsTwoPage();
233 // setDragHandler1up()
234 //______________________________________________________________________________
235 GnuBook.prototype.setDragHandler1up = function(div) {
236 div.dragging = false;
238 $(div).bind('mousedown', function(e) {
239 //console.log('mousedown at ' + e.pageY);
241 this.dragging = true;
242 this.prevMouseX = e.pageX;
243 this.prevMouseY = e.pageY;
245 var startX = e.pageX;
246 var startY = e.pageY;
247 var startTop = $('#GBcontainer').attr('scrollTop');
248 var startLeft = $('#GBcontainer').attr('scrollLeft');
253 $(div).bind('mousemove', function(ee) {
254 //console.log('mousemove ' + startY);
256 var offsetX = ee.pageX - this.prevMouseX;
257 var offsetY = ee.pageY - this.prevMouseY;
260 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
261 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
264 this.prevMouseX = ee.pageX;
265 this.prevMouseY = ee.pageY;
270 $(div).bind('mouseup', function(ee) {
271 //console.log('mouseup');
273 this.dragging = false;
277 $(div).bind('mouseleave', function(e) {
278 //console.log('mouseleave');
280 //$(this).unbind('mousemove mouseup');
281 this.dragging = false;
286 // drawLeafsOnePage()
287 //______________________________________________________________________________
288 GnuBook.prototype.drawLeafsOnePage = function() {
289 //alert('drawing leafs!');
293 var scrollTop = $('#GBcontainer').attr('scrollTop');
294 var scrollBottom = scrollTop + $('#GBcontainer').height();
295 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
297 var indicesToDisplay = [];
302 for (i=0; i<this.numLeafs; i++) {
303 var height = parseInt(this.getPageHeight(i)/this.reduce);
305 leafBottom += height;
306 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
307 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
308 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
309 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
310 if (topInView | bottomInView | middleInView) {
311 //console.log('displayed: ' + this.displayedIndices);
312 //console.log('to display: ' + i);
313 indicesToDisplay.push(i);
315 leafTop += height +10;
319 var firstIndexToDraw = indicesToDisplay[0];
320 this.firstIndex = firstIndexToDraw;
322 // Update hash, but only if we're currently displaying a leaf
323 // Hack that fixes #365790
324 if (this.displayedIndices.length > 0) {
325 this.updateLocationHash();
328 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
330 indicesToDisplay.unshift(firstIndexToDraw);
333 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
334 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
335 indicesToDisplay.push(lastIndexToDraw+1);
340 for (i=0; i<firstIndexToDraw; i++) {
341 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
344 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
345 var viewWidth = $('#GBcontainer').attr('scrollWidth');
348 for (i=0; i<indicesToDisplay.length; i++) {
349 var index = indicesToDisplay[i];
350 var height = parseInt(this.getPageHeight(index)/this.reduce);
352 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
353 var width = parseInt(this.getPageWidth(index)/this.reduce);
354 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
355 var div = document.createElement("div");
356 div.className = 'GBpagediv1up';
357 div.id = 'pagediv'+index;
358 div.style.position = "absolute";
359 $(div).css('top', leafTop + 'px');
360 var left = (viewWidth-width)>>1;
361 if (left<0) left = 0;
362 $(div).css('left', left+'px');
363 $(div).css('width', width+'px');
364 $(div).css('height', height+'px');
365 //$(div).text('loading...');
367 this.setDragHandler1up(div);
369 $('#GBpageview').append(div);
371 var img = document.createElement("img");
372 img.src = this.getPageURI(index);
373 $(img).css('width', width+'px');
374 $(img).css('height', height+'px');
378 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
381 leafTop += height +10;
385 for (i=0; i<this.displayedIndices.length; i++) {
386 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
387 var index = this.displayedIndices[i];
388 //console.log('Removing leaf ' + index);
389 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
390 $('#pagediv'+index).remove();
392 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
396 this.displayedIndices = indicesToDisplay.slice();
397 this.updateSearchHilites();
399 if (null != this.getPageNum(firstIndexToDraw)) {
400 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
402 $("#GBpagenum").val('');
405 //var centerY = this.centerY1up();
406 //var centerX = this.centerX1up();
407 //console.log('draw center ' + centerY + ',' + centerX);
408 //console.log('scroll left ' + $('#GBcontainer').attr('scrollLeft'));
412 // drawLeafsTwoPage()
413 //______________________________________________________________________________
414 GnuBook.prototype.drawLeafsTwoPage = function() {
415 console.log('drawing two leafs!'); // XXX
417 var scrollTop = $('#GBtwopageview').attr('scrollTop');
418 var scrollBottom = scrollTop + $('#GBtwopageview').height();
420 console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.currentIndexL); // XXX
422 var index = this.currentIndexL;
423 var height = this.getPageHeight(index);
424 var width = this.getPageWidth(index);
425 var handSide= this.getPageSide(index);
427 var leafEdgeWidthL = this.leafEdgeWidth(index);
428 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
429 var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
430 var bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
431 //console.log(leafEdgeWidthL);
433 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
434 var left = middle - this.twoPageW;
435 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
437 var scaledW = parseInt(this.twoPageH*width/height);
438 left = 10+leafEdgeWidthL;
439 //var right = left+scaledW;
440 var right = $(this.twoPageDiv).width()-11-$(this.leafEdgeL).width()-scaledW;
442 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
444 this.prefetchImg(index);
445 $(this.prefetchedImgs[index]).css({
446 position: 'absolute',
447 /*right: gutter+'px',*/
448 left: gutter-scaledW+'px',
451 backgroundColor: 'rgb(234, 226, 205)',
452 height: this.twoPageH +'px',
453 width: scaledW + 'px',
454 borderRight: '1px solid black',
456 }).appendTo('#GBtwopageview');
457 //$('#GBcontainer').append(this.prefetchedImgs[index]);
460 var index = this.currentIndexR;
461 var height = this.getPageHeight(index);
462 var width = this.getPageWidth(index);
463 // var left = ($('#GBcontainer').width() >> 1);
466 var scaledW = this.twoPageH*width/height;
467 this.prefetchImg(index);
468 $(this.prefetchedImgs[index]).css({
469 position: 'absolute',
473 backgroundColor: 'rgb(234, 226, 205)',
474 height: this.twoPageH + 'px',
475 width: scaledW + 'px',
476 borderLeft: '1px solid black',
478 }).appendTo('#GBtwopageview');
479 //$('#GBcontainer').append(this.prefetchedImgs[index]);
482 this.displayedIndices = [this.currentIndexL, this.currentIndexR];
483 this.setClickHandlers();
485 this.updatePageNumBox2UP();
488 // updatePageNumBox2UP
489 //______________________________________________________________________________
490 GnuBook.prototype.updatePageNumBox2UP = function() {
491 if (null != this.getPageNum(this.currentIndexL)) {
492 $("#GBpagenum").val(this.getPageNum(this.currentIndexL));
494 $("#GBpagenum").val('');
496 this.updateLocationHash();
500 //______________________________________________________________________________
501 GnuBook.prototype.loadLeafs = function() {
505 if (null == this.timer) {
506 this.timer=setTimeout(function(){self.drawLeafs()},250);
508 clearTimeout(this.timer);
509 this.timer=setTimeout(function(){self.drawLeafs()},250);
515 //______________________________________________________________________________
516 GnuBook.prototype.zoom1up = function(dir) {
517 if (2 == this.mode) { //can only zoom in 1-page mode
522 // $$$ with flexible zoom we could "snap" to /2 page reductions
523 // for better scaling
525 if (this.reduce <= 0.5) return;
526 this.reduce*=0.5; //zoom in
528 if (this.reduce >= 8) return;
529 this.reduce*=2; //zoom out
532 this.resizePageView();
534 $('#GBpageview').empty()
535 this.displayedIndices = [];
538 $('#GBzoom').text(100/this.reduce);
542 //______________________________________________________________________________
543 GnuBook.prototype.resizePageView = function() {
546 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
547 var viewWidth = $('#GBcontainer').attr('clientWidth');
549 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
550 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
551 var oldPageViewHeight = $('#GBpageview').height();
552 var oldPageViewWidth = $('#GBpageview').width();
554 var oldCenterY = this.centerY1up();
555 var oldCenterX = this.centerX1up();
557 if (0 != oldPageViewHeight) {
558 var scrollRatio = oldCenterY / oldPageViewHeight;
563 for (i=0; i<this.numLeafs; i++) {
564 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
565 var width = parseInt(this.getPageWidth(i)/this.reduce);
566 if (width>viewWidth) viewWidth=width;
568 $('#GBpageview').height(viewHeight);
569 $('#GBpageview').width(viewWidth);
571 var newCenterY = scrollRatio*viewHeight;
572 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
573 $('#GBcontainer').attr('scrollTop', newTop);
575 // We use clientWidth here to avoid miscalculating due to scroll bar
576 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
577 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
578 newLeft = Math.min(newLeft, 0);
579 $('#GBcontainer').attr('scrollLeft', newLeft);
580 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
582 //this.centerPageView();
588 //______________________________________________________________________________
589 // Returns the current offset of the viewport center in scaled document coordinates.
590 GnuBook.prototype.centerX1up = function() {
592 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
593 centerX = $('#GBpageview').width();
595 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
597 centerX = Math.floor(centerX);
602 //______________________________________________________________________________
603 // Returns the current offset of the viewport center in scaled document coordinates.
604 GnuBook.prototype.centerY1up = function() {
605 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
606 return Math.floor(centerY);
610 //______________________________________________________________________________
611 GnuBook.prototype.centerPageView = function() {
613 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
614 var clientWidth = $('#GBcontainer').attr('clientWidth');
615 //console.log('sW='+scrollWidth+' cW='+clientWidth);
616 if (scrollWidth > clientWidth) {
617 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
623 //______________________________________________________________________________
624 // Attempts to jump to page. Returns true if page could be found, false otherwise.
625 GnuBook.prototype.jumpToPage = function(pageNum) {
627 var pageIndex = this.getPageIndex(pageNum);
629 if ('undefined' != typeof(pageIndex)) {
632 this.jumpToIndex(pageIndex);
633 $('#GBcontainer').attr('scrollTop', leafTop);
642 //______________________________________________________________________________
643 GnuBook.prototype.jumpToIndex = function(index) {
645 if (2 == this.mode) {
648 // By checking against min/max we do nothing if requested index
650 if (index < Math.min(this.currentIndexL, this.currentIndexR)) {
651 this.flipBackToIndex(index);
652 } else if (index > Math.max(this.currentIndexL, this.currentIndexR)) {
653 this.flipFwdToIndex(index);
660 for (i=0; i<index; i++) {
661 h = parseInt(this.getPageHeight(i)/this.reduce);
662 leafTop += h + this.padding;
664 //$('#GBcontainer').attr('scrollTop', leafTop);
665 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
672 //______________________________________________________________________________
673 GnuBook.prototype.switchMode = function(mode) {
675 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
677 if (mode == this.mode) return;
679 if (!this.canSwitchToMode(mode)) {
684 this.removeSearchHilites();
688 this.switchToolbarMode(mode);
691 this.prepareOnePageView();
693 this.prepareTwoPageView();
698 //prepareOnePageView()
699 //______________________________________________________________________________
700 GnuBook.prototype.prepareOnePageView = function() {
702 // var startLeaf = this.displayedIndices[0];
703 var startLeaf = this.currentIndex();
705 $('#GBcontainer').empty();
706 $('#GBcontainer').css({
711 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
713 this.resizePageView();
715 this.jumpToIndex(startLeaf);
716 this.displayedIndices = [];
718 this.drawLeafsOnePage();
719 $('#GBzoom').text(100/this.reduce);
721 // Bind mouse handlers
722 // Disable mouse click to avoid selected/highlighted page images - bug 354239
723 gbPageView.bind('mousedown', function(e) {
726 // Special hack for IE7
727 gbPageView[0].onselectstart = function(e) { return false; };
730 // prepareTwoPageView()
731 //______________________________________________________________________________
732 GnuBook.prototype.prepareTwoPageView = function() {
733 $('#GBcontainer').empty();
735 // Add the two page view
736 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
737 // Explicitly set sizes the same
738 $('#GBtwopageview').css( {
739 height: $('#GBcontainer').height(),
740 width: $('#GBcontainer').width(),
744 // We want to display two facing pages. We may be missing
745 // one side of the spread because it is the first/last leaf,
746 // foldouts, missing pages, etc
748 //var targetLeaf = this.displayedIndices[0];
749 var targetLeaf = this.firstIndex;
751 if (targetLeaf < this.firstDisplayableIndex()) {
752 targetLeaf = this.firstDisplayableIndex();
755 if (targetLeaf > this.lastDisplayableIndex()) {
756 targetLeaf = this.lastDisplayableIndex();
759 this.currentIndexL = null;
760 this.currentIndexR = null;
761 this.pruneUnusedImgs();
763 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
764 this.currentIndexL = currentSpreadIndices[0];
765 this.currentIndexR = currentSpreadIndices[1];
766 this.firstIndex = this.currentIndexL;
768 this.calculateSpreadSize(); //sets this.twoPageW, twoPageH, and twoPageRatio
770 // We want to minimize the unused space in two-up mode (maximize the amount of page
771 // shown). We give width to the leaf edges and these widths change (though the sum
772 // of the two remains constant) as we flip through the book. With the book
773 // cover centered and fixed in the GBcontainer div the page images will meet
774 // at the "gutter" which is generally offset from the center.
775 var middle = ($('#GBcontainer').attr('clientWidth') >> 1); // Middle of the GBcontainer div
776 //var gutter = middle+parseInt((2*this.currentIndexL - this.numLeafs)*this.twoPageEdgeW/this.numLeafs/2);
778 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
780 var scaledWL = this.getPageWidth2UP(this.currentIndexL);
781 var scaledWR = this.getPageWidth2UP(this.currentIndexR);
782 var leafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
783 var leafEdgeWidthR = this.twoPageEdgeW - leafEdgeWidthL;
785 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
786 //var bookCoverDivWidth = this.twoPageW*2+20 + this.twoPageEdgeW;
788 // The width of the book cover div. The combined width of both pages, twice the width
789 // of the book cover internal padding (2*10) and the page edges
790 var bookCoverDivWidth = scaledWL + scaledWR + 20 + this.twoPageEdgeW;
792 // The height of the book cover div
793 var bookCoverDivHeight = this.twoPageH+20;
795 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
796 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-10;
797 var bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
798 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
800 this.twoPageDiv = document.createElement('div');
801 $(this.twoPageDiv).attr('id', 'GBbookcover').css({
802 border: '1px solid rgb(68, 25, 17)',
803 width: bookCoverDivWidth + 'px',
804 height: bookCoverDivHeight+'px',
805 visibility: 'visible',
806 position: 'absolute',
807 backgroundColor: '#663929',
808 left: bookCoverDivLeft + 'px',
809 top: bookCoverDivTop+'px',
810 MozBorderRadiusTopleft: '7px',
811 MozBorderRadiusTopright: '7px',
812 MozBorderRadiusBottomright: '7px',
813 MozBorderRadiusBottomleft: '7px'
814 }).appendTo('#GBtwopageview');
815 //$('#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;"/>');
818 var height = this.getPageHeight(this.currentIndexR);
819 var width = this.getPageWidth(this.currentIndexR);
820 var scaledW = this.twoPageH*width/height;
822 this.leafEdgeR = document.createElement('div');
823 this.leafEdgeR.className = 'leafEdgeR';
824 $(this.leafEdgeR).css({
825 borderStyle: 'solid solid solid none',
826 borderColor: 'rgb(51, 51, 34)',
827 borderWidth: '1px 1px 1px 0px',
828 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
829 width: leafEdgeWidthR + 'px',
830 height: this.twoPageH-1 + 'px',
832 left: gutter+scaledW+'px',
833 top: bookCoverDivTop+10+'px',
835 }).appendTo('#GBtwopageview');
837 this.leafEdgeL = document.createElement('div');
838 this.leafEdgeL.className = 'leafEdgeL';
839 $(this.leafEdgeL).css({
840 borderStyle: 'solid none solid solid',
841 borderColor: 'rgb(51, 51, 34)',
842 borderWidth: '1px 0px 1px 1px',
843 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
844 width: leafEdgeWidthL + 'px',
845 height: this.twoPageH-1 + 'px',
846 left: bookCoverDivLeft+10+'px',
847 top: bookCoverDivTop+10+'px',
849 }).appendTo('#GBtwopageview');
853 bookCoverDivWidth = 30;
854 bookCoverDivHeight = this.twoPageH+20;
855 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
856 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
858 div = document.createElement('div');
859 $(div).attr('id', 'GBbookspine').css({
860 border: '1px solid rgb(68, 25, 17)',
861 width: bookCoverDivWidth+'px',
862 height: bookCoverDivHeight+'px',
863 position: 'absolute',
864 backgroundColor: 'rgb(68, 25, 17)',
865 left: bookCoverDivLeft+'px',
866 top: bookCoverDivTop+'px'
867 }).appendTo('#GBtwopageview');
868 //$('#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;"/>');
870 bookCoverDivWidth = this.twoPageW*2;
871 bookCoverDivHeight = this.twoPageH;
872 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
873 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
876 this.prepareTwoPagePopUp();
878 this.displayedIndices = [];
880 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
881 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
883 this.drawLeafsTwoPage();
884 this.updateSearchHilites2UP();
887 $('#GBzoom').text((100*this.twoPageH/this.getPageHeight(this.currentIndexL)).toString().substr(0,4));
890 // prepareTwoPagePopUp()
892 // This function prepares the "View Page n" popup that shows while the mouse is
893 // over the left/right "stack of sheets" edges. It also binds the mouse
894 // events for these divs.
895 //______________________________________________________________________________
896 GnuBook.prototype.prepareTwoPagePopUp = function() {
898 this.twoPagePopUp = document.createElement('div');
899 $(this.twoPagePopUp).css({
900 border: '1px solid black',
902 position: 'absolute',
903 fontFamily: 'sans-serif',
906 backgroundColor: 'rgb(255, 255, 238)',
908 }).appendTo('#GBcontainer');
909 $(this.twoPagePopUp).hide();
911 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
912 $(e.data.twoPagePopUp).show();
915 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
916 $(e.data.twoPagePopUp).hide();
919 $(this.leafEdgeL).bind('click', this, function(e) {
921 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
922 e.data.jumpToIndex(jumpIndex);
925 $(this.leafEdgeR).bind('click', this, function(e) {
927 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
928 e.data.jumpToIndex(jumpIndex);
931 $(this.leafEdgeR).bind('mousemove', this, function(e) {
933 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
934 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
936 $(e.data.twoPagePopUp).css({
937 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px', // XXX use offset
938 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
942 $(this.leafEdgeL).bind('mousemove', this, function(e) {
944 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
945 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
947 $(e.data.twoPagePopUp).css({
948 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px', // XXX use offset
949 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
954 // calculateSpreadSize()
955 //______________________________________________________________________________
956 // Calculates 2-page spread dimensions based on this.currentIndexL and
957 // this.currentIndexR
958 // This function sets this.twoPageH, twoPageW, and twoPageRatio
960 GnuBook.prototype.calculateSpreadSize = function() {
961 console.log('calculateSpreadSize ' + this.currentIndexL); // XXX
963 var firstIndex = this.currentIndexL;
964 var secondIndex = this.currentIndexR;
965 //console.log('first page is ' + firstIndex);
967 var canon5Dratio = 1.5;
969 var firstIndexRatio = this.getPageHeight(firstIndex) / this.getPageWidth(firstIndex);
970 var secondIndexRatio = this.getPageHeight(secondIndex) / this.getPageWidth(secondIndex);
971 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
974 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
975 ratio = firstIndexRatio;
976 //console.log('using firstIndexRatio ' + ratio);
978 ratio = secondIndexRatio;
979 //console.log('using secondIndexRatio ' + ratio);
982 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
983 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
984 totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
987 $('#GBcontainer').css('overflow', 'auto');
989 var idealWidth = ($('#GBcontainer').attr('clientWidth') - 30 - totalLeafEdgeWidth)>>1;
990 var idealHeight = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
991 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
993 if (idealHeight/ratio <= idealWidth) {
995 idealWidth = parseInt(idealHeight/ratio);
998 idealHeight = parseInt(idealWidth*ratio);
1001 this.twoPageH = idealHeight;
1002 this.twoPageW = idealWidth;
1003 this.twoPageRatio = ratio;
1004 this.twoPageEdgeW = totalLeafEdgeWidth; // The combined width of both edges
1007 // this.twoPageH *= 2;
1008 // this.twoPageW *= 2;
1009 // this.twoPageEdgeW *= 2;
1014 //______________________________________________________________________________
1015 // Returns the currently active index.
1016 GnuBook.prototype.currentIndex = function() {
1017 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1018 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1019 return this.firstIndex;
1021 throw 'currentIndex called for unimplemented mode ' + this.mode;
1026 //______________________________________________________________________________
1027 // Flip the right page over onto the left
1028 GnuBook.prototype.right = function() {
1029 if ('rl' != this.pageProgression) {
1039 //______________________________________________________________________________
1040 // Flip to the rightmost page
1041 GnuBook.prototype.rightmost = function() {
1042 if ('rl' != this.pageProgression) {
1050 //______________________________________________________________________________
1051 // Flip the left page over onto the right.
1052 GnuBook.prototype.left = function() {
1053 if ('rl' != this.pageProgression) {
1063 //______________________________________________________________________________
1064 // Flip to the leftmost page
1065 GnuBook.prototype.leftmost = function() {
1066 if ('rl' != this.pageProgression) {
1074 //______________________________________________________________________________
1075 GnuBook.prototype.next = function() {
1076 if (2 == this.mode) {
1078 this.flipFwdToIndex(null);
1080 if (this.firstIndex < this.lastDisplayableIndex()) {
1081 this.jumpToIndex(this.firstIndex+1);
1087 //______________________________________________________________________________
1088 GnuBook.prototype.prev = function() {
1089 if (2 == this.mode) {
1091 this.flipBackToIndex(null);
1093 if (this.firstIndex >= 1) {
1094 this.jumpToIndex(this.firstIndex-1);
1099 GnuBook.prototype.first = function() {
1100 if (2 == this.mode) {
1101 this.jumpToIndex(2);
1104 this.jumpToIndex(0);
1108 GnuBook.prototype.last = function() {
1109 if (2 == this.mode) {
1110 this.jumpToIndex(this.lastDisplayableIndex());
1113 this.jumpToIndex(this.lastDisplayableIndex());
1117 // flipBackToIndex()
1118 //______________________________________________________________________________
1119 // to flip back one spread, pass index=null
1120 GnuBook.prototype.flipBackToIndex = function(index) {
1121 if (1 == this.mode) return;
1123 var leftIndex = this.currentIndexL;
1125 // $$$ Need to change this to be able to see first spread.
1126 // See https://bugs.launchpad.net/gnubook/+bug/296788
1127 if (leftIndex <= 2) return;
1128 if (this.animating) return;
1130 if (null != this.leafEdgeTmp) {
1131 alert('error: leafEdgeTmp should be null!');
1135 if (null == index) {
1136 index = leftIndex-2;
1138 //if (index<0) return;
1140 var previousIndices = this.getSpreadIndices(index);
1142 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1146 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1148 this.animating = true;
1150 if ('rl' != this.pageProgression) {
1151 // Assume LTR and we are going backward
1152 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1153 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1156 // RTL and going backward
1157 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1158 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1162 // flipLeftToRight()
1163 //______________________________________________________________________________
1164 // Flips the page on the left towards the page on the right
1165 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1167 var leftLeaf = this.currentIndexL;
1169 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1170 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1171 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1173 var currWidthL = this.getPageWidth2UP(leftLeaf);
1174 var newWidthL = this.getPageWidth2UP(newIndexL);
1175 var newWidthR = this.getPageWidth2UP(newIndexR);
1177 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1179 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1180 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1182 //animation strategy:
1183 // 0. remove search highlight, if any.
1184 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1185 // of the left leaf and where the user clicked in the leaf edge.
1186 // Note that if this function was triggered by left() and not a
1187 // mouse click, the width of leafEdgeTmp is very small (zero px).
1188 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1189 // leftLeaf to width=0.
1190 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1191 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1192 // its new full width.
1193 // 4. After step 3 is finished, do the following:
1194 // - remove leafEdgeTmp from the dom.
1195 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1196 // and width=twoPageEdgeW-newLeafEdgeWidthL.
1197 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1198 // and width=newLeafEdgeWidthL.
1199 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1200 // and width=newWidthL+newWidthR+twoPageEdgeW+20
1201 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1202 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1203 // - prefetch new adjacent leafs.
1204 // - set up click handlers for both new left and right leafs.
1205 // - redraw the search highlight.
1206 // - update the pagenum box and the url.
1209 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1211 this.leafEdgeTmp = document.createElement('div');
1212 $(this.leafEdgeTmp).css({
1213 borderStyle: 'solid none solid solid',
1214 borderColor: 'rgb(51, 51, 34)',
1215 borderWidth: '1px 0px 1px 1px',
1216 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1217 width: leafEdgeTmpW + 'px',
1218 height: this.twoPageH-1 + 'px',
1219 left: leftEdgeTmpLeft + 'px',
1221 position: 'absolute',
1223 }).appendTo('#GBtwopageview');
1225 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1226 $(this.leafEdgeL).css({
1227 width: newLeafEdgeWidthL+'px',
1228 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1231 // Left gets the offset of the current left leaf from the document
1232 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1233 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1234 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1235 // We change the left leaf to right positioning
1236 $(this.prefetchedImgs[leftLeaf]).css({
1241 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1243 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1245 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1246 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1250 this.removeSearchHilites();
1252 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1253 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1255 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1256 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1258 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1259 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1260 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1262 $(self.leafEdgeR).css({
1263 // Moves the right leaf edge
1264 width: self.twoPageEdgeW-newLeafEdgeWidthL+'px',
1265 left: gutter+newWidthR+'px'
1268 $(self.leafEdgeL).css({
1269 // Moves and resizes the left leaf edge
1270 width: newLeafEdgeWidthL+'px',
1271 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1275 $(self.twoPageDiv).css({
1276 // Resizes the brown border div
1277 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1278 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1281 $(self.leafEdgeTmp).remove();
1282 self.leafEdgeTmp = null;
1284 self.currentIndexL = newIndexL;
1285 self.currentIndexR = newIndexR;
1286 self.firstIndex = self.currentIndexL;
1287 self.displayedIndices = [newIndexL, newIndexR];
1288 self.setClickHandlers();
1289 self.pruneUnusedImgs();
1291 self.animating = false;
1293 self.updateSearchHilites2UP();
1294 self.updatePageNumBox2UP();
1295 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1297 if (self.animationFinishedCallback) {
1298 self.animationFinishedCallback();
1299 self.animationFinishedCallback = null;
1307 //______________________________________________________________________________
1308 // Whether we flip left or right is dependent on the page progression
1309 // to flip forward one spread, pass index=null
1310 GnuBook.prototype.flipFwdToIndex = function(index) {
1312 if (this.animating) return;
1314 if (null != this.leafEdgeTmp) {
1315 alert('error: leafEdgeTmp should be null!');
1319 if (null == index) {
1320 index = this.currentIndexR+2; // $$$ assumes indices are continuous
1322 if (index > this.lastDisplayableIndex()) return;
1324 this.animating = true;
1326 var nextIndices = this.getSpreadIndices(index);
1328 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1330 if ('rl' != this.pageProgression) {
1331 // We did not specify RTL
1332 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1333 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1336 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1337 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1341 // flipRightToLeft(nextL, nextR, gutter)
1342 // $$$ better not to have to pass gutter in
1343 //______________________________________________________________________________
1344 // Flip from left to right and show the nextL and nextR indices on those sides
1345 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1346 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.currentIndexL);
1347 var oldLeafEdgeWidthR = this.twoPageEdgeW-oldLeafEdgeWidthL;
1348 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1349 var newLeafEdgeWidthR = this.twoPageEdgeW-newLeafEdgeWidthL;
1351 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1353 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1355 var scaledW = this.getPageWidth2UP(this.currentIndexR);
1357 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1358 var currGutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1361 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1363 this.leafEdgeTmp = document.createElement('div');
1364 $(this.leafEdgeTmp).css({
1365 borderStyle: 'solid none solid solid',
1366 borderColor: 'rgb(51, 51, 34)',
1367 borderWidth: '1px 0px 1px 1px',
1368 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1369 width: leafEdgeTmpW + 'px',
1370 height: this.twoPageH-1 + 'px',
1371 left: currGutter+scaledW+'px',
1373 position: 'absolute',
1375 }).appendTo('#GBtwopageview');
1377 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1378 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1380 var currWidthL = this.getPageWidth2UP(this.currentIndexL);
1381 var currWidthR = this.getPageWidth2UP(this.currentIndexR);
1382 var newWidthL = this.getPageWidth2UP(newIndexL);
1383 var newWidthR = this.getPageWidth2UP(newIndexR);
1385 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1387 var self = this; // closure-tastic!
1389 var speed = this.flipSpeed;
1391 this.removeSearchHilites();
1393 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1394 $(this.prefetchedImgs[this.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1395 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1396 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1397 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1399 $(self.leafEdgeL).css({
1400 width: newLeafEdgeWidthL+'px',
1401 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1404 $(self.twoPageDiv).css({
1405 width: newWidthL+newWidthR+self.twoPageEdgeW+20+'px',
1406 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1409 $(self.leafEdgeTmp).remove();
1410 self.leafEdgeTmp = null;
1412 self.currentIndexL = newIndexL;
1413 self.currentIndexR = newIndexR;
1414 self.firstIndex = self.currentIndexL;
1415 self.displayedIndices = [newIndexL, newIndexR];
1416 self.setClickHandlers();
1417 self.pruneUnusedImgs();
1419 self.animating = false;
1422 self.updateSearchHilites2UP();
1423 self.updatePageNumBox2UP();
1424 //$('#GBzoom').text((self.twoPageH/self.getPageHeight(newIndexL)).toString().substr(0,4));
1426 if (self.animationFinishedCallback) {
1427 self.animationFinishedCallback();
1428 self.animationFinishedCallback = null;
1435 //______________________________________________________________________________
1436 GnuBook.prototype.setClickHandlers = function() {
1438 $(this.prefetchedImgs[this.currentIndexL]).click(function() {
1443 $(this.prefetchedImgs[this.currentIndexR]).click(function() {
1451 //______________________________________________________________________________
1452 GnuBook.prototype.prefetchImg = function(index) {
1453 if (undefined == this.prefetchedImgs[index]) {
1454 //console.log('prefetching ' + index);
1455 var img = document.createElement("img");
1456 img.src = this.getPageURI(index);
1457 this.prefetchedImgs[index] = img;
1462 // prepareFlipLeftToRight()
1464 //______________________________________________________________________________
1466 // Prepare to flip the left page towards the right. This corresponds to moving
1467 // backward when the page progression is left to right.
1468 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1470 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1472 this.prefetchImg(prevL);
1473 this.prefetchImg(prevR);
1475 var height = this.getPageHeight(prevL);
1476 var width = this.getPageWidth(prevL);
1477 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1478 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1479 var scaledW = this.twoPageH*width/height;
1481 // The gutter is the dividing line between the left and right pages.
1482 // It is offset from the middle to create the illusion of thickness to the pages
1483 var gutter = middle + this.gutterOffsetForIndex(prevL);
1486 console.log(' gutter for ' + prevL + ' is ' + gutter);
1487 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1488 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1490 $(this.prefetchedImgs[prevL]).css({
1491 position: 'absolute',
1492 /*right: middle+'px',*/
1493 left: gutter-scaledW+'px',
1496 backgroundColor: 'rgb(234, 226, 205)',
1497 height: this.twoPageH,
1498 width: scaledW+'px',
1499 borderRight: '1px solid black',
1503 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1505 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1507 $(this.prefetchedImgs[prevR]).css({
1508 position: 'absolute',
1512 backgroundColor: 'rgb(234, 226, 205)',
1513 height: this.twoPageH,
1515 borderLeft: '1px solid black',
1519 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1526 // XXXmang we're adding an extra pixel in the middle
1527 // prepareFlipRightToLeft()
1528 //______________________________________________________________________________
1529 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1531 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1533 this.prefetchImg(nextL);
1534 this.prefetchImg(nextR);
1536 var height = this.getPageHeight(nextR);
1537 var width = this.getPageWidth(nextR);
1538 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1539 var top = ($('#GBtwopageview').height() - this.twoPageH) >> 1;
1540 var scaledW = this.twoPageH*width/height;
1542 var gutter = middle + this.gutterOffsetForIndex(nextL);
1544 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1546 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1547 $(this.prefetchedImgs[nextR]).css({
1548 position: 'absolute',
1551 backgroundColor: 'rgb(234, 226, 205)',
1552 height: this.twoPageH,
1553 width: scaledW+'px',
1554 borderLeft: '1px solid black',
1558 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1560 height = this.getPageHeight(nextL);
1561 width = this.getPageWidth(nextL);
1562 scaledW = this.twoPageH*width/height;
1564 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1565 $(this.prefetchedImgs[nextL]).css({
1566 position: 'absolute',
1567 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1569 backgroundColor: 'rgb(234, 226, 205)',
1570 height: this.twoPageH,
1572 borderRight: '1px solid black',
1576 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1582 // getNextLeafs() -- NOT RTL AWARE
1583 //______________________________________________________________________________
1584 // GnuBook.prototype.getNextLeafs = function(o) {
1585 // //TODO: we might have two left or two right leafs in a row (damaged book)
1586 // //For now, assume that leafs are contiguous.
1588 // //return [this.currentIndexL+2, this.currentIndexL+3];
1589 // o.L = this.currentIndexL+2;
1590 // o.R = this.currentIndexL+3;
1593 // getprevLeafs() -- NOT RTL AWARE
1594 //______________________________________________________________________________
1595 // GnuBook.prototype.getPrevLeafs = function(o) {
1596 // //TODO: we might have two left or two right leafs in a row (damaged book)
1597 // //For now, assume that leafs are contiguous.
1599 // //return [this.currentIndexL-2, this.currentIndexL-1];
1600 // o.L = this.currentIndexL-2;
1601 // o.R = this.currentIndexL-1;
1604 // pruneUnusedImgs()
1605 //______________________________________________________________________________
1606 GnuBook.prototype.pruneUnusedImgs = function() {
1607 //console.log('current: ' + this.currentIndexL + ' ' + this.currentIndexR);
1608 for (var key in this.prefetchedImgs) {
1609 //console.log('key is ' + key);
1610 if ((key != this.currentIndexL) && (key != this.currentIndexR)) {
1611 //console.log('removing key '+ key);
1612 $(this.prefetchedImgs[key]).remove();
1614 if ((key < this.currentIndexL-4) || (key > this.currentIndexR+4)) {
1615 //console.log('deleting key '+ key);
1616 delete this.prefetchedImgs[key];
1622 //______________________________________________________________________________
1623 GnuBook.prototype.prefetch = function() {
1625 var lim = this.currentIndexL-4;
1627 lim = Math.max(lim, 0);
1628 for (i = lim; i < this.currentIndexL; i++) {
1629 this.prefetchImg(i);
1632 if (this.numLeafs > (this.currentIndexR+1)) {
1633 lim = Math.min(this.currentIndexR+4, this.numLeafs-1);
1634 for (i=this.currentIndexR+1; i<=lim; i++) {
1635 this.prefetchImg(i);
1640 // getPageWidth2UP()
1641 //______________________________________________________________________________
1642 GnuBook.prototype.getPageWidth2UP = function(index) {
1643 var height = this.getPageHeight(index);
1644 var width = this.getPageWidth(index);
1645 return Math.floor(this.twoPageH*width/height);
1649 //______________________________________________________________________________
1650 GnuBook.prototype.search = function(term) {
1651 $('#GnuBookSearchScript').remove();
1652 var script = document.createElement("script");
1653 script.setAttribute('id', 'GnuBookSearchScript');
1654 script.setAttribute("type", "text/javascript");
1655 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1656 document.getElementsByTagName('head')[0].appendChild(script);
1657 $('#GnuBookSearchResults').html('Searching...');
1660 // GBSearchCallback()
1661 //______________________________________________________________________________
1662 GnuBook.prototype.GBSearchCallback = function(txt) {
1664 if (jQuery.browser.msie) {
1665 var dom=new ActiveXObject("Microsoft.XMLDOM");
1669 var parser = new DOMParser();
1670 var dom = parser.parseFromString(txt, "text/xml");
1673 $('#GnuBookSearchResults').empty();
1674 $('#GnuBookSearchResults').append('<ul>');
1676 for (var key in this.searchResults) {
1677 if (null != this.searchResults[key].div) {
1678 $(this.searchResults[key].div).remove();
1680 delete this.searchResults[key];
1683 var pages = dom.getElementsByTagName('PAGE');
1685 if (0 == pages.length) {
1686 // $$$ it would be nice to echo the (sanitized) search result here
1687 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1689 for (var i = 0; i < pages.length; i++){
1690 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1693 var re = new RegExp (/_(\d{4})/);
1694 var reMatch = re.exec(pages[i].getAttribute('file'));
1695 var index = parseInt(reMatch[1], 10);
1696 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1698 var children = pages[i].childNodes;
1700 for (var j=0; j<children.length; j++) {
1701 //console.log(j + ' - ' + children[j].nodeName);
1702 //console.log(children[j].firstChild.nodeValue);
1703 if ('CONTEXT' == children[j].nodeName) {
1704 context += children[j].firstChild.nodeValue;
1705 } else if ('WORD' == children[j].nodeName) {
1706 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1708 var index = this.leafNumToIndex(index);
1709 if (null != index) {
1710 //coordinates are [left, bottom, right, top, [baseline]]
1711 //we'll skip baseline for now...
1712 var coords = children[j].getAttribute('coords').split(',',4);
1713 if (4 == coords.length) {
1714 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1719 var pageName = this.getPageName(index);
1720 //TODO: remove hardcoded instance name
1721 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1724 $('#GnuBookSearchResults').append('</ul>');
1726 this.updateSearchHilites();
1729 // updateSearchHilites()
1730 //______________________________________________________________________________
1731 GnuBook.prototype.updateSearchHilites = function() {
1732 if (2 == this.mode) {
1733 this.updateSearchHilites2UP();
1735 this.updateSearchHilites1UP();
1739 // showSearchHilites1UP()
1740 //______________________________________________________________________________
1741 GnuBook.prototype.updateSearchHilites1UP = function() {
1743 for (var key in this.searchResults) {
1745 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1746 var result = this.searchResults[key];
1747 if(null == result.div) {
1748 result.div = document.createElement('div');
1749 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1750 //console.log('appending ' + key);
1753 width: (result.r-result.l)/this.reduce + 'px',
1754 height: (result.b-result.t)/this.reduce + 'px',
1755 left: (result.l)/this.reduce + 'px',
1756 top: (result.t)/this.reduce +'px'
1760 //console.log(key + ' not displayed');
1761 this.searchResults[key].div=null;
1766 // showSearchHilites2UP()
1767 //______________________________________________________________________________
1768 GnuBook.prototype.updateSearchHilites2UP = function() {
1770 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1772 for (var key in this.searchResults) {
1773 key = parseInt(key, 10);
1774 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1775 var result = this.searchResults[key];
1776 if(null == result.div) {
1777 result.div = document.createElement('div');
1778 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1779 //console.log('appending ' + key);
1782 var height = this.getPageHeight(key);
1783 var width = this.getPageWidth(key)
1784 var reduce = this.twoPageH/height;
1785 var scaledW = parseInt(width*reduce);
1787 var gutter = middle + this.gutterOffsetForIndex(this.currentIndexL);
1789 if ('L' == this.getPageSide(key)) {
1790 var pageL = gutter-scaledW;
1794 var pageT = ($('#GBtwopagview').height() - this.twoPageH) >> 1;
1797 width: (result.r-result.l)*reduce + 'px',
1798 height: (result.b-result.t)*reduce + 'px',
1799 left: pageL+(result.l)*reduce + 'px',
1800 top: pageT+(result.t)*reduce +'px'
1804 //console.log(key + ' not displayed');
1805 if (null != this.searchResults[key].div) {
1806 //console.log('removing ' + key);
1807 $(this.searchResults[key].div).remove();
1809 this.searchResults[key].div=null;
1814 // removeSearchHilites()
1815 //______________________________________________________________________________
1816 GnuBook.prototype.removeSearchHilites = function() {
1817 for (var key in this.searchResults) {
1818 if (null != this.searchResults[key].div) {
1819 $(this.searchResults[key].div).remove();
1820 this.searchResults[key].div=null;
1826 //______________________________________________________________________________
1827 GnuBook.prototype.showEmbedCode = function() {
1828 if (null != this.embedPopup) { // check if already showing
1832 this.embedPopup = document.createElement("div");
1833 $(this.embedPopup).css({
1834 position: 'absolute',
1836 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1839 border: "3px double #999999",
1841 backgroundColor: "#fff"
1842 }).appendTo('#GnuBook');
1844 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1845 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>';
1846 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1847 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1849 this.embedPopup.innerHTML = htmlStr;
1850 $(this.embedPopup).find('input').bind('click', function() {
1856 //______________________________________________________________________________
1857 GnuBook.prototype.autoToggle = function() {
1859 var bComingFrom1up = false;
1860 if (2 != this.mode) {
1861 bComingFrom1up = true;
1866 if (null == this.autoTimer) {
1867 this.flipSpeed = 2000;
1869 // $$$ Draw events currently cause layout problems when they occur during animation.
1870 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1871 // we workaround for now by not triggering immediate animation in that case.
1872 // See https://bugs.launchpad.net/gnubook/+bug/328327
1873 if (('rl' == this.pageProgression) && bComingFrom1up) {
1874 // don't flip immediately -- wait until timer fires
1877 this.flipFwdToIndex();
1880 $('#GBtoolbar .play').hide();
1881 $('#GBtoolbar .pause').show();
1882 this.autoTimer=setInterval(function(){
1883 if (self.animating) {return;}
1885 if (Math.max(self.currentIndexL, self.currentIndexR) >= self.lastDisplayableIndex()) {
1886 self.flipBackToIndex(1); // $$$ really what we want?
1888 self.flipFwdToIndex();
1897 //______________________________________________________________________________
1898 GnuBook.prototype.autoStop = function() {
1899 if (null != this.autoTimer) {
1900 clearInterval(this.autoTimer);
1901 this.flipSpeed = 'fast';
1902 $('#GBtoolbar .pause').hide();
1903 $('#GBtoolbar .play').show();
1904 this.autoTimer = null;
1908 // keyboardNavigationIsDisabled(event)
1909 // - returns true if keyboard navigation should be disabled for the event
1910 //______________________________________________________________________________
1911 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1912 if (event.target.tagName == "INPUT") {
1918 // gutterOffsetForIndex
1919 //______________________________________________________________________________
1921 // Returns the gutter offset for the spread containing the given index.
1922 // This function supports RTL
1923 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
1925 // $$$ incorporate zooming
1927 // To find the offset of the gutter from the middle we calculate our percentage distance
1928 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
1929 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPageEdgeW);
1931 // But then again for RTL it's the opposite
1932 if ('rl' == this.pageProgression) {
1940 //______________________________________________________________________________
1941 // Returns the width of the leaf edge div for the page with index given
1942 GnuBook.prototype.leafEdgeWidth = function(pindex) {
1943 // $$$ could there be single pixel rounding errors for L vs R?
1944 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
1945 return parseInt( (pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1947 return parseInt( (1 - pindex/this.numLeafs) * this.twoPageEdgeW + 0.5);
1951 // jumpIndexForLeftEdgePageX
1952 //______________________________________________________________________________
1953 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
1954 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
1955 if ('rl' != this.pageProgression) {
1956 // LTR - flipping backward
1957 var jumpIndex = this.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1959 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
1960 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexL - 2);
1964 var jumpIndex = this.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
1965 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexL + 2, this.lastDisplayableIndex());
1970 // jumpIndexForRightEdgePageX
1971 //______________________________________________________________________________
1972 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
1973 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
1974 if ('rl' != this.pageProgression) {
1976 var jumpIndex = this.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
1977 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.currentIndexR + 2, this.lastDisplayableIndex());
1980 var jumpIndex = this.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
1981 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.currentIndexR - 2);
1986 GnuBook.prototype.initToolbar = function(mode, ui) {
1988 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
1989 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
1990 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom1up(-1); return false;'/>"
1991 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom1up(1); return false;'/>"
1992 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
1993 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
1994 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
1995 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
1998 if (ui == "embed") {
1999 $("#GnuBook a.logo").attr("target","_blank");
2002 // $$$ turn this into a member variable
2003 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2005 // We build in mode 2
2006 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2007 + "<button class='GBicon rollover embed' />"
2008 + "<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>"
2009 + "<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>"
2010 + "<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>"
2011 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2013 this.bindToolbarNavHandlers(jToolbar);
2015 // Setup tooltips -- later we could load these from a file for i18n
2016 var titles = { '.logo': 'Go to Archive.org',
2017 '.zoom_in': 'Zoom in',
2018 '.zoom_out': 'Zoom out',
2019 '.one_page_mode': 'One-page view',
2020 '.two_page_mode': 'Two-page view',
2021 '.embed': 'Embed bookreader',
2022 '.book_left': 'Flip left',
2023 '.book_right': 'Flip right',
2024 '.book_up': 'Page up',
2025 '.book_down': 'Page down',
2028 '.book_top': 'First page',
2029 '.book_bottom': 'Last page'
2031 if ('rl' == this.pageProgression) {
2032 titles['.book_leftmost'] = 'Last page';
2033 titles['.book_rightmost'] = 'First page';
2035 titles['.book_leftmost'] = 'First page';
2036 titles['.book_rightmost'] = 'Last page';
2039 for (var icon in titles) {
2040 jToolbar.find(icon).attr('title', titles[icon]);
2043 // Hide mode buttons and autoplay if 2up is not available
2044 // $$$ if we end up with more than two modes we should show the applicable buttons
2045 if ( !this.canSwitchToMode(this.constMode2up) ) {
2046 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2049 // Switch to requested mode -- binds other click handlers
2050 this.switchToolbarMode(mode);
2055 // switchToolbarMode
2056 //______________________________________________________________________________
2057 // Update the toolbar for the given mode (changes navigation buttons)
2058 // $$$ we should soon split the toolbar out into its own module
2059 GnuBook.prototype.switchToolbarMode = function(mode) {
2062 $('#GBtoolbar .GBtoolbarmode2').hide();
2063 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2066 $('#GBtoolbar .GBtoolbarmode1').hide();
2067 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2071 // bindToolbarNavHandlers
2072 //______________________________________________________________________________
2073 // Binds the toolbar handlers
2074 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2076 jToolbar.find('.book_left').bind('click', function(e) {
2081 jToolbar.find('.book_right').bind('click', function(e) {
2086 jToolbar.find('.book_up').bind('click', function(e) {
2091 jToolbar.find('.book_down').bind('click', function(e) {
2096 jToolbar.find('.embed').bind('click', function(e) {
2101 jToolbar.find('.play').bind('click', function(e) {
2106 jToolbar.find('.pause').bind('click', function(e) {
2111 jToolbar.find('.book_top').bind('click', function(e) {
2116 jToolbar.find('.book_bottom').bind('click', function(e) {
2121 jToolbar.find('.book_leftmost').bind('click', function(e) {
2126 jToolbar.find('.book_rightmost').bind('click', function(e) {
2132 // firstDisplayableIndex
2133 //______________________________________________________________________________
2134 // Returns the index of the first visible page, dependent on the mode.
2135 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2136 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2137 GnuBook.prototype.firstDisplayableIndex = function() {
2138 if (this.mode == 0) {
2141 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2145 // lastDisplayableIndex
2146 //______________________________________________________________________________
2147 // Returns the index of the last visible page, dependent on the mode.
2148 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2149 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2150 GnuBook.prototype.lastDisplayableIndex = function() {
2151 if (this.mode == 2) {
2152 if (this.lastDisplayableIndex2up === null) {
2153 // Calculate and cache
2154 var candidate = this.numLeafs - 1;
2155 for ( ; candidate >= 0; candidate--) {
2156 var spreadIndices = this.getSpreadIndices(candidate);
2157 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2161 this.lastDisplayableIndex2up = candidate;
2163 return this.lastDisplayableIndex2up;
2165 return this.numLeafs - 1;
2169 // shortTitle(maximumCharacters)
2171 // Returns a shortened version of the title with the maximum number of characters
2172 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2173 if (this.bookTitle.length < maximumCharacters) {
2174 return this.bookTitle;
2177 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2184 // Parameter related functions
2186 // updateFromParams(params)
2188 // Update ourselves from the params object.
2190 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2191 GnuBook.prototype.updateFromParams = function(params) {
2192 if ('undefined' != typeof(params.mode)) {
2193 this.switchMode(params.mode);
2196 // $$$ process /search
2197 // $$$ process /zoom
2199 // We only respect page if index is not set
2200 if ('undefined' != typeof(params.index)) {
2201 if (params.index != this.currentIndex()) {
2202 this.jumpToIndex(params.index);
2204 } else if ('undefined' != typeof(params.page)) {
2205 // $$$ this assumes page numbers are unique
2206 if (params.page != this.getPageNum(this.currentIndex())) {
2207 this.jumpToPage(params.page);
2211 // $$$ process /region
2212 // $$$ process /highlight
2215 // paramsFromFragment(urlFragment)
2217 // Returns a object with configuration parametes from a URL fragment.
2219 // E.g paramsFromFragment(window.location.hash)
2220 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2221 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2225 // For convenience we allow an initial # character (as from window.location.hash)
2226 // but don't require it
2227 if (urlFragment.substr(0,1) == '#') {
2228 urlFragment = urlFragment.substr(1);
2231 // Simple #nn syntax
2232 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2233 if ( !isNaN(oldStyleLeafNum) ) {
2234 params.index = oldStyleLeafNum;
2236 // Done processing if using old-style syntax
2240 // Split into key-value pairs
2241 var urlArray = urlFragment.split('/');
2243 for (var i = 0; i < urlArray.length; i += 2) {
2244 urlHash[urlArray[i]] = urlArray[i+1];
2248 if ('1up' == urlHash['mode']) {
2249 params.mode = this.constMode1up;
2250 } else if ('2up' == urlHash['mode']) {
2251 params.mode = this.constMode2up;
2255 if ('undefined' != typeof(urlHash['page'])) {
2256 // page was set -- may not be int
2257 params.page = urlHash['page'];
2260 // $$$ process /region
2261 // $$$ process /search
2262 // $$$ process /highlight
2267 // paramsFromCurrent()
2269 // Create a params object from the current parameters.
2270 GnuBook.prototype.paramsFromCurrent = function() {
2274 var pageNum = this.getPageNum(this.currentIndex());
2275 if ((pageNum === 0) || pageNum) {
2276 params.page = pageNum;
2279 params.index = this.currentIndex();
2280 params.mode = this.mode;
2289 // fragmentFromParams(params)
2291 // Create a fragment string from the params object.
2292 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2293 GnuBook.prototype.fragmentFromParams = function(params) {
2294 var separator = '/';
2298 if ('undefined' != typeof(params.page)) {
2299 fragments.push('page', params.page);
2301 // Don't have page numbering -- use index instead
2302 fragments.push('page', 'n' + params.index);
2310 if ('undefined' != typeof(params.mode)) {
2311 if (params.mode == this.constMode1up) {
2312 fragments.push('mode', '1up');
2313 } else if (params.mode == this.constMode2up) {
2314 fragments.push('mode', '2up');
2316 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2320 return fragments.join(separator);
2323 // getPageIndex(pageNum)
2325 // Returns the *highest* index the given page number, or undefined
2326 GnuBook.prototype.getPageIndex = function(pageNum) {
2327 var pageIndices = this.getPageIndices(pageNum);
2329 if (pageIndices.length > 0) {
2330 return pageIndices[pageIndices.length - 1];
2336 // getPageIndices(pageNum)
2338 // Returns an array (possibly empty) of the indices with the given page number
2339 GnuBook.prototype.getPageIndices = function(pageNum) {
2342 // Check for special "nXX" page number
2343 if (pageNum.slice(0,1) == 'n') {
2345 var pageIntStr = pageNum.slice(1, pageNum.length);
2346 var pageIndex = parseInt(pageIntStr);
2347 indices.append(pageIndex);
2350 // Do nothing... will run through page names and see if one matches
2355 for (i=0; i<this.numLeafs; i++) {
2356 if (this.getPageNum(i) == pageNum) {
2364 // getPageName(index)
2366 // Returns the name of the page as it should be displayed in the user interface
2367 GnuBook.prototype.getPageName = function(index) {
2368 return 'Page ' + this.getPageNum(index);
2371 // updateLocationHash
2373 // Update the location hash from the current parameters. Call this instead of manually
2374 // using window.location.replace
2375 GnuBook.prototype.updateLocationHash = function() {
2376 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2377 window.location.replace(newHash);
2379 // This is the variable checked in the timer. Only user-generated changes
2380 // to the URL will trigger the event.
2381 this.oldLocationHash = newHash;
2384 // startLocationPolling
2386 // Starts polling of window.location to see hash fragment changes
2387 GnuBook.prototype.startLocationPolling = function() {
2388 var self = this; // remember who I am
2389 self.oldLocationHash = window.location.hash;
2391 if (this.locationPollId) {
2392 clearInterval(this.locationPollID);
2393 this.locationPollId = null;
2396 this.locationPollId = setInterval(function() {
2397 var newHash = window.location.hash;
2398 if (newHash != self.oldLocationHash) {
2399 if (newHash != self.oldUserHash) { // Only process new user hash once
2400 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2402 // Queue change if animating
2403 if (self.animating) {
2405 self.animationFinishedCallback = function() {
2406 self.updateFromParams(self.paramsFromFragment(newHash));
2408 } else { // update immediately
2409 self.updateFromParams(self.paramsFromFragment(newHash));
2411 self.oldUserHash = newHash;
2419 // Returns a URL for an embedded version of the current book
2420 GnuBook.prototype.getEmbedURL = function() {
2421 // We could generate a URL hash fragment here but for now we just leave at defaults
2422 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2427 // Returns the embed code HTML fragment suitable for copy and paste
2428 GnuBook.prototype.getEmbedCode = function() {
2429 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2434 // Returns true if we can switch to the requested mode
2435 GnuBook.prototype.canSwitchToMode = function(mode) {
2436 if (mode == this.constMode2up) {
2437 // check there are enough pages to display
2438 // $$$ this is a workaround for the mis-feature that we can't display
2439 // short books in 2up mode
2440 if (this.numLeafs < 6) {
2448 // Library functions
2450 clamp: function(value, min, max) {
2451 return Math.min(Math.max(value, min), max);