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;
75 // Object to hold parameters related to 2up mode
77 coverInternalPadding: 10, // Width of cover
83 //______________________________________________________________________________
84 GnuBook.prototype.init = function() {
86 var startIndex = undefined;
88 // Find start index and mode if set in location hash
89 var params = this.paramsFromFragment(window.location.hash);
91 if ('undefined' != typeof(params.index)) {
92 startIndex = params.index;
93 } else if ('undefined' != typeof(params.page)) {
94 startIndex = this.getPageIndex(params.page);
97 if ('undefined' == typeof(startIndex)) {
98 if ('undefined' != typeof(this.titleLeaf)) {
99 startIndex = this.leafNumToIndex(this.titleLeaf);
103 if ('undefined' == typeof(startIndex)) {
107 if ('undefined' != typeof(params.mode)) {
108 this.mode = params.mode;
111 // Set document title -- may have already been set in enclosing html for
112 // search engine visibility
113 document.title = this.shortTitle(50);
115 // Sanitize parameters
116 if ( !this.canSwitchToMode( this.mode ) ) {
117 this.mode = this.constMode1up;
120 $("#GnuBook").empty();
121 this.initToolbar(this.mode, this.ui); // Build inside of toolbar div
122 $("#GnuBook").append("<div id='GBcontainer'></div>");
123 $("#GBcontainer").append("<div id='GBpageview'></div>");
125 $("#GBcontainer").bind('scroll', this, function(e) {
129 this.setupKeyListeners();
130 this.startLocationPolling();
132 $(window).bind('resize', this, function(e) {
133 //console.log('resize!');
134 if (1 == e.data.mode) {
135 //console.log('centering 1page view');
136 e.data.centerPageView();
137 $('#GBpageview').empty()
138 e.data.displayedIndices = [];
139 e.data.updateSearchHilites(); //deletes hilights but does not call remove()
142 //console.log('drawing 2 page view');
143 e.data.prepareTwoPageView();
147 $('.GBpagediv1up').bind('mousedown', this, function(e) {
148 //console.log('mousedown!');
151 if (1 == this.mode) {
152 this.resizePageView();
153 this.firstIndex = startIndex;
154 this.jumpToIndex(startIndex);
156 //this.resizePageView();
158 this.displayedIndices=[0];
159 this.firstIndex = startIndex;
160 this.displayedIndices = [this.firstIndex];
161 //console.log('titleLeaf: %d', this.titleLeaf);
162 //console.log('displayedIndices: %s', this.displayedIndices);
163 this.prepareTwoPageView();
164 //if (this.auto) this.nextPage();
167 // Enact other parts of initial params
168 this.updateFromParams(params);
171 GnuBook.prototype.setupKeyListeners = function() {
184 // We use document here instead of window to avoid a bug in jQuery on IE7
185 $(document).keydown(function(e) {
187 // Keyboard navigation
191 // In 1up mode page scrolling is handled by browser
192 if (2 == self.mode) {
198 if (2 == self.mode) {
209 if (self.keyboardNavigationIsDisabled(e)) {
212 if (2 == self.mode) {
217 if (self.keyboardNavigationIsDisabled(e)) {
220 if (2 == self.mode) {
229 //______________________________________________________________________________
230 GnuBook.prototype.drawLeafs = function() {
231 if (1 == this.mode) {
232 this.drawLeafsOnePage();
234 this.drawLeafsTwoPage();
238 // setDragHandler1up()
239 //______________________________________________________________________________
240 GnuBook.prototype.setDragHandler1up = function(div) {
241 div.dragging = false;
243 $(div).bind('mousedown', function(e) {
244 //console.log('mousedown at ' + e.pageY);
246 this.dragging = true;
247 this.prevMouseX = e.pageX;
248 this.prevMouseY = e.pageY;
250 var startX = e.pageX;
251 var startY = e.pageY;
252 var startTop = $('#GBcontainer').attr('scrollTop');
253 var startLeft = $('#GBcontainer').attr('scrollLeft');
258 $(div).bind('mousemove', function(ee) {
259 //console.log('mousemove ' + startY);
261 var offsetX = ee.pageX - this.prevMouseX;
262 var offsetY = ee.pageY - this.prevMouseY;
265 $('#GBcontainer').attr('scrollTop', $('#GBcontainer').attr('scrollTop') - offsetY);
266 $('#GBcontainer').attr('scrollLeft', $('#GBcontainer').attr('scrollLeft') - offsetX);
269 this.prevMouseX = ee.pageX;
270 this.prevMouseY = ee.pageY;
275 $(div).bind('mouseup', function(ee) {
276 //console.log('mouseup');
278 this.dragging = false;
282 $(div).bind('mouseleave', function(e) {
283 //console.log('mouseleave');
285 //$(this).unbind('mousemove mouseup');
286 this.dragging = false;
291 // drawLeafsOnePage()
292 //______________________________________________________________________________
293 GnuBook.prototype.drawLeafsOnePage = function() {
294 //alert('drawing leafs!');
298 var scrollTop = $('#GBcontainer').attr('scrollTop');
299 var scrollBottom = scrollTop + $('#GBcontainer').height();
300 //console.log('top=' + scrollTop + ' bottom='+scrollBottom);
302 var indicesToDisplay = [];
307 for (i=0; i<this.numLeafs; i++) {
308 var height = parseInt(this.getPageHeight(i)/this.reduce);
310 leafBottom += height;
311 //console.log('leafTop = '+leafTop+ ' pageH = ' + this.pageH[i] + 'leafTop>=scrollTop=' + (leafTop>=scrollTop));
312 var topInView = (leafTop >= scrollTop) && (leafTop <= scrollBottom);
313 var bottomInView = (leafBottom >= scrollTop) && (leafBottom <= scrollBottom);
314 var middleInView = (leafTop <=scrollTop) && (leafBottom>=scrollBottom);
315 if (topInView | bottomInView | middleInView) {
316 //console.log('displayed: ' + this.displayedIndices);
317 //console.log('to display: ' + i);
318 indicesToDisplay.push(i);
320 leafTop += height +10;
324 var firstIndexToDraw = indicesToDisplay[0];
325 this.firstIndex = firstIndexToDraw;
327 // Update hash, but only if we're currently displaying a leaf
328 // Hack that fixes #365790
329 if (this.displayedIndices.length > 0) {
330 this.updateLocationHash();
333 if ((0 != firstIndexToDraw) && (1 < this.reduce)) {
335 indicesToDisplay.unshift(firstIndexToDraw);
338 var lastIndexToDraw = indicesToDisplay[indicesToDisplay.length-1];
339 if ( ((this.numLeafs-1) != lastIndexToDraw) && (1 < this.reduce) ) {
340 indicesToDisplay.push(lastIndexToDraw+1);
345 for (i=0; i<firstIndexToDraw; i++) {
346 leafTop += parseInt(this.getPageHeight(i)/this.reduce) +10;
349 //var viewWidth = $('#GBpageview').width(); //includes scroll bar width
350 var viewWidth = $('#GBcontainer').attr('scrollWidth');
353 for (i=0; i<indicesToDisplay.length; i++) {
354 var index = indicesToDisplay[i];
355 var height = parseInt(this.getPageHeight(index)/this.reduce);
357 if(-1 == jQuery.inArray(indicesToDisplay[i], this.displayedIndices)) {
358 var width = parseInt(this.getPageWidth(index)/this.reduce);
359 //console.log("displaying leaf " + indicesToDisplay[i] + ' leafTop=' +leafTop);
360 var div = document.createElement("div");
361 div.className = 'GBpagediv1up';
362 div.id = 'pagediv'+index;
363 div.style.position = "absolute";
364 $(div).css('top', leafTop + 'px');
365 var left = (viewWidth-width)>>1;
366 if (left<0) left = 0;
367 $(div).css('left', left+'px');
368 $(div).css('width', width+'px');
369 $(div).css('height', height+'px');
370 //$(div).text('loading...');
372 this.setDragHandler1up(div);
374 $('#GBpageview').append(div);
376 var img = document.createElement("img");
377 img.src = this.getPageURI(index);
378 $(img).css('width', width+'px');
379 $(img).css('height', height+'px');
383 //console.log("not displaying " + indicesToDisplay[i] + ' score=' + jQuery.inArray(indicesToDisplay[i], this.displayedIndices));
386 leafTop += height +10;
390 for (i=0; i<this.displayedIndices.length; i++) {
391 if (-1 == jQuery.inArray(this.displayedIndices[i], indicesToDisplay)) {
392 var index = this.displayedIndices[i];
393 //console.log('Removing leaf ' + index);
394 //console.log('id='+'#pagediv'+index+ ' top = ' +$('#pagediv'+index).css('top'));
395 $('#pagediv'+index).remove();
397 //console.log('NOT Removing leaf ' + this.displayedIndices[i]);
401 this.displayedIndices = indicesToDisplay.slice();
402 this.updateSearchHilites();
404 if (null != this.getPageNum(firstIndexToDraw)) {
405 $("#GBpagenum").val(this.getPageNum(this.currentIndex()));
407 $("#GBpagenum").val('');
410 //var centerY = this.centerY1up();
411 //var centerX = this.centerX1up();
412 //console.log('draw center ' + centerY + ',' + centerX);
413 //console.log('scroll left ' + $('#GBcontainer').attr('scrollLeft'));
417 // drawLeafsTwoPage()
418 //______________________________________________________________________________
419 GnuBook.prototype.drawLeafsTwoPage = function() {
420 console.log('drawing two leafs!'); // XXX
422 var scrollTop = $('#GBtwopageview').attr('scrollTop');
423 var scrollBottom = scrollTop + $('#GBtwopageview').height();
425 console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.twoPage.currentIndexL); // XXX
427 var indexL = this.twoPage.currentIndexL;
428 var heightL = this.getPageHeight(indexL);
429 var widthL = this.getPageWidth(indexL);
431 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
432 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
433 var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
434 //console.log(leafEdgeWidthL);
436 var middle, top, bookCoverDivLeft;
437 if (this.twoPage.autofit) {
438 middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
439 top = ($('#GBtwopageview').attr('clientHeight') - this.twoPage.height) >> 1;
440 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
442 // $$$ add external padding
443 middle = $('#GBtwopageview').width() >> 1;
444 top = this.twoPage.coverInternalPadding; // $$$ TODO getter for top
445 bookCoverDivLeft = 0; // $$$ TODO getter for left
448 // $$$ should get getwidth2up?
449 //var scaledWL = parseInt(this.twoPage.height*widthL/heightL);
450 var scaledWL = this.getPageWidth2UP(indexL);
451 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
453 this.prefetchImg(indexL);
454 $(this.prefetchedImgs[indexL]).css({
455 position: 'absolute',
456 left: gutter-scaledWL+'px',
459 backgroundColor: 'rgb(234, 226, 205)',
460 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
461 width: scaledWL + 'px',
462 borderRight: '1px solid black',
464 }).appendTo('#GBtwopageview');
467 var indexR = this.twoPage.currentIndexR;
468 var heightR = this.getPageHeight(indexR);
469 var widthR = this.getPageWidth(indexR);
471 // $$$ should use getwidth2up?
472 //var scaledWR = this.twoPage.height*widthR/heightR;
473 var scaledWR = this.getPageWidth2UP(indexR);
474 this.prefetchImg(indexR);
475 $(this.prefetchedImgs[indexR]).css({
476 position: 'absolute',
480 backgroundColor: 'rgb(234, 226, 205)',
481 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
482 width: scaledWR + 'px',
483 borderLeft: '1px solid black',
485 }).appendTo('#GBtwopageview');
488 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
489 this.setClickHandlers();
491 this.updatePageNumBox2UP();
494 // updatePageNumBox2UP
495 //______________________________________________________________________________
496 GnuBook.prototype.updatePageNumBox2UP = function() {
497 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
498 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
500 $("#GBpagenum").val('');
502 this.updateLocationHash();
506 //______________________________________________________________________________
507 GnuBook.prototype.loadLeafs = function() {
511 if (null == this.timer) {
512 this.timer=setTimeout(function(){self.drawLeafs()},250);
514 clearTimeout(this.timer);
515 this.timer=setTimeout(function(){self.drawLeafs()},250);
521 // Pass 1 to zoom in, anything else to zoom out
522 //______________________________________________________________________________
523 GnuBook.prototype.zoom = function(direction) {
525 case this.constMode1up:
526 return this.zoom1up(direction);
527 case this.constMode2up:
528 return this.zoom2up(direction);
533 //______________________________________________________________________________
534 GnuBook.prototype.zoom1up = function(dir) {
535 if (2 == this.mode) { //can only zoom in 1-page mode
540 // $$$ with flexible zoom we could "snap" to /2 page reductions
541 // for better scaling
543 if (this.reduce <= 0.5) return;
544 this.reduce*=0.5; //zoom in
546 if (this.reduce >= 8) return;
547 this.reduce*=2; //zoom out
550 this.resizePageView();
552 $('#GBpageview').empty()
553 this.displayedIndices = [];
556 $('#GBzoom').text(100/this.reduce);
560 //______________________________________________________________________________
561 GnuBook.prototype.resizePageView = function() {
564 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
565 var viewWidth = $('#GBcontainer').attr('clientWidth');
567 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
568 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
569 var oldPageViewHeight = $('#GBpageview').height();
570 var oldPageViewWidth = $('#GBpageview').width();
572 var oldCenterY = this.centerY1up();
573 var oldCenterX = this.centerX1up();
575 if (0 != oldPageViewHeight) {
576 var scrollRatio = oldCenterY / oldPageViewHeight;
581 for (i=0; i<this.numLeafs; i++) {
582 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
583 var width = parseInt(this.getPageWidth(i)/this.reduce);
584 if (width>viewWidth) viewWidth=width;
586 $('#GBpageview').height(viewHeight);
587 $('#GBpageview').width(viewWidth);
589 var newCenterY = scrollRatio*viewHeight;
590 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
591 $('#GBcontainer').attr('scrollTop', newTop);
593 // We use clientWidth here to avoid miscalculating due to scroll bar
594 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
595 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
596 newLeft = Math.max(newLeft, 0);
597 $('#GBcontainer').attr('scrollLeft', newLeft);
598 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
600 //this.centerPageView();
606 //______________________________________________________________________________
607 // Returns the current offset of the viewport center in scaled document coordinates.
608 GnuBook.prototype.centerX1up = function() {
610 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
611 centerX = $('#GBpageview').width();
613 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
615 centerX = Math.floor(centerX);
620 //______________________________________________________________________________
621 // Returns the current offset of the viewport center in scaled document coordinates.
622 GnuBook.prototype.centerY1up = function() {
623 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
624 return Math.floor(centerY);
628 //______________________________________________________________________________
629 GnuBook.prototype.centerPageView = function() {
631 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
632 var clientWidth = $('#GBcontainer').attr('clientWidth');
633 //console.log('sW='+scrollWidth+' cW='+clientWidth);
634 if (scrollWidth > clientWidth) {
635 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
640 // zoom2up(direction)
641 //______________________________________________________________________________
642 GnuBook.prototype.zoom2up = function(direction) {
643 // $$$ this is where we can e.g. snap to %2 sizes
644 if (0 == direction) { // autofit mode
645 this.twoPage.autofit = true;;
646 } else if (1 == direction) {
647 if (this.reduce <= 0.5) return;
648 this.reduce*=0.5; //zoom in
649 this.twoPage.autofit = false;
651 if (this.reduce >= 8) return;
652 this.reduce *= 2; // zoom out
653 this.twoPage.autofit = false;
656 this.prepareTwoPageView();
660 //______________________________________________________________________________
661 // Attempts to jump to page. Returns true if page could be found, false otherwise.
662 GnuBook.prototype.jumpToPage = function(pageNum) {
664 var pageIndex = this.getPageIndex(pageNum);
666 if ('undefined' != typeof(pageIndex)) {
669 this.jumpToIndex(pageIndex);
670 $('#GBcontainer').attr('scrollTop', leafTop);
679 //______________________________________________________________________________
680 GnuBook.prototype.jumpToIndex = function(index) {
682 if (2 == this.mode) {
685 // By checking against min/max we do nothing if requested index
687 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
688 this.flipBackToIndex(index);
689 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
690 this.flipFwdToIndex(index);
697 for (i=0; i<index; i++) {
698 h = parseInt(this.getPageHeight(i)/this.reduce);
699 leafTop += h + this.padding;
701 //$('#GBcontainer').attr('scrollTop', leafTop);
702 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
709 //______________________________________________________________________________
710 GnuBook.prototype.switchMode = function(mode) {
712 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
714 if (mode == this.mode) return;
716 if (!this.canSwitchToMode(mode)) {
721 this.removeSearchHilites();
725 this.switchToolbarMode(mode);
728 this.prepareOnePageView();
730 this.prepareTwoPageView();
735 //prepareOnePageView()
736 //______________________________________________________________________________
737 GnuBook.prototype.prepareOnePageView = function() {
739 // var startLeaf = this.displayedIndices[0];
740 var startLeaf = this.currentIndex();
742 $('#GBcontainer').empty();
743 $('#GBcontainer').css({
748 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
750 this.resizePageView();
752 this.jumpToIndex(startLeaf);
753 this.displayedIndices = [];
755 this.drawLeafsOnePage();
756 $('#GBzoom').text(100/this.reduce);
758 // Bind mouse handlers
759 // Disable mouse click to avoid selected/highlighted page images - bug 354239
760 gbPageView.bind('mousedown', function(e) {
763 // Special hack for IE7
764 gbPageView[0].onselectstart = function(e) { return false; };
767 // prepareTwoPageView()
768 //______________________________________________________________________________
769 GnuBook.prototype.prepareTwoPageView = function() {
770 $('#GBcontainer').empty();
771 $('#GBcontainer').css('overflow', 'auto');
774 // Add the two page view
775 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
776 // Explicitly set sizes the same
777 $('#GBtwopageview').css( {
778 height: $('#GBcontainer').height(),
779 width: $('#GBcontainer').width(),
783 // We want to display two facing pages. We may be missing
784 // one side of the spread because it is the first/last leaf,
785 // foldouts, missing pages, etc
787 //var targetLeaf = this.displayedIndices[0];
788 var targetLeaf = this.firstIndex;
790 if (targetLeaf < this.firstDisplayableIndex()) {
791 targetLeaf = this.firstDisplayableIndex();
794 if (targetLeaf > this.lastDisplayableIndex()) {
795 targetLeaf = this.lastDisplayableIndex();
798 this.twoPage.currentIndexL = null;
799 this.twoPage.currentIndexR = null;
800 this.pruneUnusedImgs();
802 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
803 this.twoPage.currentIndexL = currentSpreadIndices[0];
804 this.twoPage.currentIndexR = currentSpreadIndices[1];
805 this.firstIndex = this.twoPage.currentIndexL;
807 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height, and twoPage.ratio
809 var scaledWL = this.getPageWidth2UP(this.twoPage.currentIndexL);
810 var scaledWR = this.getPageWidth2UP(this.twoPage.currentIndexR);
811 var leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
812 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
814 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
815 //var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth;
817 // The width of the book cover div. The combined width of both pages, twice the width
818 // of the book cover internal padding (2*10) and the page edges
819 var bookCoverDivWidth = scaledWL + scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
821 // The height of the book cover div
822 var bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
825 // XXX explicitly set size of GBtwopageview here then use that when calculating positions
826 // GBtwopageview should have autoscroll turned off
827 $('#GBtwopageview').width(bookCoverDivWidth).height(bookCoverDivHeight);
829 // We want to minimize the unused space in two-up mode (maximize the amount of page
830 // shown). We give width to the leaf edges and these widths change (though the sum
831 // of the two remains constant) as we flip through the book. With the book
832 // cover centered and fixed in the GBcontainer div the page images will meet
833 // at the "gutter" which is generally offset from the center.
834 var middle = ($('#GBtwopageview').width() >> 1); // Middle of the page view
835 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
837 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
838 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-this.twoPage.coverInternalPadding;
839 var bookCoverDivTop = ($('#GBtwopageview').height() - bookCoverDivHeight) >> 1;
840 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
842 this.twoPageDiv = document.createElement('div');
843 $(this.twoPageDiv).attr('id', 'GBbookcover').css({
844 border: '1px solid rgb(68, 25, 17)',
845 width: bookCoverDivWidth + 'px',
846 height: bookCoverDivHeight+'px',
847 visibility: 'visible',
848 position: 'absolute',
849 backgroundColor: '#663929',
850 left: bookCoverDivLeft + 'px',
851 top: bookCoverDivTop+'px',
852 MozBorderRadiusTopleft: '7px',
853 MozBorderRadiusTopright: '7px',
854 MozBorderRadiusBottomright: '7px',
855 MozBorderRadiusBottomleft: '7px'
856 }).appendTo('#GBtwopageview');
859 var height = this.getPageHeight(this.twoPage.currentIndexR);
860 var width = this.getPageWidth(this.twoPage.currentIndexR);
861 var scaledW = this.twoPage.height*width/height;
863 this.leafEdgeR = document.createElement('div');
864 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
865 $(this.leafEdgeR).css({
866 borderStyle: 'solid solid solid none',
867 borderColor: 'rgb(51, 51, 34)',
868 borderWidth: '1px 1px 1px 0px',
869 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
870 width: leafEdgeWidthR + 'px',
871 height: this.twoPage.height-1 + 'px',
873 left: gutter+scaledW+'px',
874 top: bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
876 }).appendTo('#GBtwopageview');
878 this.leafEdgeL = document.createElement('div');
879 this.leafEdgeL.className = 'leafEdgeL';
880 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
881 borderStyle: 'solid none solid solid',
882 borderColor: 'rgb(51, 51, 34)',
883 borderWidth: '1px 0px 1px 1px',
884 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
885 width: leafEdgeWidthL + 'px',
886 height: this.twoPage.height-1 + 'px',
887 left: bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
888 top: bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
890 }).appendTo('#GBtwopageview');
894 var bookSpineDivWidth = 30;
895 bookSpineDivHeight = this.twoPage.height+20;
896 bookSpineDivLeft = ($('#GBtwopageview').width() - bookSpineDivWidth) >> 1;
897 bookSpineDivTop = ($('#GBtwopageview').height() - bookSpineDivHeight) >> 1;
899 div = document.createElement('div');
900 $(div).attr('id', 'GBbookspine').css({
901 border: '1px solid rgb(68, 25, 17)',
902 width: bookSpineDivWidth+'px',
903 height: bookSpineDivHeight+'px',
904 position: 'absolute',
905 backgroundColor: 'rgb(68, 25, 17)',
906 left: bookSpineDivLeft+'px',
907 top: bookSpineDivTop+'px'
908 }).appendTo('#GBtwopageview');
911 bookCoverDivWidth = this.twoPage.width*2;
912 bookCoverDivHeight = this.twoPage.height;
913 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
914 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
917 this.prepareTwoPagePopUp();
919 this.displayedIndices = [];
921 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
922 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
924 this.drawLeafsTwoPage();
925 this.updateSearchHilites2UP();
928 // $$$ Zoom text formatting could be cleaner - see https://bugs.edge.launchpad.net/gnubook/+bug/411581
929 $('#GBzoom').text((100*this.twoPage.height/this.getPageHeight(this.twoPage.currentIndexL)).toString().substr(0,4));
932 // prepareTwoPagePopUp()
934 // This function prepares the "View Page n" popup that shows while the mouse is
935 // over the left/right "stack of sheets" edges. It also binds the mouse
936 // events for these divs.
937 //______________________________________________________________________________
938 GnuBook.prototype.prepareTwoPagePopUp = function() {
940 this.twoPagePopUp = document.createElement('div');
941 $(this.twoPagePopUp).css({
942 border: '1px solid black',
944 position: 'absolute',
945 fontFamily: 'sans-serif',
948 backgroundColor: 'rgb(255, 255, 238)',
950 }).appendTo('#GBcontainer');
951 $(this.twoPagePopUp).hide();
953 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
954 $(e.data.twoPagePopUp).show();
957 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
958 $(e.data.twoPagePopUp).hide();
961 $(this.leafEdgeL).bind('click', this, function(e) {
963 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
964 e.data.jumpToIndex(jumpIndex);
967 $(this.leafEdgeR).bind('click', this, function(e) {
969 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
970 e.data.jumpToIndex(jumpIndex);
973 $(this.leafEdgeR).bind('mousemove', this, function(e) {
975 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
976 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
978 // $$$ TODO: Make sure popup is positioned so that it is in view
979 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
980 $(e.data.twoPagePopUp).css({
981 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
982 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
986 $(this.leafEdgeL).bind('mousemove', this, function(e) {
988 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
989 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
991 // $$$ TODO: Make sure popup is positioned so that it is in view
992 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
993 $(e.data.twoPagePopUp).css({
994 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
995 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
1000 // calculateSpreadSize()
1001 //______________________________________________________________________________
1002 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
1003 // this.twoPage.currentIndexR
1004 // This function sets this.twoPage.height, twoPage.width, and twoPage.ratio
1006 GnuBook.prototype.calculateSpreadSize = function() {
1007 console.log('calculateSpreadSize ' + this.twoPage.currentIndexL); // XXX
1009 // $$$ TODO Calculate the spread size based on the reduction factor. If we are using
1010 // fit mode we recalculate the reduction factor based on the current page sizes
1011 // and display size first.
1013 var firstIndex = this.twoPage.currentIndexL;
1014 var secondIndex = this.twoPage.currentIndexR;
1015 //console.log('first page is ' + firstIndex);
1017 // $$$ Right now we just use the ideal size
1019 if ( this.twoPage.autofit) {
1020 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1022 // set based on reduction factor
1023 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1025 console.dir(spreadSize);
1028 this.twoPage.height = spreadSize.height;
1029 this.twoPage.width = spreadSize.width;
1030 this.twoPage.ratio = spreadSize.ratio;
1031 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1032 this.reduce = spreadSize.reduce;
1035 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1038 var canon5Dratio = 1.5;
1041 height: this.getPageHeight(firstIndex),
1042 width: this.getPageWidth(firstIndex)
1046 height: this.getPageHeight(secondIndex),
1047 width: this.getPageWidth(secondIndex)
1050 var firstIndexRatio = first.height / first.width;
1051 var secondIndexRatio = second.height / second.width;
1052 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1054 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1055 ideal.ratio = firstIndexRatio;
1056 //console.log('using firstIndexRatio ' + ratio);
1058 ideal.ratio = secondIndexRatio;
1059 //console.log('using secondIndexRatio ' + ratio);
1062 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1063 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1064 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1066 ideal.width = ($('#GBcontainer').attr('clientWidth') - 30 - ideal.totalLeafEdgeWidth)>>1;
1067 ideal.height = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1068 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
1070 if (ideal.height/ideal.ratio <= ideal.width) {
1072 ideal.width = parseInt(ideal.height/ideal.ratio);
1075 ideal.height = parseInt(ideal.width*ideal.ratio);
1078 // XXX check this logic with large spreads
1079 ideal.reduce = ((first.width + second.width) / 2) / ideal.width;
1084 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1085 var spreadSize = {};
1086 // $$$ Scale this based on reduce?
1087 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1088 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1089 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1091 // $$$ this isn't quite right when the pages are different sizes
1092 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1093 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1094 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1095 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1096 spreadSize.reduce = reduce;
1099 console.log('spread size: ' + firstIndex + ',' + secondIndex + ',' + reduce);
1105 //______________________________________________________________________________
1106 // Returns the currently active index.
1107 GnuBook.prototype.currentIndex = function() {
1108 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1109 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1110 return this.firstIndex;
1112 throw 'currentIndex called for unimplemented mode ' + this.mode;
1117 //______________________________________________________________________________
1118 // Flip the right page over onto the left
1119 GnuBook.prototype.right = function() {
1120 if ('rl' != this.pageProgression) {
1130 //______________________________________________________________________________
1131 // Flip to the rightmost page
1132 GnuBook.prototype.rightmost = function() {
1133 if ('rl' != this.pageProgression) {
1141 //______________________________________________________________________________
1142 // Flip the left page over onto the right.
1143 GnuBook.prototype.left = function() {
1144 if ('rl' != this.pageProgression) {
1154 //______________________________________________________________________________
1155 // Flip to the leftmost page
1156 GnuBook.prototype.leftmost = function() {
1157 if ('rl' != this.pageProgression) {
1165 //______________________________________________________________________________
1166 GnuBook.prototype.next = function() {
1167 if (2 == this.mode) {
1169 this.flipFwdToIndex(null);
1171 if (this.firstIndex < this.lastDisplayableIndex()) {
1172 this.jumpToIndex(this.firstIndex+1);
1178 //______________________________________________________________________________
1179 GnuBook.prototype.prev = function() {
1180 if (2 == this.mode) {
1182 this.flipBackToIndex(null);
1184 if (this.firstIndex >= 1) {
1185 this.jumpToIndex(this.firstIndex-1);
1190 GnuBook.prototype.first = function() {
1191 if (2 == this.mode) {
1192 this.jumpToIndex(2);
1195 this.jumpToIndex(0);
1199 GnuBook.prototype.last = function() {
1200 if (2 == this.mode) {
1201 this.jumpToIndex(this.lastDisplayableIndex());
1204 this.jumpToIndex(this.lastDisplayableIndex());
1208 // flipBackToIndex()
1209 //______________________________________________________________________________
1210 // to flip back one spread, pass index=null
1211 GnuBook.prototype.flipBackToIndex = function(index) {
1212 if (1 == this.mode) return;
1214 var leftIndex = this.twoPage.currentIndexL;
1216 // $$$ Need to change this to be able to see first spread.
1217 // See https://bugs.launchpad.net/gnubook/+bug/296788
1218 if (leftIndex <= 2) return;
1219 if (this.animating) return;
1221 if (null != this.leafEdgeTmp) {
1222 alert('error: leafEdgeTmp should be null!');
1226 if (null == index) {
1227 index = leftIndex-2;
1229 //if (index<0) return;
1231 var previousIndices = this.getSpreadIndices(index);
1233 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1237 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1239 this.animating = true;
1241 if ('rl' != this.pageProgression) {
1242 // Assume LTR and we are going backward
1243 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1244 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1247 // RTL and going backward
1248 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1249 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1253 // flipLeftToRight()
1254 //______________________________________________________________________________
1255 // Flips the page on the left towards the page on the right
1256 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1258 var leftLeaf = this.twoPage.currentIndexL;
1260 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1261 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1262 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1264 var currWidthL = this.getPageWidth2UP(leftLeaf);
1265 var newWidthL = this.getPageWidth2UP(newIndexL);
1266 var newWidthR = this.getPageWidth2UP(newIndexR);
1268 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1270 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1271 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1273 //animation strategy:
1274 // 0. remove search highlight, if any.
1275 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1276 // of the left leaf and where the user clicked in the leaf edge.
1277 // Note that if this function was triggered by left() and not a
1278 // mouse click, the width of leafEdgeTmp is very small (zero px).
1279 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1280 // leftLeaf to width=0.
1281 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1282 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1283 // its new full width.
1284 // 4. After step 3 is finished, do the following:
1285 // - remove leafEdgeTmp from the dom.
1286 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1287 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1288 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1289 // and width=newLeafEdgeWidthL.
1290 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1291 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1292 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1293 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1294 // - prefetch new adjacent leafs.
1295 // - set up click handlers for both new left and right leafs.
1296 // - redraw the search highlight.
1297 // - update the pagenum box and the url.
1300 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1302 this.leafEdgeTmp = document.createElement('div');
1303 $(this.leafEdgeTmp).css({
1304 borderStyle: 'solid none solid solid',
1305 borderColor: 'rgb(51, 51, 34)',
1306 borderWidth: '1px 0px 1px 1px',
1307 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1308 width: leafEdgeTmpW + 'px',
1309 height: this.twoPage.height-1 + 'px',
1310 left: leftEdgeTmpLeft + 'px',
1312 position: 'absolute',
1314 }).appendTo('#GBtwopageview');
1316 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1317 $(this.leafEdgeL).css({
1318 width: newLeafEdgeWidthL+'px',
1319 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1322 // Left gets the offset of the current left leaf from the document
1323 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1324 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1325 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1326 // We change the left leaf to right positioning
1327 $(this.prefetchedImgs[leftLeaf]).css({
1332 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1334 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1336 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1337 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1341 this.removeSearchHilites();
1343 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1344 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1346 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1347 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1349 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1350 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1351 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1353 $(self.leafEdgeR).css({
1354 // Moves the right leaf edge
1355 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1356 left: gutter+newWidthR+'px'
1359 $(self.leafEdgeL).css({
1360 // Moves and resizes the left leaf edge
1361 width: newLeafEdgeWidthL+'px',
1362 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1366 $(self.twoPageDiv).css({
1367 // Resizes the brown border div
1368 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1369 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1372 $(self.leafEdgeTmp).remove();
1373 self.leafEdgeTmp = null;
1375 self.twoPage.currentIndexL = newIndexL;
1376 self.twoPage.currentIndexR = newIndexR;
1377 self.firstIndex = self.twoPage.currentIndexL;
1378 self.displayedIndices = [newIndexL, newIndexR];
1379 self.setClickHandlers();
1380 self.pruneUnusedImgs();
1382 self.animating = false;
1384 self.updateSearchHilites2UP();
1385 self.updatePageNumBox2UP();
1386 //$('#GBzoom').text((self.twoPage.height/self.getPageHeight(newIndexL)).toString().substr(0,4));
1388 if (self.animationFinishedCallback) {
1389 self.animationFinishedCallback();
1390 self.animationFinishedCallback = null;
1398 //______________________________________________________________________________
1399 // Whether we flip left or right is dependent on the page progression
1400 // to flip forward one spread, pass index=null
1401 GnuBook.prototype.flipFwdToIndex = function(index) {
1403 if (this.animating) return;
1405 if (null != this.leafEdgeTmp) {
1406 alert('error: leafEdgeTmp should be null!');
1410 if (null == index) {
1411 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1413 if (index > this.lastDisplayableIndex()) return;
1415 this.animating = true;
1417 var nextIndices = this.getSpreadIndices(index);
1419 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1421 if ('rl' != this.pageProgression) {
1422 // We did not specify RTL
1423 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1424 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1427 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1428 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1432 // flipRightToLeft(nextL, nextR, gutter)
1433 // $$$ better not to have to pass gutter in
1434 //______________________________________________________________________________
1435 // Flip from left to right and show the nextL and nextR indices on those sides
1436 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1437 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1438 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1439 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1440 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1442 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1444 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1446 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1448 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1449 var currGutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1452 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1454 this.leafEdgeTmp = document.createElement('div');
1455 $(this.leafEdgeTmp).css({
1456 borderStyle: 'solid none solid solid',
1457 borderColor: 'rgb(51, 51, 34)',
1458 borderWidth: '1px 0px 1px 1px',
1459 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1460 width: leafEdgeTmpW + 'px',
1461 height: this.twoPage.height-1 + 'px',
1462 left: currGutter+scaledW+'px',
1464 position: 'absolute',
1466 }).appendTo('#GBtwopageview');
1468 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1469 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1471 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1472 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1473 var newWidthL = this.getPageWidth2UP(newIndexL);
1474 var newWidthR = this.getPageWidth2UP(newIndexR);
1476 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1478 var self = this; // closure-tastic!
1480 var speed = this.flipSpeed;
1482 this.removeSearchHilites();
1484 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1485 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1486 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1487 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1488 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1490 $(self.leafEdgeL).css({
1491 width: newLeafEdgeWidthL+'px',
1492 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1495 $(self.twoPageDiv).css({
1496 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1497 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1500 $(self.leafEdgeTmp).remove();
1501 self.leafEdgeTmp = null;
1503 self.twoPage.currentIndexL = newIndexL;
1504 self.twoPage.currentIndexR = newIndexR;
1505 self.firstIndex = self.twoPage.currentIndexL;
1506 self.displayedIndices = [newIndexL, newIndexR];
1507 self.setClickHandlers();
1508 self.pruneUnusedImgs();
1510 self.animating = false;
1513 self.updateSearchHilites2UP();
1514 self.updatePageNumBox2UP();
1515 //$('#GBzoom').text((self.twoPage.height/self.getPageHeight(newIndexL)).toString().substr(0,4));
1517 if (self.animationFinishedCallback) {
1518 self.animationFinishedCallback();
1519 self.animationFinishedCallback = null;
1526 //______________________________________________________________________________
1527 GnuBook.prototype.setClickHandlers = function() {
1529 // $$$ TODO don't set again if already set
1530 $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
1535 $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
1543 //______________________________________________________________________________
1544 GnuBook.prototype.prefetchImg = function(index) {
1545 if (undefined == this.prefetchedImgs[index]) {
1546 //console.log('prefetching ' + index);
1547 var img = document.createElement("img");
1548 img.src = this.getPageURI(index);
1549 this.prefetchedImgs[index] = img;
1554 // prepareFlipLeftToRight()
1556 //______________________________________________________________________________
1558 // Prepare to flip the left page towards the right. This corresponds to moving
1559 // backward when the page progression is left to right.
1560 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1562 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1564 this.prefetchImg(prevL);
1565 this.prefetchImg(prevR);
1567 var height = this.getPageHeight(prevL);
1568 var width = this.getPageWidth(prevL);
1569 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1570 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1571 var scaledW = this.twoPage.height*width/height;
1573 // The gutter is the dividing line between the left and right pages.
1574 // It is offset from the middle to create the illusion of thickness to the pages
1575 var gutter = middle + this.gutterOffsetForIndex(prevL);
1578 console.log(' gutter for ' + prevL + ' is ' + gutter);
1579 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1580 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1582 $(this.prefetchedImgs[prevL]).css({
1583 position: 'absolute',
1584 /*right: middle+'px',*/
1585 left: gutter-scaledW+'px',
1588 backgroundColor: 'rgb(234, 226, 205)',
1589 height: this.twoPage.height,
1590 width: scaledW+'px',
1591 borderRight: '1px solid black',
1595 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1597 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1599 $(this.prefetchedImgs[prevR]).css({
1600 position: 'absolute',
1604 backgroundColor: 'rgb(234, 226, 205)',
1605 height: this.twoPage.height,
1607 borderLeft: '1px solid black',
1611 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1618 // XXXmang we're adding an extra pixel in the middle
1619 // prepareFlipRightToLeft()
1620 //______________________________________________________________________________
1621 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1623 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1625 this.prefetchImg(nextL);
1626 this.prefetchImg(nextR);
1628 var height = this.getPageHeight(nextR);
1629 var width = this.getPageWidth(nextR);
1630 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1631 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1632 var scaledW = this.twoPage.height*width/height;
1634 var gutter = middle + this.gutterOffsetForIndex(nextL);
1636 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1638 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1639 $(this.prefetchedImgs[nextR]).css({
1640 position: 'absolute',
1643 backgroundColor: 'rgb(234, 226, 205)',
1644 height: this.twoPage.height,
1645 width: scaledW+'px',
1646 borderLeft: '1px solid black',
1650 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1652 height = this.getPageHeight(nextL);
1653 width = this.getPageWidth(nextL);
1654 scaledW = this.twoPage.height*width/height;
1656 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1657 $(this.prefetchedImgs[nextL]).css({
1658 position: 'absolute',
1659 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1661 backgroundColor: 'rgb(234, 226, 205)',
1662 height: this.twoPage.height,
1664 borderRight: '1px solid black',
1668 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1674 // getNextLeafs() -- NOT RTL AWARE
1675 //______________________________________________________________________________
1676 // GnuBook.prototype.getNextLeafs = function(o) {
1677 // //TODO: we might have two left or two right leafs in a row (damaged book)
1678 // //For now, assume that leafs are contiguous.
1680 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1681 // o.L = this.twoPage.currentIndexL+2;
1682 // o.R = this.twoPage.currentIndexL+3;
1685 // getprevLeafs() -- NOT RTL AWARE
1686 //______________________________________________________________________________
1687 // GnuBook.prototype.getPrevLeafs = function(o) {
1688 // //TODO: we might have two left or two right leafs in a row (damaged book)
1689 // //For now, assume that leafs are contiguous.
1691 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1692 // o.L = this.twoPage.currentIndexL-2;
1693 // o.R = this.twoPage.currentIndexL-1;
1696 // pruneUnusedImgs()
1697 //______________________________________________________________________________
1698 GnuBook.prototype.pruneUnusedImgs = function() {
1699 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1700 for (var key in this.prefetchedImgs) {
1701 //console.log('key is ' + key);
1702 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1703 //console.log('removing key '+ key);
1704 $(this.prefetchedImgs[key]).remove();
1706 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1707 //console.log('deleting key '+ key);
1708 delete this.prefetchedImgs[key];
1714 //______________________________________________________________________________
1715 GnuBook.prototype.prefetch = function() {
1717 var lim = this.twoPage.currentIndexL-4;
1719 lim = Math.max(lim, 0);
1720 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1721 this.prefetchImg(i);
1724 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1725 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1726 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1727 this.prefetchImg(i);
1732 // getPageWidth2UP()
1733 //______________________________________________________________________________
1734 GnuBook.prototype.getPageWidth2UP = function(index) {
1735 var height = this.getPageHeight(index);
1736 var width = this.getPageWidth(index);
1737 return Math.floor(this.twoPage.height*width/height);
1741 //______________________________________________________________________________
1742 GnuBook.prototype.search = function(term) {
1743 $('#GnuBookSearchScript').remove();
1744 var script = document.createElement("script");
1745 script.setAttribute('id', 'GnuBookSearchScript');
1746 script.setAttribute("type", "text/javascript");
1747 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1748 document.getElementsByTagName('head')[0].appendChild(script);
1749 $('#GnuBookSearchResults').html('Searching...');
1752 // GBSearchCallback()
1753 //______________________________________________________________________________
1754 GnuBook.prototype.GBSearchCallback = function(txt) {
1756 if (jQuery.browser.msie) {
1757 var dom=new ActiveXObject("Microsoft.XMLDOM");
1761 var parser = new DOMParser();
1762 var dom = parser.parseFromString(txt, "text/xml");
1765 $('#GnuBookSearchResults').empty();
1766 $('#GnuBookSearchResults').append('<ul>');
1768 for (var key in this.searchResults) {
1769 if (null != this.searchResults[key].div) {
1770 $(this.searchResults[key].div).remove();
1772 delete this.searchResults[key];
1775 var pages = dom.getElementsByTagName('PAGE');
1777 if (0 == pages.length) {
1778 // $$$ it would be nice to echo the (sanitized) search result here
1779 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1781 for (var i = 0; i < pages.length; i++){
1782 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1785 var re = new RegExp (/_(\d{4})/);
1786 var reMatch = re.exec(pages[i].getAttribute('file'));
1787 var index = parseInt(reMatch[1], 10);
1788 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1790 var children = pages[i].childNodes;
1792 for (var j=0; j<children.length; j++) {
1793 //console.log(j + ' - ' + children[j].nodeName);
1794 //console.log(children[j].firstChild.nodeValue);
1795 if ('CONTEXT' == children[j].nodeName) {
1796 context += children[j].firstChild.nodeValue;
1797 } else if ('WORD' == children[j].nodeName) {
1798 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1800 var index = this.leafNumToIndex(index);
1801 if (null != index) {
1802 //coordinates are [left, bottom, right, top, [baseline]]
1803 //we'll skip baseline for now...
1804 var coords = children[j].getAttribute('coords').split(',',4);
1805 if (4 == coords.length) {
1806 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1811 var pageName = this.getPageName(index);
1812 //TODO: remove hardcoded instance name
1813 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1816 $('#GnuBookSearchResults').append('</ul>');
1818 this.updateSearchHilites();
1821 // updateSearchHilites()
1822 //______________________________________________________________________________
1823 GnuBook.prototype.updateSearchHilites = function() {
1824 if (2 == this.mode) {
1825 this.updateSearchHilites2UP();
1827 this.updateSearchHilites1UP();
1831 // showSearchHilites1UP()
1832 //______________________________________________________________________________
1833 GnuBook.prototype.updateSearchHilites1UP = function() {
1835 for (var key in this.searchResults) {
1837 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1838 var result = this.searchResults[key];
1839 if(null == result.div) {
1840 result.div = document.createElement('div');
1841 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1842 //console.log('appending ' + key);
1845 width: (result.r-result.l)/this.reduce + 'px',
1846 height: (result.b-result.t)/this.reduce + 'px',
1847 left: (result.l)/this.reduce + 'px',
1848 top: (result.t)/this.reduce +'px'
1852 //console.log(key + ' not displayed');
1853 this.searchResults[key].div=null;
1858 // showSearchHilites2UP()
1859 //______________________________________________________________________________
1860 GnuBook.prototype.updateSearchHilites2UP = function() {
1862 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1864 for (var key in this.searchResults) {
1865 key = parseInt(key, 10);
1866 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1867 var result = this.searchResults[key];
1868 if(null == result.div) {
1869 result.div = document.createElement('div');
1870 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1871 //console.log('appending ' + key);
1874 var height = this.getPageHeight(key);
1875 var width = this.getPageWidth(key)
1876 var reduce = this.twoPage.height/height;
1877 var scaledW = parseInt(width*reduce);
1879 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1881 if ('L' == this.getPageSide(key)) {
1882 var pageL = gutter-scaledW;
1886 var pageT = ($('#GBtwopagview').height() - this.twoPage.height) >> 1;
1889 width: (result.r-result.l)*reduce + 'px',
1890 height: (result.b-result.t)*reduce + 'px',
1891 left: pageL+(result.l)*reduce + 'px',
1892 top: pageT+(result.t)*reduce +'px'
1896 //console.log(key + ' not displayed');
1897 if (null != this.searchResults[key].div) {
1898 //console.log('removing ' + key);
1899 $(this.searchResults[key].div).remove();
1901 this.searchResults[key].div=null;
1906 // removeSearchHilites()
1907 //______________________________________________________________________________
1908 GnuBook.prototype.removeSearchHilites = function() {
1909 for (var key in this.searchResults) {
1910 if (null != this.searchResults[key].div) {
1911 $(this.searchResults[key].div).remove();
1912 this.searchResults[key].div=null;
1918 //______________________________________________________________________________
1919 GnuBook.prototype.showEmbedCode = function() {
1920 if (null != this.embedPopup) { // check if already showing
1924 this.embedPopup = document.createElement("div");
1925 $(this.embedPopup).css({
1926 position: 'absolute',
1928 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1931 border: "3px double #999999",
1933 backgroundColor: "#fff"
1934 }).appendTo('#GnuBook');
1936 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1937 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>';
1938 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1939 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1941 this.embedPopup.innerHTML = htmlStr;
1942 $(this.embedPopup).find('input').bind('click', function() {
1948 //______________________________________________________________________________
1949 GnuBook.prototype.autoToggle = function() {
1951 var bComingFrom1up = false;
1952 if (2 != this.mode) {
1953 bComingFrom1up = true;
1958 if (null == this.autoTimer) {
1959 this.flipSpeed = 2000;
1961 // $$$ Draw events currently cause layout problems when they occur during animation.
1962 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1963 // we workaround for now by not triggering immediate animation in that case.
1964 // See https://bugs.launchpad.net/gnubook/+bug/328327
1965 if (('rl' == this.pageProgression) && bComingFrom1up) {
1966 // don't flip immediately -- wait until timer fires
1969 this.flipFwdToIndex();
1972 $('#GBtoolbar .play').hide();
1973 $('#GBtoolbar .pause').show();
1974 this.autoTimer=setInterval(function(){
1975 if (self.animating) {return;}
1977 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
1978 self.flipBackToIndex(1); // $$$ really what we want?
1980 self.flipFwdToIndex();
1989 //______________________________________________________________________________
1990 GnuBook.prototype.autoStop = function() {
1991 if (null != this.autoTimer) {
1992 clearInterval(this.autoTimer);
1993 this.flipSpeed = 'fast';
1994 $('#GBtoolbar .pause').hide();
1995 $('#GBtoolbar .play').show();
1996 this.autoTimer = null;
2000 // keyboardNavigationIsDisabled(event)
2001 // - returns true if keyboard navigation should be disabled for the event
2002 //______________________________________________________________________________
2003 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
2004 if (event.target.tagName == "INPUT") {
2010 // gutterOffsetForIndex
2011 //______________________________________________________________________________
2013 // Returns the gutter offset for the spread containing the given index.
2014 // This function supports RTL
2015 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2017 // To find the offset of the gutter from the middle we calculate our percentage distance
2018 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2019 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2021 // But then again for RTL it's the opposite
2022 if ('rl' == this.pageProgression) {
2030 //______________________________________________________________________________
2031 // Returns the width of the leaf edge div for the page with index given
2032 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2033 // $$$ could there be single pixel rounding errors for L vs R?
2034 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2035 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2037 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2041 // jumpIndexForLeftEdgePageX
2042 //______________________________________________________________________________
2043 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2044 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2045 if ('rl' != this.pageProgression) {
2046 // LTR - flipping backward
2047 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2049 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2050 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2054 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2055 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2060 // jumpIndexForRightEdgePageX
2061 //______________________________________________________________________________
2062 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2063 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2064 if ('rl' != this.pageProgression) {
2066 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2067 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2070 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2071 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2076 GnuBook.prototype.initToolbar = function(mode, ui) {
2078 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2079 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2080 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2081 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2082 + " <span class='label'>Zoom: <span id='GBzoom'>"+100/this.reduce+"</span>%</span>"
2083 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2084 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2085 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2088 if (ui == "embed") {
2089 $("#GnuBook a.logo").attr("target","_blank");
2092 // $$$ turn this into a member variable
2093 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2095 // We build in mode 2
2096 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2097 + "<button class='GBicon rollover embed' />"
2098 + "<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>"
2099 + "<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>"
2100 + "<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>"
2101 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2103 this.bindToolbarNavHandlers(jToolbar);
2105 // Setup tooltips -- later we could load these from a file for i18n
2106 var titles = { '.logo': 'Go to Archive.org',
2107 '.zoom_in': 'Zoom in',
2108 '.zoom_out': 'Zoom out',
2109 '.one_page_mode': 'One-page view',
2110 '.two_page_mode': 'Two-page view',
2111 '.embed': 'Embed bookreader',
2112 '.book_left': 'Flip left',
2113 '.book_right': 'Flip right',
2114 '.book_up': 'Page up',
2115 '.book_down': 'Page down',
2118 '.book_top': 'First page',
2119 '.book_bottom': 'Last page'
2121 if ('rl' == this.pageProgression) {
2122 titles['.book_leftmost'] = 'Last page';
2123 titles['.book_rightmost'] = 'First page';
2125 titles['.book_leftmost'] = 'First page';
2126 titles['.book_rightmost'] = 'Last page';
2129 for (var icon in titles) {
2130 jToolbar.find(icon).attr('title', titles[icon]);
2133 // Hide mode buttons and autoplay if 2up is not available
2134 // $$$ if we end up with more than two modes we should show the applicable buttons
2135 if ( !this.canSwitchToMode(this.constMode2up) ) {
2136 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2139 // Switch to requested mode -- binds other click handlers
2140 this.switchToolbarMode(mode);
2145 // switchToolbarMode
2146 //______________________________________________________________________________
2147 // Update the toolbar for the given mode (changes navigation buttons)
2148 // $$$ we should soon split the toolbar out into its own module
2149 GnuBook.prototype.switchToolbarMode = function(mode) {
2152 $('#GBtoolbar .GBtoolbarmode2').hide();
2153 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2156 $('#GBtoolbar .GBtoolbarmode1').hide();
2157 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2161 // bindToolbarNavHandlers
2162 //______________________________________________________________________________
2163 // Binds the toolbar handlers
2164 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2166 jToolbar.find('.book_left').bind('click', function(e) {
2171 jToolbar.find('.book_right').bind('click', function(e) {
2176 jToolbar.find('.book_up').bind('click', function(e) {
2181 jToolbar.find('.book_down').bind('click', function(e) {
2186 jToolbar.find('.embed').bind('click', function(e) {
2191 jToolbar.find('.play').bind('click', function(e) {
2196 jToolbar.find('.pause').bind('click', function(e) {
2201 jToolbar.find('.book_top').bind('click', function(e) {
2206 jToolbar.find('.book_bottom').bind('click', function(e) {
2211 jToolbar.find('.book_leftmost').bind('click', function(e) {
2216 jToolbar.find('.book_rightmost').bind('click', function(e) {
2222 // firstDisplayableIndex
2223 //______________________________________________________________________________
2224 // Returns the index of the first visible page, dependent on the mode.
2225 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2226 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2227 GnuBook.prototype.firstDisplayableIndex = function() {
2228 if (this.mode == 0) {
2231 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2235 // lastDisplayableIndex
2236 //______________________________________________________________________________
2237 // Returns the index of the last visible page, dependent on the mode.
2238 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2239 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2240 GnuBook.prototype.lastDisplayableIndex = function() {
2241 if (this.mode == 2) {
2242 if (this.lastDisplayableIndex2up === null) {
2243 // Calculate and cache
2244 var candidate = this.numLeafs - 1;
2245 for ( ; candidate >= 0; candidate--) {
2246 var spreadIndices = this.getSpreadIndices(candidate);
2247 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2251 this.lastDisplayableIndex2up = candidate;
2253 return this.lastDisplayableIndex2up;
2255 return this.numLeafs - 1;
2259 // shortTitle(maximumCharacters)
2261 // Returns a shortened version of the title with the maximum number of characters
2262 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2263 if (this.bookTitle.length < maximumCharacters) {
2264 return this.bookTitle;
2267 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2274 // Parameter related functions
2276 // updateFromParams(params)
2278 // Update ourselves from the params object.
2280 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2281 GnuBook.prototype.updateFromParams = function(params) {
2282 if ('undefined' != typeof(params.mode)) {
2283 this.switchMode(params.mode);
2286 // $$$ process /search
2287 // $$$ process /zoom
2289 // We only respect page if index is not set
2290 if ('undefined' != typeof(params.index)) {
2291 if (params.index != this.currentIndex()) {
2292 this.jumpToIndex(params.index);
2294 } else if ('undefined' != typeof(params.page)) {
2295 // $$$ this assumes page numbers are unique
2296 if (params.page != this.getPageNum(this.currentIndex())) {
2297 this.jumpToPage(params.page);
2301 // $$$ process /region
2302 // $$$ process /highlight
2305 // paramsFromFragment(urlFragment)
2307 // Returns a object with configuration parametes from a URL fragment.
2309 // E.g paramsFromFragment(window.location.hash)
2310 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2311 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2315 // For convenience we allow an initial # character (as from window.location.hash)
2316 // but don't require it
2317 if (urlFragment.substr(0,1) == '#') {
2318 urlFragment = urlFragment.substr(1);
2321 // Simple #nn syntax
2322 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2323 if ( !isNaN(oldStyleLeafNum) ) {
2324 params.index = oldStyleLeafNum;
2326 // Done processing if using old-style syntax
2330 // Split into key-value pairs
2331 var urlArray = urlFragment.split('/');
2333 for (var i = 0; i < urlArray.length; i += 2) {
2334 urlHash[urlArray[i]] = urlArray[i+1];
2338 if ('1up' == urlHash['mode']) {
2339 params.mode = this.constMode1up;
2340 } else if ('2up' == urlHash['mode']) {
2341 params.mode = this.constMode2up;
2345 if ('undefined' != typeof(urlHash['page'])) {
2346 // page was set -- may not be int
2347 params.page = urlHash['page'];
2350 // $$$ process /region
2351 // $$$ process /search
2352 // $$$ process /highlight
2357 // paramsFromCurrent()
2359 // Create a params object from the current parameters.
2360 GnuBook.prototype.paramsFromCurrent = function() {
2364 var pageNum = this.getPageNum(this.currentIndex());
2365 if ((pageNum === 0) || pageNum) {
2366 params.page = pageNum;
2369 params.index = this.currentIndex();
2370 params.mode = this.mode;
2379 // fragmentFromParams(params)
2381 // Create a fragment string from the params object.
2382 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2383 GnuBook.prototype.fragmentFromParams = function(params) {
2384 var separator = '/';
2388 if ('undefined' != typeof(params.page)) {
2389 fragments.push('page', params.page);
2391 // Don't have page numbering -- use index instead
2392 fragments.push('page', 'n' + params.index);
2400 if ('undefined' != typeof(params.mode)) {
2401 if (params.mode == this.constMode1up) {
2402 fragments.push('mode', '1up');
2403 } else if (params.mode == this.constMode2up) {
2404 fragments.push('mode', '2up');
2406 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2410 return fragments.join(separator);
2413 // getPageIndex(pageNum)
2415 // Returns the *highest* index the given page number, or undefined
2416 GnuBook.prototype.getPageIndex = function(pageNum) {
2417 var pageIndices = this.getPageIndices(pageNum);
2419 if (pageIndices.length > 0) {
2420 return pageIndices[pageIndices.length - 1];
2426 // getPageIndices(pageNum)
2428 // Returns an array (possibly empty) of the indices with the given page number
2429 GnuBook.prototype.getPageIndices = function(pageNum) {
2432 // Check for special "nXX" page number
2433 if (pageNum.slice(0,1) == 'n') {
2435 var pageIntStr = pageNum.slice(1, pageNum.length);
2436 var pageIndex = parseInt(pageIntStr);
2437 indices.append(pageIndex);
2440 // Do nothing... will run through page names and see if one matches
2445 for (i=0; i<this.numLeafs; i++) {
2446 if (this.getPageNum(i) == pageNum) {
2454 // getPageName(index)
2456 // Returns the name of the page as it should be displayed in the user interface
2457 GnuBook.prototype.getPageName = function(index) {
2458 return 'Page ' + this.getPageNum(index);
2461 // updateLocationHash
2463 // Update the location hash from the current parameters. Call this instead of manually
2464 // using window.location.replace
2465 GnuBook.prototype.updateLocationHash = function() {
2466 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2467 window.location.replace(newHash);
2469 // This is the variable checked in the timer. Only user-generated changes
2470 // to the URL will trigger the event.
2471 this.oldLocationHash = newHash;
2474 // startLocationPolling
2476 // Starts polling of window.location to see hash fragment changes
2477 GnuBook.prototype.startLocationPolling = function() {
2478 var self = this; // remember who I am
2479 self.oldLocationHash = window.location.hash;
2481 if (this.locationPollId) {
2482 clearInterval(this.locationPollID);
2483 this.locationPollId = null;
2486 this.locationPollId = setInterval(function() {
2487 var newHash = window.location.hash;
2488 if (newHash != self.oldLocationHash) {
2489 if (newHash != self.oldUserHash) { // Only process new user hash once
2490 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2492 // Queue change if animating
2493 if (self.animating) {
2495 self.animationFinishedCallback = function() {
2496 self.updateFromParams(self.paramsFromFragment(newHash));
2498 } else { // update immediately
2499 self.updateFromParams(self.paramsFromFragment(newHash));
2501 self.oldUserHash = newHash;
2509 // Returns a URL for an embedded version of the current book
2510 GnuBook.prototype.getEmbedURL = function() {
2511 // We could generate a URL hash fragment here but for now we just leave at defaults
2512 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2517 // Returns the embed code HTML fragment suitable for copy and paste
2518 GnuBook.prototype.getEmbedCode = function() {
2519 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2524 // Returns true if we can switch to the requested mode
2525 GnuBook.prototype.canSwitchToMode = function(mode) {
2526 if (mode == this.constMode2up) {
2527 // check there are enough pages to display
2528 // $$$ this is a workaround for the mis-feature that we can't display
2529 // short books in 2up mode
2530 if (this.numLeafs < 6) {
2538 // Library functions
2540 clamp: function(value, min, max) {
2541 return Math.min(Math.max(value, min), max);