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 this.updateToolbarZoom(this.reduce);
414 // drawLeafsTwoPage()
415 //______________________________________________________________________________
416 GnuBook.prototype.drawLeafsTwoPage = function() {
417 console.log('drawing two leafs!'); // XXX
419 var scrollTop = $('#GBtwopageview').attr('scrollTop');
420 var scrollBottom = scrollTop + $('#GBtwopageview').height();
422 console.log('drawLeafsTwoPage: this.currrentLeafL ' + this.twoPage.currentIndexL); // XXX
424 var indexL = this.twoPage.currentIndexL;
425 var heightL = this.getPageHeight(indexL);
426 var widthL = this.getPageWidth(indexL);
428 var leafEdgeWidthL = this.leafEdgeWidth(indexL);
429 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
430 var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth; // $$$ hardcoded cover width
431 //console.log(leafEdgeWidthL);
433 var middle, top, bookCoverDivLeft;
434 if (this.twoPage.autofit) {
435 middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
436 top = ($('#GBtwopageview').attr('clientHeight') - this.twoPage.height) >> 1;
437 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
439 // $$$ add external padding
440 middle = $('#GBtwopageview').width() >> 1;
441 top = this.twoPage.coverInternalPadding; // $$$ TODO getter for top
442 bookCoverDivLeft = 0; // $$$ TODO getter for left
445 // $$$ should get getwidth2up?
446 //var scaledWL = parseInt(this.twoPage.height*widthL/heightL);
447 var scaledWL = this.getPageWidth2UP(indexL);
448 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
450 this.prefetchImg(indexL);
451 $(this.prefetchedImgs[indexL]).css({
452 position: 'absolute',
453 left: gutter-scaledWL+'px',
456 backgroundColor: 'rgb(234, 226, 205)',
457 height: this.twoPage.height +'px', // $$$ height forced the same for both pages
458 width: scaledWL + 'px',
459 borderRight: '1px solid black',
461 }).appendTo('#GBtwopageview');
464 var indexR = this.twoPage.currentIndexR;
465 var heightR = this.getPageHeight(indexR);
466 var widthR = this.getPageWidth(indexR);
468 // $$$ should use getwidth2up?
469 //var scaledWR = this.twoPage.height*widthR/heightR;
470 var scaledWR = this.getPageWidth2UP(indexR);
471 this.prefetchImg(indexR);
472 $(this.prefetchedImgs[indexR]).css({
473 position: 'absolute',
477 backgroundColor: 'rgb(234, 226, 205)',
478 height: this.twoPage.height + 'px', // $$$ height forced the same for both pages
479 width: scaledWR + 'px',
480 borderLeft: '1px solid black',
482 }).appendTo('#GBtwopageview');
485 this.displayedIndices = [this.twoPage.currentIndexL, this.twoPage.currentIndexR];
486 this.setClickHandlers();
488 this.updatePageNumBox2UP();
489 this.updateToolbarZoom(this.reduce);
492 // updatePageNumBox2UP
493 //______________________________________________________________________________
494 GnuBook.prototype.updatePageNumBox2UP = function() {
495 if (null != this.getPageNum(this.twoPage.currentIndexL)) {
496 $("#GBpagenum").val(this.getPageNum(this.twoPage.currentIndexL));
498 $("#GBpagenum").val('');
500 this.updateLocationHash();
504 //______________________________________________________________________________
505 GnuBook.prototype.loadLeafs = function() {
509 if (null == this.timer) {
510 this.timer=setTimeout(function(){self.drawLeafs()},250);
512 clearTimeout(this.timer);
513 this.timer=setTimeout(function(){self.drawLeafs()},250);
519 // Pass 1 to zoom in, anything else to zoom out
520 //______________________________________________________________________________
521 GnuBook.prototype.zoom = function(direction) {
523 case this.constMode1up:
524 return this.zoom1up(direction);
525 case this.constMode2up:
526 return this.zoom2up(direction);
531 //______________________________________________________________________________
532 GnuBook.prototype.zoom1up = function(dir) {
533 if (2 == this.mode) { //can only zoom in 1-page mode
538 // $$$ with flexible zoom we could "snap" to /2 page reductions
539 // for better scaling
541 if (this.reduce <= 0.5) return;
542 this.reduce*=0.5; //zoom in
544 if (this.reduce >= 8) return;
545 this.reduce*=2; //zoom out
548 this.resizePageView();
550 $('#GBpageview').empty()
551 this.displayedIndices = [];
554 this.updateToolbarZoom(this.reduce);
558 //______________________________________________________________________________
559 GnuBook.prototype.resizePageView = function() {
562 //var viewWidth = $('#GBcontainer').width(); //includes scrollBar
563 var viewWidth = $('#GBcontainer').attr('clientWidth');
565 var oldScrollTop = $('#GBcontainer').attr('scrollTop');
566 var oldScrollLeft = $('#GBcontainer').attr('scrollLeft');
567 var oldPageViewHeight = $('#GBpageview').height();
568 var oldPageViewWidth = $('#GBpageview').width();
570 var oldCenterY = this.centerY1up();
571 var oldCenterX = this.centerX1up();
573 if (0 != oldPageViewHeight) {
574 var scrollRatio = oldCenterY / oldPageViewHeight;
579 for (i=0; i<this.numLeafs; i++) {
580 viewHeight += parseInt(this.getPageHeight(i)/this.reduce) + this.padding;
581 var width = parseInt(this.getPageWidth(i)/this.reduce);
582 if (width>viewWidth) viewWidth=width;
584 $('#GBpageview').height(viewHeight);
585 $('#GBpageview').width(viewWidth);
587 var newCenterY = scrollRatio*viewHeight;
588 var newTop = Math.max(0, Math.floor( newCenterY - $('#GBcontainer').height()/2 ));
589 $('#GBcontainer').attr('scrollTop', newTop);
591 // We use clientWidth here to avoid miscalculating due to scroll bar
592 var newCenterX = oldCenterX * (viewWidth / oldPageViewWidth);
593 var newLeft = newCenterX - $('#GBcontainer').attr('clientWidth') / 2;
594 newLeft = Math.max(newLeft, 0);
595 $('#GBcontainer').attr('scrollLeft', newLeft);
596 //console.log('oldCenterX ' + oldCenterX + ' newCenterX ' + newCenterX + ' newLeft ' + newLeft);
598 //this.centerPageView();
604 //______________________________________________________________________________
605 // Returns the current offset of the viewport center in scaled document coordinates.
606 GnuBook.prototype.centerX1up = function() {
608 if ($('#GBpageview').width() < $('#GBcontainer').attr('clientWidth')) { // fully shown
609 centerX = $('#GBpageview').width();
611 centerX = $('#GBcontainer').attr('scrollLeft') + $('#GBcontainer').attr('clientWidth') / 2;
613 centerX = Math.floor(centerX);
618 //______________________________________________________________________________
619 // Returns the current offset of the viewport center in scaled document coordinates.
620 GnuBook.prototype.centerY1up = function() {
621 var centerY = $('#GBcontainer').attr('scrollTop') + $('#GBcontainer').height() / 2;
622 return Math.floor(centerY);
626 //______________________________________________________________________________
627 GnuBook.prototype.centerPageView = function() {
629 var scrollWidth = $('#GBcontainer').attr('scrollWidth');
630 var clientWidth = $('#GBcontainer').attr('clientWidth');
631 //console.log('sW='+scrollWidth+' cW='+clientWidth);
632 if (scrollWidth > clientWidth) {
633 $('#GBcontainer').attr('scrollLeft', (scrollWidth-clientWidth)/2);
638 // zoom2up(direction)
639 //______________________________________________________________________________
640 GnuBook.prototype.zoom2up = function(direction) {
641 // $$$ this is where we can e.g. snap to %2 sizes
642 if (0 == direction) { // autofit mode
643 this.twoPage.autofit = true;;
644 } else if (1 == direction) {
645 if (this.reduce <= 0.5) return;
646 this.reduce*=0.5; //zoom in
647 this.twoPage.autofit = false;
649 if (this.reduce >= 8) return;
650 this.reduce *= 2; // zoom out
651 this.twoPage.autofit = false;
654 this.prepareTwoPageView();
658 //______________________________________________________________________________
659 // Attempts to jump to page. Returns true if page could be found, false otherwise.
660 GnuBook.prototype.jumpToPage = function(pageNum) {
662 var pageIndex = this.getPageIndex(pageNum);
664 if ('undefined' != typeof(pageIndex)) {
667 this.jumpToIndex(pageIndex);
668 $('#GBcontainer').attr('scrollTop', leafTop);
677 //______________________________________________________________________________
678 GnuBook.prototype.jumpToIndex = function(index) {
680 if (2 == this.mode) {
683 // By checking against min/max we do nothing if requested index
685 if (index < Math.min(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
686 this.flipBackToIndex(index);
687 } else if (index > Math.max(this.twoPage.currentIndexL, this.twoPage.currentIndexR)) {
688 this.flipFwdToIndex(index);
695 for (i=0; i<index; i++) {
696 h = parseInt(this.getPageHeight(i)/this.reduce);
697 leafTop += h + this.padding;
699 //$('#GBcontainer').attr('scrollTop', leafTop);
700 $('#GBcontainer').animate({scrollTop: leafTop },'fast');
707 //______________________________________________________________________________
708 GnuBook.prototype.switchMode = function(mode) {
710 //console.log(' asked to switch to mode ' + mode + ' from ' + this.mode);
712 if (mode == this.mode) return;
714 if (!this.canSwitchToMode(mode)) {
719 this.removeSearchHilites();
723 this.switchToolbarMode(mode);
726 this.prepareOnePageView();
728 this.prepareTwoPageView();
733 //prepareOnePageView()
734 //______________________________________________________________________________
735 GnuBook.prototype.prepareOnePageView = function() {
737 // var startLeaf = this.displayedIndices[0];
738 var startLeaf = this.currentIndex();
740 $('#GBcontainer').empty();
741 $('#GBcontainer').css({
746 var gbPageView = $("#GBcontainer").append("<div id='GBpageview'></div>");
748 this.resizePageView();
750 this.jumpToIndex(startLeaf);
751 this.displayedIndices = [];
753 this.drawLeafsOnePage();
755 // Bind mouse handlers
756 // Disable mouse click to avoid selected/highlighted page images - bug 354239
757 gbPageView.bind('mousedown', function(e) {
760 // Special hack for IE7
761 gbPageView[0].onselectstart = function(e) { return false; };
764 // prepareTwoPageView()
765 //______________________________________________________________________________
766 GnuBook.prototype.prepareTwoPageView = function() {
767 $('#GBcontainer').empty();
768 $('#GBcontainer').css('overflow', 'auto');
771 // Add the two page view
772 $('#GBcontainer').append('<div id="GBtwopageview"></div>');
773 // Explicitly set sizes the same
774 $('#GBtwopageview').css( {
775 height: $('#GBcontainer').height(),
776 width: $('#GBcontainer').width(),
780 // We want to display two facing pages. We may be missing
781 // one side of the spread because it is the first/last leaf,
782 // foldouts, missing pages, etc
784 //var targetLeaf = this.displayedIndices[0];
785 var targetLeaf = this.firstIndex;
787 if (targetLeaf < this.firstDisplayableIndex()) {
788 targetLeaf = this.firstDisplayableIndex();
791 if (targetLeaf > this.lastDisplayableIndex()) {
792 targetLeaf = this.lastDisplayableIndex();
795 this.twoPage.currentIndexL = null;
796 this.twoPage.currentIndexR = null;
797 this.pruneUnusedImgs();
799 var currentSpreadIndices = this.getSpreadIndices(targetLeaf);
800 this.twoPage.currentIndexL = currentSpreadIndices[0];
801 this.twoPage.currentIndexR = currentSpreadIndices[1];
802 this.firstIndex = this.twoPage.currentIndexL;
804 this.calculateSpreadSize(); //sets twoPage.width, twoPage.height, and twoPage.ratio
806 var scaledWL = this.getPageWidth2UP(this.twoPage.currentIndexL);
807 var scaledWR = this.getPageWidth2UP(this.twoPage.currentIndexR);
808 var leafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
809 var leafEdgeWidthR = this.twoPage.edgeWidth - leafEdgeWidthL;
811 //console.log('idealWidth='+idealWidth+' idealHeight='+idealHeight);
812 //var bookCoverDivWidth = this.twoPage.width*2+20 + this.twoPage.edgeWidth;
814 // The width of the book cover div. The combined width of both pages, twice the width
815 // of the book cover internal padding (2*10) and the page edges
816 var bookCoverDivWidth = scaledWL + scaledWR + 2 * this.twoPage.coverInternalPadding + this.twoPage.edgeWidth;
818 // The height of the book cover div
819 var bookCoverDivHeight = this.twoPage.height + 2 * this.twoPage.coverInternalPadding;
822 // XXX explicitly set size of GBtwopageview here then use that when calculating positions
823 // GBtwopageview should have autoscroll turned off
824 $('#GBtwopageview').width(bookCoverDivWidth).height(bookCoverDivHeight);
826 // We want to minimize the unused space in two-up mode (maximize the amount of page
827 // shown). We give width to the leaf edges and these widths change (though the sum
828 // of the two remains constant) as we flip through the book. With the book
829 // cover centered and fixed in the GBcontainer div the page images will meet
830 // at the "gutter" which is generally offset from the center.
831 var middle = ($('#GBtwopageview').width() >> 1); // Middle of the page view
832 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
834 //var bookCoverDivLeft = ($('#GBcontainer').width() - bookCoverDivWidth) >> 1;
835 var bookCoverDivLeft = gutter-scaledWL-leafEdgeWidthL-this.twoPage.coverInternalPadding;
836 var bookCoverDivTop = ($('#GBtwopageview').height() - bookCoverDivHeight) >> 1;
837 //console.log('bookCoverDivWidth='+bookCoverDivWidth+' bookCoverDivHeight='+bookCoverDivHeight+ ' bookCoverDivLeft='+bookCoverDivLeft+' bookCoverDivTop='+bookCoverDivTop);
839 this.twoPageDiv = document.createElement('div');
840 $(this.twoPageDiv).attr('id', 'GBbookcover').css({
841 border: '1px solid rgb(68, 25, 17)',
842 width: bookCoverDivWidth + 'px',
843 height: bookCoverDivHeight+'px',
844 visibility: 'visible',
845 position: 'absolute',
846 backgroundColor: '#663929',
847 left: bookCoverDivLeft + 'px',
848 top: bookCoverDivTop+'px',
849 MozBorderRadiusTopleft: '7px',
850 MozBorderRadiusTopright: '7px',
851 MozBorderRadiusBottomright: '7px',
852 MozBorderRadiusBottomleft: '7px'
853 }).appendTo('#GBtwopageview');
856 var height = this.getPageHeight(this.twoPage.currentIndexR);
857 var width = this.getPageWidth(this.twoPage.currentIndexR);
858 var scaledW = this.twoPage.height*width/height;
860 this.leafEdgeR = document.createElement('div');
861 this.leafEdgeR.className = 'leafEdgeR'; // $$$ the static CSS should be moved into the .css file
862 $(this.leafEdgeR).css({
863 borderStyle: 'solid solid solid none',
864 borderColor: 'rgb(51, 51, 34)',
865 borderWidth: '1px 1px 1px 0px',
866 background: 'transparent url(' + this.imagesBaseURL + 'right_edges.png) repeat scroll 0% 0%',
867 width: leafEdgeWidthR + 'px',
868 height: this.twoPage.height-1 + 'px',
870 left: gutter+scaledW+'px',
871 top: bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
873 }).appendTo('#GBtwopageview');
875 this.leafEdgeL = document.createElement('div');
876 this.leafEdgeL.className = 'leafEdgeL';
877 $(this.leafEdgeL).css({ // $$$ static CSS should be moved to file
878 borderStyle: 'solid none solid solid',
879 borderColor: 'rgb(51, 51, 34)',
880 borderWidth: '1px 0px 1px 1px',
881 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
882 width: leafEdgeWidthL + 'px',
883 height: this.twoPage.height-1 + 'px',
884 left: bookCoverDivLeft+this.twoPage.coverInternalPadding+'px',
885 top: bookCoverDivTop+this.twoPage.coverInternalPadding+'px',
887 }).appendTo('#GBtwopageview');
891 var bookSpineDivWidth = 30;
892 bookSpineDivHeight = this.twoPage.height+20;
893 bookSpineDivLeft = ($('#GBtwopageview').width() - bookSpineDivWidth) >> 1;
894 bookSpineDivTop = ($('#GBtwopageview').height() - bookSpineDivHeight) >> 1;
896 div = document.createElement('div');
897 $(div).attr('id', 'GBbookspine').css({
898 border: '1px solid rgb(68, 25, 17)',
899 width: bookSpineDivWidth+'px',
900 height: bookSpineDivHeight+'px',
901 position: 'absolute',
902 backgroundColor: 'rgb(68, 25, 17)',
903 left: bookSpineDivLeft+'px',
904 top: bookSpineDivTop+'px'
905 }).appendTo('#GBtwopageview');
908 bookCoverDivWidth = this.twoPage.width*2;
909 bookCoverDivHeight = this.twoPage.height;
910 bookCoverDivLeft = ($('#GBcontainer').attr('clientWidth') - bookCoverDivWidth) >> 1;
911 bookCoverDivTop = ($('#GBcontainer').height() - bookCoverDivHeight) >> 1;
914 this.prepareTwoPagePopUp();
916 this.displayedIndices = [];
918 //this.indicesToDisplay=[firstLeaf, firstLeaf+1];
919 //console.log('indicesToDisplay: ' + this.indicesToDisplay[0] + ' ' + this.indicesToDisplay[1]);
921 this.drawLeafsTwoPage();
922 this.updateSearchHilites2UP();
923 this.updateToolbarZoom(this.reduce);
928 // prepareTwoPagePopUp()
930 // This function prepares the "View Page n" popup that shows while the mouse is
931 // over the left/right "stack of sheets" edges. It also binds the mouse
932 // events for these divs.
933 //______________________________________________________________________________
934 GnuBook.prototype.prepareTwoPagePopUp = function() {
936 this.twoPagePopUp = document.createElement('div');
937 $(this.twoPagePopUp).css({
938 border: '1px solid black',
940 position: 'absolute',
941 fontFamily: 'sans-serif',
944 backgroundColor: 'rgb(255, 255, 238)',
946 }).appendTo('#GBcontainer');
947 $(this.twoPagePopUp).hide();
949 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseenter', this, function(e) {
950 $(e.data.twoPagePopUp).show();
953 $(this.leafEdgeL).add(this.leafEdgeR).bind('mouseleave', this, function(e) {
954 $(e.data.twoPagePopUp).hide();
957 $(this.leafEdgeL).bind('click', this, function(e) {
959 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
960 e.data.jumpToIndex(jumpIndex);
963 $(this.leafEdgeR).bind('click', this, function(e) {
965 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
966 e.data.jumpToIndex(jumpIndex);
969 $(this.leafEdgeR).bind('mousemove', this, function(e) {
971 var jumpIndex = e.data.jumpIndexForRightEdgePageX(e.pageX);
972 $(e.data.twoPagePopUp).text('View ' + e.data.getPageName(jumpIndex));
974 // $$$ TODO: Make sure popup is positioned so that it is in view
975 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
976 $(e.data.twoPagePopUp).css({
977 left: e.pageX- $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() + 20 + 'px',
978 top: e.pageY - $('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
982 $(this.leafEdgeL).bind('mousemove', this, function(e) {
984 var jumpIndex = e.data.jumpIndexForLeftEdgePageX(e.pageX);
985 $(e.data.twoPagePopUp).text('View '+ e.data.getPageName(jumpIndex));
987 // $$$ TODO: Make sure popup is positioned so that it is in view
988 // (https://bugs.edge.launchpad.net/gnubook/+bug/327456)
989 $(e.data.twoPagePopUp).css({
990 left: e.pageX - $('#GBcontainer').offset().left + $('#GBcontainer').scrollLeft() - $(e.data.twoPagePopUp).width() - 25 + 'px',
991 top: e.pageY-$('#GBcontainer').offset().top + $('#GBcontainer').scrollTop() + 'px'
996 // calculateSpreadSize()
997 //______________________________________________________________________________
998 // Calculates 2-page spread dimensions based on this.twoPage.currentIndexL and
999 // this.twoPage.currentIndexR
1000 // This function sets this.twoPage.height, twoPage.width, and twoPage.ratio
1002 GnuBook.prototype.calculateSpreadSize = function() {
1003 console.log('calculateSpreadSize ' + this.twoPage.currentIndexL); // XXX
1005 // $$$ TODO Calculate the spread size based on the reduction factor. If we are using
1006 // fit mode we recalculate the reduction factor based on the current page sizes
1007 // and display size first.
1009 var firstIndex = this.twoPage.currentIndexL;
1010 var secondIndex = this.twoPage.currentIndexR;
1011 //console.log('first page is ' + firstIndex);
1013 // $$$ Right now we just use the ideal size
1015 if ( this.twoPage.autofit) {
1016 spreadSize = this.getIdealSpreadSize(firstIndex, secondIndex);
1018 // set based on reduction factor
1019 spreadSize = this.getSpreadSizeFromReduce(firstIndex, secondIndex, this.reduce);
1021 console.dir(spreadSize);
1024 this.twoPage.height = spreadSize.height;
1025 this.twoPage.width = spreadSize.width;
1026 this.twoPage.ratio = spreadSize.ratio;
1027 this.twoPage.edgeWidth = spreadSize.totalLeafEdgeWidth; // The combined width of both edges
1028 this.reduce = spreadSize.reduce;
1031 GnuBook.prototype.getIdealSpreadSize = function(firstIndex, secondIndex) {
1034 var canon5Dratio = 1.5;
1037 height: this.getPageHeight(firstIndex),
1038 width: this.getPageWidth(firstIndex)
1042 height: this.getPageHeight(secondIndex),
1043 width: this.getPageWidth(secondIndex)
1046 var firstIndexRatio = first.height / first.width;
1047 var secondIndexRatio = second.height / second.width;
1048 //console.log('firstIndexRatio = ' + firstIndexRatio + ' secondIndexRatio = ' + secondIndexRatio);
1050 if (Math.abs(firstIndexRatio - canon5Dratio) < Math.abs(secondIndexRatio - canon5Dratio)) {
1051 ideal.ratio = firstIndexRatio;
1052 //console.log('using firstIndexRatio ' + ratio);
1054 ideal.ratio = secondIndexRatio;
1055 //console.log('using secondIndexRatio ' + ratio);
1058 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1059 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1060 ideal.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1062 ideal.width = ($('#GBcontainer').attr('clientWidth') - 30 - ideal.totalLeafEdgeWidth)>>1;
1063 ideal.height = $('#GBcontainer').height() - 30; // $$$ why - 30? book edge width?
1064 //console.log('init idealWidth='+idealWidth+' idealHeight='+idealHeight + ' ratio='+ratio);
1066 if (ideal.height/ideal.ratio <= ideal.width) {
1068 ideal.width = parseInt(ideal.height/ideal.ratio);
1071 ideal.height = parseInt(ideal.width*ideal.ratio);
1074 // XXX check this logic with large spreads
1075 ideal.reduce = ((first.width + second.width) / 2) / ideal.width;
1080 GnuBook.prototype.getSpreadSizeFromReduce = function(firstIndex, secondIndex, reduce) {
1081 var spreadSize = {};
1082 // $$$ Scale this based on reduce?
1083 var totalLeafEdgeWidth = parseInt(this.numLeafs * 0.1);
1084 var maxLeafEdgeWidth = parseInt($('#GBcontainer').attr('clientWidth') * 0.1);
1085 spreadSize.totalLeafEdgeWidth = Math.min(totalLeafEdgeWidth, maxLeafEdgeWidth);
1087 // $$$ this isn't quite right when the pages are different sizes
1088 var nativeWidth = this.getPageWidth(firstIndex) + this.getPageWidth(secondIndex);
1089 var nativeHeight = this.getPageHeight(firstIndex) + this.getPageHeight(secondIndex);
1090 spreadSize.height = parseInt( (nativeHeight / 2) / this.reduce );
1091 spreadSize.width = parseInt( (nativeWidth / 2) / this.reduce );
1092 spreadSize.reduce = reduce;
1095 console.log('spread size: ' + firstIndex + ',' + secondIndex + ',' + reduce);
1101 //______________________________________________________________________________
1102 // Returns the currently active index.
1103 GnuBook.prototype.currentIndex = function() {
1104 // $$$ we should be cleaner with our idea of which index is active in 1up/2up
1105 if (this.mode == this.constMode1up || this.mode == this.constMode2up) {
1106 return this.firstIndex;
1108 throw 'currentIndex called for unimplemented mode ' + this.mode;
1113 //______________________________________________________________________________
1114 // Flip the right page over onto the left
1115 GnuBook.prototype.right = function() {
1116 if ('rl' != this.pageProgression) {
1126 //______________________________________________________________________________
1127 // Flip to the rightmost page
1128 GnuBook.prototype.rightmost = function() {
1129 if ('rl' != this.pageProgression) {
1137 //______________________________________________________________________________
1138 // Flip the left page over onto the right.
1139 GnuBook.prototype.left = function() {
1140 if ('rl' != this.pageProgression) {
1150 //______________________________________________________________________________
1151 // Flip to the leftmost page
1152 GnuBook.prototype.leftmost = function() {
1153 if ('rl' != this.pageProgression) {
1161 //______________________________________________________________________________
1162 GnuBook.prototype.next = function() {
1163 if (2 == this.mode) {
1165 this.flipFwdToIndex(null);
1167 if (this.firstIndex < this.lastDisplayableIndex()) {
1168 this.jumpToIndex(this.firstIndex+1);
1174 //______________________________________________________________________________
1175 GnuBook.prototype.prev = function() {
1176 if (2 == this.mode) {
1178 this.flipBackToIndex(null);
1180 if (this.firstIndex >= 1) {
1181 this.jumpToIndex(this.firstIndex-1);
1186 GnuBook.prototype.first = function() {
1187 if (2 == this.mode) {
1188 this.jumpToIndex(2);
1191 this.jumpToIndex(0);
1195 GnuBook.prototype.last = function() {
1196 if (2 == this.mode) {
1197 this.jumpToIndex(this.lastDisplayableIndex());
1200 this.jumpToIndex(this.lastDisplayableIndex());
1204 // flipBackToIndex()
1205 //______________________________________________________________________________
1206 // to flip back one spread, pass index=null
1207 GnuBook.prototype.flipBackToIndex = function(index) {
1208 if (1 == this.mode) return;
1210 var leftIndex = this.twoPage.currentIndexL;
1212 // $$$ Need to change this to be able to see first spread.
1213 // See https://bugs.launchpad.net/gnubook/+bug/296788
1214 if (leftIndex <= 2) return;
1215 if (this.animating) return;
1217 if (null != this.leafEdgeTmp) {
1218 alert('error: leafEdgeTmp should be null!');
1222 if (null == index) {
1223 index = leftIndex-2;
1225 //if (index<0) return;
1227 var previousIndices = this.getSpreadIndices(index);
1229 if (previousIndices[0] < 0 || previousIndices[1] < 0) {
1233 //console.log("flipping back to " + previousIndices[0] + ',' + previousIndices[1]);
1235 this.animating = true;
1237 if ('rl' != this.pageProgression) {
1238 // Assume LTR and we are going backward
1239 var gutter = this.prepareFlipLeftToRight(previousIndices[0], previousIndices[1]);
1240 this.flipLeftToRight(previousIndices[0], previousIndices[1], gutter);
1243 // RTL and going backward
1244 var gutter = this.prepareFlipRightToLeft(previousIndices[0], previousIndices[1]);
1245 this.flipRightToLeft(previousIndices[0], previousIndices[1], gutter);
1249 // flipLeftToRight()
1250 //______________________________________________________________________________
1251 // Flips the page on the left towards the page on the right
1252 GnuBook.prototype.flipLeftToRight = function(newIndexL, newIndexR, gutter) {
1254 var leftLeaf = this.twoPage.currentIndexL;
1256 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1257 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1258 var leafEdgeTmpW = oldLeafEdgeWidthL - newLeafEdgeWidthL;
1260 var currWidthL = this.getPageWidth2UP(leftLeaf);
1261 var newWidthL = this.getPageWidth2UP(newIndexL);
1262 var newWidthR = this.getPageWidth2UP(newIndexR);
1264 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1266 //console.log('leftEdgeTmpW ' + leafEdgeTmpW);
1267 //console.log(' gutter ' + gutter + ', scaledWL ' + scaledWL + ', newLeafEdgeWL ' + newLeafEdgeWidthL);
1269 //animation strategy:
1270 // 0. remove search highlight, if any.
1271 // 1. create a new div, called leafEdgeTmp to represent the leaf edge between the leftmost edge
1272 // of the left leaf and where the user clicked in the leaf edge.
1273 // Note that if this function was triggered by left() and not a
1274 // mouse click, the width of leafEdgeTmp is very small (zero px).
1275 // 2. animate both leafEdgeTmp to the gutter (without changing its width) and animate
1276 // leftLeaf to width=0.
1277 // 3. When step 2 is finished, animate leafEdgeTmp to right-hand side of new right leaf
1278 // (left=gutter+newWidthR) while also animating the new right leaf from width=0 to
1279 // its new full width.
1280 // 4. After step 3 is finished, do the following:
1281 // - remove leafEdgeTmp from the dom.
1282 // - resize and move the right leaf edge (leafEdgeR) to left=gutter+newWidthR
1283 // and width=twoPage.edgeWidth-newLeafEdgeWidthL.
1284 // - resize and move the left leaf edge (leafEdgeL) to left=gutter-newWidthL-newLeafEdgeWidthL
1285 // and width=newLeafEdgeWidthL.
1286 // - resize the back cover (twoPageDiv) to left=gutter-newWidthL-newLeafEdgeWidthL-10
1287 // and width=newWidthL+newWidthR+twoPage.edgeWidth+20
1288 // - move new left leaf (newIndexL) forward to zindex=2 so it can receive clicks.
1289 // - remove old left and right leafs from the dom [pruneUnusedImgs()].
1290 // - prefetch new adjacent leafs.
1291 // - set up click handlers for both new left and right leafs.
1292 // - redraw the search highlight.
1293 // - update the pagenum box and the url.
1296 var leftEdgeTmpLeft = gutter - currWidthL - leafEdgeTmpW;
1298 this.leafEdgeTmp = document.createElement('div');
1299 $(this.leafEdgeTmp).css({
1300 borderStyle: 'solid none solid solid',
1301 borderColor: 'rgb(51, 51, 34)',
1302 borderWidth: '1px 0px 1px 1px',
1303 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1304 width: leafEdgeTmpW + 'px',
1305 height: this.twoPage.height-1 + 'px',
1306 left: leftEdgeTmpLeft + 'px',
1308 position: 'absolute',
1310 }).appendTo('#GBtwopageview');
1312 //$(this.leafEdgeL).css('width', newLeafEdgeWidthL+'px');
1313 $(this.leafEdgeL).css({
1314 width: newLeafEdgeWidthL+'px',
1315 left: gutter-currWidthL-newLeafEdgeWidthL+'px'
1318 // Left gets the offset of the current left leaf from the document
1319 var left = $(this.prefetchedImgs[leftLeaf]).offset().left;
1320 // $$$ This seems very similar to the gutter. May be able to consolidate the logic.
1321 var right = $('#GBtwopageview').attr('clientWidth')-left-$(this.prefetchedImgs[leftLeaf]).width()+$('#GBtwopageview').offset().left-2+'px';
1322 // We change the left leaf to right positioning
1323 $(this.prefetchedImgs[leftLeaf]).css({
1328 left = $(this.prefetchedImgs[leftLeaf]).offset().left - $('#book_div_1').offset().left;
1330 right = left+$(this.prefetchedImgs[leftLeaf]).width()+'px';
1332 $(this.leafEdgeTmp).animate({left: gutter}, this.flipSpeed, 'easeInSine');
1333 //$(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, 'slow', 'easeInSine');
1337 this.removeSearchHilites();
1339 //console.log('animating leafLeaf ' + leftLeaf + ' to 0px');
1340 $(this.prefetchedImgs[leftLeaf]).animate({width: '0px'}, self.flipSpeed, 'easeInSine', function() {
1342 //console.log(' and now leafEdgeTmp to left: gutter+newWidthR ' + (gutter + newWidthR));
1343 $(self.leafEdgeTmp).animate({left: gutter+newWidthR+'px'}, self.flipSpeed, 'easeOutSine');
1345 //console.log(' animating newIndexR ' + newIndexR + ' to ' + newWidthR + ' from ' + $(self.prefetchedImgs[newIndexR]).width());
1346 $(self.prefetchedImgs[newIndexR]).animate({width: newWidthR+'px'}, self.flipSpeed, 'easeOutSine', function() {
1347 $(self.prefetchedImgs[newIndexL]).css('zIndex', 2);
1349 $(self.leafEdgeR).css({
1350 // Moves the right leaf edge
1351 width: self.twoPage.edgeWidth-newLeafEdgeWidthL+'px',
1352 left: gutter+newWidthR+'px'
1355 $(self.leafEdgeL).css({
1356 // Moves and resizes the left leaf edge
1357 width: newLeafEdgeWidthL+'px',
1358 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1362 $(self.twoPageDiv).css({
1363 // Resizes the brown border div
1364 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1365 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1368 $(self.leafEdgeTmp).remove();
1369 self.leafEdgeTmp = null;
1371 self.twoPage.currentIndexL = newIndexL;
1372 self.twoPage.currentIndexR = newIndexR;
1373 self.firstIndex = self.twoPage.currentIndexL;
1374 self.displayedIndices = [newIndexL, newIndexR];
1375 self.setClickHandlers();
1376 self.pruneUnusedImgs();
1378 self.animating = false;
1380 self.updateSearchHilites2UP();
1381 self.updatePageNumBox2UP();
1383 if (self.animationFinishedCallback) {
1384 self.animationFinishedCallback();
1385 self.animationFinishedCallback = null;
1393 //______________________________________________________________________________
1394 // Whether we flip left or right is dependent on the page progression
1395 // to flip forward one spread, pass index=null
1396 GnuBook.prototype.flipFwdToIndex = function(index) {
1398 if (this.animating) return;
1400 if (null != this.leafEdgeTmp) {
1401 alert('error: leafEdgeTmp should be null!');
1405 if (null == index) {
1406 index = this.twoPage.currentIndexR+2; // $$$ assumes indices are continuous
1408 if (index > this.lastDisplayableIndex()) return;
1410 this.animating = true;
1412 var nextIndices = this.getSpreadIndices(index);
1414 //console.log('flipfwd to indices ' + nextIndices[0] + ',' + nextIndices[1]);
1416 if ('rl' != this.pageProgression) {
1417 // We did not specify RTL
1418 var gutter = this.prepareFlipRightToLeft(nextIndices[0], nextIndices[1]);
1419 this.flipRightToLeft(nextIndices[0], nextIndices[1], gutter);
1422 var gutter = this.prepareFlipLeftToRight(nextIndices[0], nextIndices[1]);
1423 this.flipLeftToRight(nextIndices[0], nextIndices[1], gutter);
1427 // flipRightToLeft(nextL, nextR, gutter)
1428 // $$$ better not to have to pass gutter in
1429 //______________________________________________________________________________
1430 // Flip from left to right and show the nextL and nextR indices on those sides
1431 GnuBook.prototype.flipRightToLeft = function(newIndexL, newIndexR, gutter) {
1432 var oldLeafEdgeWidthL = this.leafEdgeWidth(this.twoPage.currentIndexL);
1433 var oldLeafEdgeWidthR = this.twoPage.edgeWidth-oldLeafEdgeWidthL;
1434 var newLeafEdgeWidthL = this.leafEdgeWidth(newIndexL);
1435 var newLeafEdgeWidthR = this.twoPage.edgeWidth-newLeafEdgeWidthL;
1437 var leafEdgeTmpW = oldLeafEdgeWidthR - newLeafEdgeWidthR;
1439 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1441 var scaledW = this.getPageWidth2UP(this.twoPage.currentIndexR);
1443 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1444 var currGutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1447 console.log('R->L middle(' + middle +') currGutter(' + currGutter + ') gutter(' + gutter + ')');
1449 this.leafEdgeTmp = document.createElement('div');
1450 $(this.leafEdgeTmp).css({
1451 borderStyle: 'solid none solid solid',
1452 borderColor: 'rgb(51, 51, 34)',
1453 borderWidth: '1px 0px 1px 1px',
1454 background: 'transparent url(' + this.imagesBaseURL + 'left_edges.png) repeat scroll 0% 0%',
1455 width: leafEdgeTmpW + 'px',
1456 height: this.twoPage.height-1 + 'px',
1457 left: currGutter+scaledW+'px',
1459 position: 'absolute',
1461 }).appendTo('#GBtwopageview');
1463 //var scaledWR = this.getPageWidth2UP(newIndexR); // $$$ should be current instead?
1464 //var scaledWL = this.getPageWidth2UP(newIndexL); // $$$ should be current instead?
1466 var currWidthL = this.getPageWidth2UP(this.twoPage.currentIndexL);
1467 var currWidthR = this.getPageWidth2UP(this.twoPage.currentIndexR);
1468 var newWidthL = this.getPageWidth2UP(newIndexL);
1469 var newWidthR = this.getPageWidth2UP(newIndexR);
1471 $(this.leafEdgeR).css({width: newLeafEdgeWidthR+'px', left: gutter+newWidthR+'px' });
1473 var self = this; // closure-tastic!
1475 var speed = this.flipSpeed;
1477 this.removeSearchHilites();
1479 $(this.leafEdgeTmp).animate({left: gutter}, speed, 'easeInSine');
1480 $(this.prefetchedImgs[this.twoPage.currentIndexR]).animate({width: '0px'}, speed, 'easeInSine', function() {
1481 $(self.leafEdgeTmp).animate({left: gutter-newWidthL-leafEdgeTmpW+'px'}, speed, 'easeOutSine');
1482 $(self.prefetchedImgs[newIndexL]).animate({width: newWidthL+'px'}, speed, 'easeOutSine', function() {
1483 $(self.prefetchedImgs[newIndexR]).css('zIndex', 2);
1485 $(self.leafEdgeL).css({
1486 width: newLeafEdgeWidthL+'px',
1487 left: gutter-newWidthL-newLeafEdgeWidthL+'px'
1490 $(self.twoPageDiv).css({
1491 width: newWidthL+newWidthR+self.twoPage.edgeWidth+20+'px',
1492 left: gutter-newWidthL-newLeafEdgeWidthL-10+'px'
1495 $(self.leafEdgeTmp).remove();
1496 self.leafEdgeTmp = null;
1498 self.twoPage.currentIndexL = newIndexL;
1499 self.twoPage.currentIndexR = newIndexR;
1500 self.firstIndex = self.twoPage.currentIndexL;
1501 self.displayedIndices = [newIndexL, newIndexR];
1502 self.setClickHandlers();
1503 self.pruneUnusedImgs();
1505 self.animating = false;
1508 self.updateSearchHilites2UP();
1509 self.updatePageNumBox2UP();
1511 if (self.animationFinishedCallback) {
1512 self.animationFinishedCallback();
1513 self.animationFinishedCallback = null;
1520 //______________________________________________________________________________
1521 GnuBook.prototype.setClickHandlers = function() {
1523 // $$$ TODO don't set again if already set
1524 $(this.prefetchedImgs[this.twoPage.currentIndexL]).click(function() {
1529 $(this.prefetchedImgs[this.twoPage.currentIndexR]).click(function() {
1537 //______________________________________________________________________________
1538 GnuBook.prototype.prefetchImg = function(index) {
1539 if (undefined == this.prefetchedImgs[index]) {
1540 //console.log('prefetching ' + index);
1541 var img = document.createElement("img");
1542 img.src = this.getPageURI(index);
1543 this.prefetchedImgs[index] = img;
1548 // prepareFlipLeftToRight()
1550 //______________________________________________________________________________
1552 // Prepare to flip the left page towards the right. This corresponds to moving
1553 // backward when the page progression is left to right.
1554 GnuBook.prototype.prepareFlipLeftToRight = function(prevL, prevR) {
1556 //console.log(' preparing left->right for ' + prevL + ',' + prevR);
1558 this.prefetchImg(prevL);
1559 this.prefetchImg(prevR);
1561 var height = this.getPageHeight(prevL);
1562 var width = this.getPageWidth(prevL);
1563 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1564 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1565 var scaledW = this.twoPage.height*width/height;
1567 // The gutter is the dividing line between the left and right pages.
1568 // It is offset from the middle to create the illusion of thickness to the pages
1569 var gutter = middle + this.gutterOffsetForIndex(prevL);
1572 console.log(' gutter for ' + prevL + ' is ' + gutter);
1573 //console.log(' prevL.left: ' + (gutter - scaledW) + 'px');
1574 //console.log(' changing prevL ' + prevL + ' to left: ' + (gutter-scaledW) + ' width: ' + scaledW);
1576 $(this.prefetchedImgs[prevL]).css({
1577 position: 'absolute',
1578 /*right: middle+'px',*/
1579 left: gutter-scaledW+'px',
1582 backgroundColor: 'rgb(234, 226, 205)',
1583 height: this.twoPage.height,
1584 width: scaledW+'px',
1585 borderRight: '1px solid black',
1589 $('#GBtwopageview').append(this.prefetchedImgs[prevL]);
1591 //console.log(' changing prevR ' + prevR + ' to left: ' + gutter + ' width: 0');
1593 $(this.prefetchedImgs[prevR]).css({
1594 position: 'absolute',
1598 backgroundColor: 'rgb(234, 226, 205)',
1599 height: this.twoPage.height,
1601 borderLeft: '1px solid black',
1605 $('#GBtwopageview').append(this.prefetchedImgs[prevR]);
1612 // XXXmang we're adding an extra pixel in the middle
1613 // prepareFlipRightToLeft()
1614 //______________________________________________________________________________
1615 GnuBook.prototype.prepareFlipRightToLeft = function(nextL, nextR) {
1617 //console.log(' preparing left<-right for ' + nextL + ',' + nextR);
1619 this.prefetchImg(nextL);
1620 this.prefetchImg(nextR);
1622 var height = this.getPageHeight(nextR);
1623 var width = this.getPageWidth(nextR);
1624 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1625 var top = ($('#GBtwopageview').height() - this.twoPage.height) >> 1;
1626 var scaledW = this.twoPage.height*width/height;
1628 var gutter = middle + this.gutterOffsetForIndex(nextL);
1630 console.log('right to left to %d gutter is %d', nextL, gutter); // XXX
1632 //console.log(' prepareRTL changing nextR ' + nextR + ' to left: ' + gutter);
1633 $(this.prefetchedImgs[nextR]).css({
1634 position: 'absolute',
1637 backgroundColor: 'rgb(234, 226, 205)',
1638 height: this.twoPage.height,
1639 width: scaledW+'px',
1640 borderLeft: '1px solid black',
1644 $('#GBtwopageview').append(this.prefetchedImgs[nextR]);
1646 height = this.getPageHeight(nextL);
1647 width = this.getPageWidth(nextL);
1648 scaledW = this.twoPage.height*width/height;
1650 //console.log(' prepareRTL changing nextL ' + nextL + ' to right: ' + $('#GBcontainer').width()-gutter);
1651 $(this.prefetchedImgs[nextL]).css({
1652 position: 'absolute',
1653 right: $('#GBtwopageview').attr('clientWidth')-gutter+'px',
1655 backgroundColor: 'rgb(234, 226, 205)',
1656 height: this.twoPage.height,
1658 borderRight: '1px solid black',
1662 $('#GBtwopageview').append(this.prefetchedImgs[nextL]);
1668 // getNextLeafs() -- NOT RTL AWARE
1669 //______________________________________________________________________________
1670 // GnuBook.prototype.getNextLeafs = function(o) {
1671 // //TODO: we might have two left or two right leafs in a row (damaged book)
1672 // //For now, assume that leafs are contiguous.
1674 // //return [this.twoPage.currentIndexL+2, this.twoPage.currentIndexL+3];
1675 // o.L = this.twoPage.currentIndexL+2;
1676 // o.R = this.twoPage.currentIndexL+3;
1679 // getprevLeafs() -- NOT RTL AWARE
1680 //______________________________________________________________________________
1681 // GnuBook.prototype.getPrevLeafs = function(o) {
1682 // //TODO: we might have two left or two right leafs in a row (damaged book)
1683 // //For now, assume that leafs are contiguous.
1685 // //return [this.twoPage.currentIndexL-2, this.twoPage.currentIndexL-1];
1686 // o.L = this.twoPage.currentIndexL-2;
1687 // o.R = this.twoPage.currentIndexL-1;
1690 // pruneUnusedImgs()
1691 //______________________________________________________________________________
1692 GnuBook.prototype.pruneUnusedImgs = function() {
1693 //console.log('current: ' + this.twoPage.currentIndexL + ' ' + this.twoPage.currentIndexR);
1694 for (var key in this.prefetchedImgs) {
1695 //console.log('key is ' + key);
1696 if ((key != this.twoPage.currentIndexL) && (key != this.twoPage.currentIndexR)) {
1697 //console.log('removing key '+ key);
1698 $(this.prefetchedImgs[key]).remove();
1700 if ((key < this.twoPage.currentIndexL-4) || (key > this.twoPage.currentIndexR+4)) {
1701 //console.log('deleting key '+ key);
1702 delete this.prefetchedImgs[key];
1708 //______________________________________________________________________________
1709 GnuBook.prototype.prefetch = function() {
1711 var lim = this.twoPage.currentIndexL-4;
1713 lim = Math.max(lim, 0);
1714 for (i = lim; i < this.twoPage.currentIndexL; i++) {
1715 this.prefetchImg(i);
1718 if (this.numLeafs > (this.twoPage.currentIndexR+1)) {
1719 lim = Math.min(this.twoPage.currentIndexR+4, this.numLeafs-1);
1720 for (i=this.twoPage.currentIndexR+1; i<=lim; i++) {
1721 this.prefetchImg(i);
1726 // getPageWidth2UP()
1727 //______________________________________________________________________________
1728 GnuBook.prototype.getPageWidth2UP = function(index) {
1729 var height = this.getPageHeight(index);
1730 var width = this.getPageWidth(index);
1731 return Math.floor(this.twoPage.height*width/height);
1735 //______________________________________________________________________________
1736 GnuBook.prototype.search = function(term) {
1737 $('#GnuBookSearchScript').remove();
1738 var script = document.createElement("script");
1739 script.setAttribute('id', 'GnuBookSearchScript');
1740 script.setAttribute("type", "text/javascript");
1741 script.setAttribute("src", 'http://'+this.server+'/GnuBook/flipbook_search_gb.php?url='+escape(this.bookPath + '_djvu.xml')+'&term='+term+'&format=XML&callback=gb.GBSearchCallback');
1742 document.getElementsByTagName('head')[0].appendChild(script);
1743 $('#GnuBookSearchResults').html('Searching...');
1746 // GBSearchCallback()
1747 //______________________________________________________________________________
1748 GnuBook.prototype.GBSearchCallback = function(txt) {
1750 if (jQuery.browser.msie) {
1751 var dom=new ActiveXObject("Microsoft.XMLDOM");
1755 var parser = new DOMParser();
1756 var dom = parser.parseFromString(txt, "text/xml");
1759 $('#GnuBookSearchResults').empty();
1760 $('#GnuBookSearchResults').append('<ul>');
1762 for (var key in this.searchResults) {
1763 if (null != this.searchResults[key].div) {
1764 $(this.searchResults[key].div).remove();
1766 delete this.searchResults[key];
1769 var pages = dom.getElementsByTagName('PAGE');
1771 if (0 == pages.length) {
1772 // $$$ it would be nice to echo the (sanitized) search result here
1773 $('#GnuBookSearchResults').append('<li>No search results found</li>');
1775 for (var i = 0; i < pages.length; i++){
1776 //console.log(pages[i].getAttribute('file').substr(1) +'-'+ parseInt(pages[i].getAttribute('file').substr(1), 10));
1779 var re = new RegExp (/_(\d{4})/);
1780 var reMatch = re.exec(pages[i].getAttribute('file'));
1781 var index = parseInt(reMatch[1], 10);
1782 //var index = parseInt(pages[i].getAttribute('file').substr(1), 10);
1784 var children = pages[i].childNodes;
1786 for (var j=0; j<children.length; j++) {
1787 //console.log(j + ' - ' + children[j].nodeName);
1788 //console.log(children[j].firstChild.nodeValue);
1789 if ('CONTEXT' == children[j].nodeName) {
1790 context += children[j].firstChild.nodeValue;
1791 } else if ('WORD' == children[j].nodeName) {
1792 context += '<b>'+children[j].firstChild.nodeValue+'</b>';
1794 var index = this.leafNumToIndex(index);
1795 if (null != index) {
1796 //coordinates are [left, bottom, right, top, [baseline]]
1797 //we'll skip baseline for now...
1798 var coords = children[j].getAttribute('coords').split(',',4);
1799 if (4 == coords.length) {
1800 this.searchResults[index] = {'l':coords[0], 'b':coords[1], 'r':coords[2], 't':coords[3], 'div':null};
1805 var pageName = this.getPageName(index);
1806 //TODO: remove hardcoded instance name
1807 $('#GnuBookSearchResults').append('<li><b><a href="javascript:gb.jumpToIndex('+index+');">' + pageName + '</a></b> - ' + context + '</li>');
1810 $('#GnuBookSearchResults').append('</ul>');
1812 this.updateSearchHilites();
1815 // updateSearchHilites()
1816 //______________________________________________________________________________
1817 GnuBook.prototype.updateSearchHilites = function() {
1818 if (2 == this.mode) {
1819 this.updateSearchHilites2UP();
1821 this.updateSearchHilites1UP();
1825 // showSearchHilites1UP()
1826 //______________________________________________________________________________
1827 GnuBook.prototype.updateSearchHilites1UP = function() {
1829 for (var key in this.searchResults) {
1831 if (-1 != jQuery.inArray(parseInt(key), this.displayedIndices)) {
1832 var result = this.searchResults[key];
1833 if(null == result.div) {
1834 result.div = document.createElement('div');
1835 $(result.div).attr('className', 'GnuBookSearchHilite').appendTo('#pagediv'+key);
1836 //console.log('appending ' + key);
1839 width: (result.r-result.l)/this.reduce + 'px',
1840 height: (result.b-result.t)/this.reduce + 'px',
1841 left: (result.l)/this.reduce + 'px',
1842 top: (result.t)/this.reduce +'px'
1846 //console.log(key + ' not displayed');
1847 this.searchResults[key].div=null;
1852 // showSearchHilites2UP()
1853 //______________________________________________________________________________
1854 GnuBook.prototype.updateSearchHilites2UP = function() {
1856 var middle = ($('#GBtwopageview').attr('clientWidth') >> 1);
1858 for (var key in this.searchResults) {
1859 key = parseInt(key, 10);
1860 if (-1 != jQuery.inArray(key, this.displayedIndices)) {
1861 var result = this.searchResults[key];
1862 if(null == result.div) {
1863 result.div = document.createElement('div');
1864 $(result.div).attr('className', 'GnuBookSearchHilite').css('zIndex', 3).appendTo('#GBtwopageview');
1865 //console.log('appending ' + key);
1868 var height = this.getPageHeight(key);
1869 var width = this.getPageWidth(key)
1870 var reduce = this.twoPage.height/height;
1871 var scaledW = parseInt(width*reduce);
1873 var gutter = middle + this.gutterOffsetForIndex(this.twoPage.currentIndexL);
1875 if ('L' == this.getPageSide(key)) {
1876 var pageL = gutter-scaledW;
1880 var pageT = ($('#GBtwopagview').height() - this.twoPage.height) >> 1;
1883 width: (result.r-result.l)*reduce + 'px',
1884 height: (result.b-result.t)*reduce + 'px',
1885 left: pageL+(result.l)*reduce + 'px',
1886 top: pageT+(result.t)*reduce +'px'
1890 //console.log(key + ' not displayed');
1891 if (null != this.searchResults[key].div) {
1892 //console.log('removing ' + key);
1893 $(this.searchResults[key].div).remove();
1895 this.searchResults[key].div=null;
1900 // removeSearchHilites()
1901 //______________________________________________________________________________
1902 GnuBook.prototype.removeSearchHilites = function() {
1903 for (var key in this.searchResults) {
1904 if (null != this.searchResults[key].div) {
1905 $(this.searchResults[key].div).remove();
1906 this.searchResults[key].div=null;
1912 //______________________________________________________________________________
1913 GnuBook.prototype.showEmbedCode = function() {
1914 if (null != this.embedPopup) { // check if already showing
1918 this.embedPopup = document.createElement("div");
1919 $(this.embedPopup).css({
1920 position: 'absolute',
1922 left: ($('#GBcontainer').attr('clientWidth')-400)/2 + 'px',
1925 border: "3px double #999999",
1927 backgroundColor: "#fff"
1928 }).appendTo('#GnuBook');
1930 htmlStr = '<p style="text-align:center;"><b>Embed Bookreader in your blog!</b></p>';
1931 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>';
1932 htmlStr += '<p>Embed Code: <input type="text" size="40" value="' + this.getEmbedCode() + '"></p>';
1933 htmlStr += '<p style="text-align:center;"><a href="" onclick="gb.embedPopup = null; $(this.parentNode.parentNode).remove(); return false">Close popup</a></p>';
1935 this.embedPopup.innerHTML = htmlStr;
1936 $(this.embedPopup).find('input').bind('click', function() {
1942 //______________________________________________________________________________
1943 GnuBook.prototype.autoToggle = function() {
1945 var bComingFrom1up = false;
1946 if (2 != this.mode) {
1947 bComingFrom1up = true;
1952 if (null == this.autoTimer) {
1953 this.flipSpeed = 2000;
1955 // $$$ Draw events currently cause layout problems when they occur during animation.
1956 // There is a specific problem when changing from 1-up immediately to autoplay in RTL so
1957 // we workaround for now by not triggering immediate animation in that case.
1958 // See https://bugs.launchpad.net/gnubook/+bug/328327
1959 if (('rl' == this.pageProgression) && bComingFrom1up) {
1960 // don't flip immediately -- wait until timer fires
1963 this.flipFwdToIndex();
1966 $('#GBtoolbar .play').hide();
1967 $('#GBtoolbar .pause').show();
1968 this.autoTimer=setInterval(function(){
1969 if (self.animating) {return;}
1971 if (Math.max(self.twoPage.currentIndexL, self.twoPage.currentIndexR) >= self.lastDisplayableIndex()) {
1972 self.flipBackToIndex(1); // $$$ really what we want?
1974 self.flipFwdToIndex();
1983 //______________________________________________________________________________
1984 GnuBook.prototype.autoStop = function() {
1985 if (null != this.autoTimer) {
1986 clearInterval(this.autoTimer);
1987 this.flipSpeed = 'fast';
1988 $('#GBtoolbar .pause').hide();
1989 $('#GBtoolbar .play').show();
1990 this.autoTimer = null;
1994 // keyboardNavigationIsDisabled(event)
1995 // - returns true if keyboard navigation should be disabled for the event
1996 //______________________________________________________________________________
1997 GnuBook.prototype.keyboardNavigationIsDisabled = function(event) {
1998 if (event.target.tagName == "INPUT") {
2004 // gutterOffsetForIndex
2005 //______________________________________________________________________________
2007 // Returns the gutter offset for the spread containing the given index.
2008 // This function supports RTL
2009 GnuBook.prototype.gutterOffsetForIndex = function(pindex) {
2011 // To find the offset of the gutter from the middle we calculate our percentage distance
2012 // through the book (0..1), remap to (-0.5..0.5) and multiply by the total page edge width
2013 var offset = parseInt(((pindex / this.numLeafs) - 0.5) * this.twoPage.edgeWidth);
2015 // But then again for RTL it's the opposite
2016 if ('rl' == this.pageProgression) {
2024 //______________________________________________________________________________
2025 // Returns the width of the leaf edge div for the page with index given
2026 GnuBook.prototype.leafEdgeWidth = function(pindex) {
2027 // $$$ could there be single pixel rounding errors for L vs R?
2028 if ((this.getPageSide(pindex) == 'L') && (this.pageProgression != 'rl')) {
2029 return parseInt( (pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2031 return parseInt( (1 - pindex/this.numLeafs) * this.twoPage.edgeWidth + 0.5);
2035 // jumpIndexForLeftEdgePageX
2036 //______________________________________________________________________________
2037 // Returns the target jump leaf given a page coordinate (inside the left page edge div)
2038 GnuBook.prototype.jumpIndexForLeftEdgePageX = function(pageX) {
2039 if ('rl' != this.pageProgression) {
2040 // LTR - flipping backward
2041 var jumpIndex = this.twoPage.currentIndexL - ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2043 // browser may have resized the div due to font size change -- see https://bugs.launchpad.net/gnubook/+bug/333570
2044 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexL - 2);
2048 var jumpIndex = this.twoPage.currentIndexL + ($(this.leafEdgeL).offset().left + $(this.leafEdgeL).width() - pageX) * 10;
2049 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexL + 2, this.lastDisplayableIndex());
2054 // jumpIndexForRightEdgePageX
2055 //______________________________________________________________________________
2056 // Returns the target jump leaf given a page coordinate (inside the right page edge div)
2057 GnuBook.prototype.jumpIndexForRightEdgePageX = function(pageX) {
2058 if ('rl' != this.pageProgression) {
2060 var jumpIndex = this.twoPage.currentIndexR + (pageX - $(this.leafEdgeR).offset().left) * 10;
2061 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.twoPage.currentIndexR + 2, this.lastDisplayableIndex());
2064 var jumpIndex = this.twoPage.currentIndexR - (pageX - $(this.leafEdgeR).offset().left) * 10;
2065 jumpIndex = GnuBook.util.clamp(Math.round(jumpIndex), this.firstDisplayableIndex(), this.twoPage.currentIndexR - 2);
2070 GnuBook.prototype.initToolbar = function(mode, ui) {
2072 $("#GnuBook").append("<div id='GBtoolbar'><span style='float:left;'>"
2073 + "<a class='GBicon logo rollover' href='" + this.logoURL + "'> </a>"
2074 + " <button class='GBicon rollover zoom_out' onclick='gb.zoom(-1); return false;'/>"
2075 + "<button class='GBicon rollover zoom_in' onclick='gb.zoom(1); return false;'/>"
2076 + " <span class='label'>Zoom: <span id='GBzoom'>"+parseInt(100/this.reduce)+"</span>%</span>"
2077 + " <button class='GBicon rollover one_page_mode' onclick='gb.switchMode(1); return false;'/>"
2078 + " <button class='GBicon rollover two_page_mode' onclick='gb.switchMode(2); return false;'/>"
2079 + " <a class='GBblack title' href='"+this.bookUrl+"' target='_blank'>"+this.shortTitle(50)+"</a>"
2082 if (ui == "embed") {
2083 $("#GnuBook a.logo").attr("target","_blank");
2086 // $$$ turn this into a member variable
2087 var jToolbar = $('#GBtoolbar'); // j prefix indicates jQuery object
2089 // We build in mode 2
2090 jToolbar.append("<span id='GBtoolbarbuttons' style='float: right'>"
2091 + "<button class='GBicon rollover embed' />"
2092 + "<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>"
2093 + "<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>"
2094 + "<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>"
2095 + "<button class='GBicon rollover play' /><button class='GBicon rollover pause' style='display: none' /></span>");
2097 this.bindToolbarNavHandlers(jToolbar);
2099 // Setup tooltips -- later we could load these from a file for i18n
2100 var titles = { '.logo': 'Go to Archive.org',
2101 '.zoom_in': 'Zoom in',
2102 '.zoom_out': 'Zoom out',
2103 '.one_page_mode': 'One-page view',
2104 '.two_page_mode': 'Two-page view',
2105 '.embed': 'Embed bookreader',
2106 '.book_left': 'Flip left',
2107 '.book_right': 'Flip right',
2108 '.book_up': 'Page up',
2109 '.book_down': 'Page down',
2112 '.book_top': 'First page',
2113 '.book_bottom': 'Last page'
2115 if ('rl' == this.pageProgression) {
2116 titles['.book_leftmost'] = 'Last page';
2117 titles['.book_rightmost'] = 'First page';
2119 titles['.book_leftmost'] = 'First page';
2120 titles['.book_rightmost'] = 'Last page';
2123 for (var icon in titles) {
2124 jToolbar.find(icon).attr('title', titles[icon]);
2127 // Hide mode buttons and autoplay if 2up is not available
2128 // $$$ if we end up with more than two modes we should show the applicable buttons
2129 if ( !this.canSwitchToMode(this.constMode2up) ) {
2130 jToolbar.find('.one_page_mode, .two_page_mode, .play, .pause').hide();
2133 // Switch to requested mode -- binds other click handlers
2134 this.switchToolbarMode(mode);
2139 // switchToolbarMode
2140 //______________________________________________________________________________
2141 // Update the toolbar for the given mode (changes navigation buttons)
2142 // $$$ we should soon split the toolbar out into its own module
2143 GnuBook.prototype.switchToolbarMode = function(mode) {
2146 $('#GBtoolbar .GBtoolbarmode2').hide();
2147 $('#GBtoolbar .GBtoolbarmode1').show().css('display', 'inline');
2150 $('#GBtoolbar .GBtoolbarmode1').hide();
2151 $('#GBtoolbar .GBtoolbarmode2').show().css('display', 'inline');
2155 // bindToolbarNavHandlers
2156 //______________________________________________________________________________
2157 // Binds the toolbar handlers
2158 GnuBook.prototype.bindToolbarNavHandlers = function(jToolbar) {
2160 jToolbar.find('.book_left').bind('click', function(e) {
2165 jToolbar.find('.book_right').bind('click', function(e) {
2170 jToolbar.find('.book_up').bind('click', function(e) {
2175 jToolbar.find('.book_down').bind('click', function(e) {
2180 jToolbar.find('.embed').bind('click', function(e) {
2185 jToolbar.find('.play').bind('click', function(e) {
2190 jToolbar.find('.pause').bind('click', function(e) {
2195 jToolbar.find('.book_top').bind('click', function(e) {
2200 jToolbar.find('.book_bottom').bind('click', function(e) {
2205 jToolbar.find('.book_leftmost').bind('click', function(e) {
2210 jToolbar.find('.book_rightmost').bind('click', function(e) {
2216 // updateToolbarZoom(reduce)
2217 //______________________________________________________________________________
2218 // Update the displayed zoom factor based on reduction factor
2219 GnuBook.prototype.updateToolbarZoom = function(reduce) {
2220 // $$$ TODO: Move toolbar to it's own object/plugin
2221 $('#GBzoom').text(parseInt(100/reduce));
2224 // firstDisplayableIndex
2225 //______________________________________________________________________________
2226 // Returns the index of the first visible page, dependent on the mode.
2227 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2228 // this function when we can as part of https://bugs.launchpad.net/gnubook/+bug/296788
2229 GnuBook.prototype.firstDisplayableIndex = function() {
2230 if (this.mode == 0) {
2233 return 1; // $$$ we assume there are enough pages... we need logic for very short books
2237 // lastDisplayableIndex
2238 //______________________________________________________________________________
2239 // Returns the index of the last visible page, dependent on the mode.
2240 // $$$ Currently we cannot display the front/back cover in 2-up and will need to update
2241 // this function when we can as pa rt of https://bugs.launchpad.net/gnubook/+bug/296788
2242 GnuBook.prototype.lastDisplayableIndex = function() {
2243 if (this.mode == 2) {
2244 if (this.lastDisplayableIndex2up === null) {
2245 // Calculate and cache
2246 var candidate = this.numLeafs - 1;
2247 for ( ; candidate >= 0; candidate--) {
2248 var spreadIndices = this.getSpreadIndices(candidate);
2249 if (Math.max(spreadIndices[0], spreadIndices[1]) < (this.numLeafs - 1)) {
2253 this.lastDisplayableIndex2up = candidate;
2255 return this.lastDisplayableIndex2up;
2257 return this.numLeafs - 1;
2261 // shortTitle(maximumCharacters)
2263 // Returns a shortened version of the title with the maximum number of characters
2264 GnuBook.prototype.shortTitle = function(maximumCharacters) {
2265 if (this.bookTitle.length < maximumCharacters) {
2266 return this.bookTitle;
2269 var title = this.bookTitle.substr(0, maximumCharacters - 3);
2276 // Parameter related functions
2278 // updateFromParams(params)
2280 // Update ourselves from the params object.
2282 // e.g. this.updateFromParams(this.paramsFromFragment(window.location.hash))
2283 GnuBook.prototype.updateFromParams = function(params) {
2284 if ('undefined' != typeof(params.mode)) {
2285 this.switchMode(params.mode);
2288 // $$$ process /search
2289 // $$$ process /zoom
2291 // We only respect page if index is not set
2292 if ('undefined' != typeof(params.index)) {
2293 if (params.index != this.currentIndex()) {
2294 this.jumpToIndex(params.index);
2296 } else if ('undefined' != typeof(params.page)) {
2297 // $$$ this assumes page numbers are unique
2298 if (params.page != this.getPageNum(this.currentIndex())) {
2299 this.jumpToPage(params.page);
2303 // $$$ process /region
2304 // $$$ process /highlight
2307 // paramsFromFragment(urlFragment)
2309 // Returns a object with configuration parametes from a URL fragment.
2311 // E.g paramsFromFragment(window.location.hash)
2312 GnuBook.prototype.paramsFromFragment = function(urlFragment) {
2313 // URL fragment syntax specification: http://openlibrary.org/dev/docs/bookurls
2317 // For convenience we allow an initial # character (as from window.location.hash)
2318 // but don't require it
2319 if (urlFragment.substr(0,1) == '#') {
2320 urlFragment = urlFragment.substr(1);
2323 // Simple #nn syntax
2324 var oldStyleLeafNum = parseInt( /^\d+$/.exec(urlFragment) );
2325 if ( !isNaN(oldStyleLeafNum) ) {
2326 params.index = oldStyleLeafNum;
2328 // Done processing if using old-style syntax
2332 // Split into key-value pairs
2333 var urlArray = urlFragment.split('/');
2335 for (var i = 0; i < urlArray.length; i += 2) {
2336 urlHash[urlArray[i]] = urlArray[i+1];
2340 if ('1up' == urlHash['mode']) {
2341 params.mode = this.constMode1up;
2342 } else if ('2up' == urlHash['mode']) {
2343 params.mode = this.constMode2up;
2347 if ('undefined' != typeof(urlHash['page'])) {
2348 // page was set -- may not be int
2349 params.page = urlHash['page'];
2352 // $$$ process /region
2353 // $$$ process /search
2354 // $$$ process /highlight
2359 // paramsFromCurrent()
2361 // Create a params object from the current parameters.
2362 GnuBook.prototype.paramsFromCurrent = function() {
2366 var pageNum = this.getPageNum(this.currentIndex());
2367 if ((pageNum === 0) || pageNum) {
2368 params.page = pageNum;
2371 params.index = this.currentIndex();
2372 params.mode = this.mode;
2381 // fragmentFromParams(params)
2383 // Create a fragment string from the params object.
2384 // See http://openlibrary.org/dev/docs/bookurls for an explanation of the fragment syntax.
2385 GnuBook.prototype.fragmentFromParams = function(params) {
2386 var separator = '/';
2390 if ('undefined' != typeof(params.page)) {
2391 fragments.push('page', params.page);
2393 // Don't have page numbering -- use index instead
2394 fragments.push('page', 'n' + params.index);
2402 if ('undefined' != typeof(params.mode)) {
2403 if (params.mode == this.constMode1up) {
2404 fragments.push('mode', '1up');
2405 } else if (params.mode == this.constMode2up) {
2406 fragments.push('mode', '2up');
2408 throw 'fragmentFromParams called with unknown mode ' + params.mode;
2412 return fragments.join(separator);
2415 // getPageIndex(pageNum)
2417 // Returns the *highest* index the given page number, or undefined
2418 GnuBook.prototype.getPageIndex = function(pageNum) {
2419 var pageIndices = this.getPageIndices(pageNum);
2421 if (pageIndices.length > 0) {
2422 return pageIndices[pageIndices.length - 1];
2428 // getPageIndices(pageNum)
2430 // Returns an array (possibly empty) of the indices with the given page number
2431 GnuBook.prototype.getPageIndices = function(pageNum) {
2434 // Check for special "nXX" page number
2435 if (pageNum.slice(0,1) == 'n') {
2437 var pageIntStr = pageNum.slice(1, pageNum.length);
2438 var pageIndex = parseInt(pageIntStr);
2439 indices.append(pageIndex);
2442 // Do nothing... will run through page names and see if one matches
2447 for (i=0; i<this.numLeafs; i++) {
2448 if (this.getPageNum(i) == pageNum) {
2456 // getPageName(index)
2458 // Returns the name of the page as it should be displayed in the user interface
2459 GnuBook.prototype.getPageName = function(index) {
2460 return 'Page ' + this.getPageNum(index);
2463 // updateLocationHash
2465 // Update the location hash from the current parameters. Call this instead of manually
2466 // using window.location.replace
2467 GnuBook.prototype.updateLocationHash = function() {
2468 var newHash = '#' + this.fragmentFromParams(this.paramsFromCurrent());
2469 window.location.replace(newHash);
2471 // This is the variable checked in the timer. Only user-generated changes
2472 // to the URL will trigger the event.
2473 this.oldLocationHash = newHash;
2476 // startLocationPolling
2478 // Starts polling of window.location to see hash fragment changes
2479 GnuBook.prototype.startLocationPolling = function() {
2480 var self = this; // remember who I am
2481 self.oldLocationHash = window.location.hash;
2483 if (this.locationPollId) {
2484 clearInterval(this.locationPollID);
2485 this.locationPollId = null;
2488 this.locationPollId = setInterval(function() {
2489 var newHash = window.location.hash;
2490 if (newHash != self.oldLocationHash) {
2491 if (newHash != self.oldUserHash) { // Only process new user hash once
2492 //console.log('url change detected ' + self.oldLocationHash + " -> " + newHash);
2494 // Queue change if animating
2495 if (self.animating) {
2497 self.animationFinishedCallback = function() {
2498 self.updateFromParams(self.paramsFromFragment(newHash));
2500 } else { // update immediately
2501 self.updateFromParams(self.paramsFromFragment(newHash));
2503 self.oldUserHash = newHash;
2511 // Returns a URL for an embedded version of the current book
2512 GnuBook.prototype.getEmbedURL = function() {
2513 // We could generate a URL hash fragment here but for now we just leave at defaults
2514 return 'http://' + window.location.host + '/stream/'+this.bookId + '?ui=embed';
2519 // Returns the embed code HTML fragment suitable for copy and paste
2520 GnuBook.prototype.getEmbedCode = function() {
2521 return "<iframe src='" + this.getEmbedURL() + "' width='480px' height='430px'></iframe>";
2526 // Returns true if we can switch to the requested mode
2527 GnuBook.prototype.canSwitchToMode = function(mode) {
2528 if (mode == this.constMode2up) {
2529 // check there are enough pages to display
2530 // $$$ this is a workaround for the mis-feature that we can't display
2531 // short books in 2up mode
2532 if (this.numLeafs < 6) {
2540 // Library functions
2542 clamp: function(value, min, max) {
2543 return Math.min(Math.max(value, min), max);